xref: /linux/net/ipv4/fib_frontend.c (revision 72ebc685bca99f466ef35600b5263d1c21c790d9)
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: FIB frontend.
8  *
9  * Authors:	Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
10  */
11 
12 #include <linux/module.h>
13 #include <linux/uaccess.h>
14 #include <linux/bitops.h>
15 #include <linux/capability.h>
16 #include <linux/types.h>
17 #include <linux/kernel.h>
18 #include <linux/mm.h>
19 #include <linux/string.h>
20 #include <linux/socket.h>
21 #include <linux/sockios.h>
22 #include <linux/errno.h>
23 #include <linux/in.h>
24 #include <linux/inet.h>
25 #include <linux/inetdevice.h>
26 #include <linux/netdevice.h>
27 #include <linux/if_addr.h>
28 #include <linux/if_arp.h>
29 #include <linux/skbuff.h>
30 #include <linux/cache.h>
31 #include <linux/init.h>
32 #include <linux/list.h>
33 #include <linux/slab.h>
34 
35 #include <net/flow.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/arp.h>
43 #include <net/ip_fib.h>
44 #include <net/nexthop.h>
45 #include <net/rtnetlink.h>
46 #include <net/xfrm.h>
47 #include <net/l3mdev.h>
48 #include <net/lwtunnel.h>
49 #include <trace/events/fib.h>
50 
51 #ifndef CONFIG_IP_MULTIPLE_TABLES
52 
53 static int __net_init fib4_rules_init(struct net *net)
54 {
55 	struct fib_table *local_table, *main_table;
56 
57 	main_table  = fib_trie_table(RT_TABLE_MAIN, NULL);
58 	if (!main_table)
59 		return -ENOMEM;
60 
61 	local_table = fib_trie_table(RT_TABLE_LOCAL, main_table);
62 	if (!local_table)
63 		goto fail;
64 
65 	hlist_add_head_rcu(&local_table->tb_hlist,
66 				&net->ipv4.fib_table_hash[TABLE_LOCAL_INDEX]);
67 	hlist_add_head_rcu(&main_table->tb_hlist,
68 				&net->ipv4.fib_table_hash[TABLE_MAIN_INDEX]);
69 	return 0;
70 
71 fail:
72 	fib_free_table(main_table);
73 	return -ENOMEM;
74 }
75 #else
76 
77 struct fib_table *fib_new_table(struct net *net, u32 id)
78 {
79 	struct fib_table *tb, *new_tb, *alias = NULL;
80 	unsigned int h;
81 
82 	if (id == 0)
83 		id = RT_TABLE_MAIN;
84 	tb = fib_get_table(net, id);
85 	if (tb)
86 		return tb;
87 
88 	if (!check_net(net))
89 		return NULL;
90 
91 	if (id == RT_TABLE_LOCAL && !net->ipv4.fib_has_custom_rules)
92 		alias = fib_new_table(net, RT_TABLE_MAIN);
93 
94 	new_tb = fib_trie_table(id, alias);
95 	if (!new_tb)
96 		return NULL;
97 
98 	spin_lock(&net->ipv4.fib_table_hash_lock);
99 
100 	tb = fib_get_table(net, id);
101 	if (tb) {
102 		spin_unlock(&net->ipv4.fib_table_hash_lock);
103 		fib_free_table(new_tb);
104 		return tb;
105 	}
106 
107 	tb = new_tb;
108 
109 	switch (id) {
110 	case RT_TABLE_MAIN:
111 		rcu_assign_pointer(net->ipv4.fib_main, tb);
112 		break;
113 	case RT_TABLE_DEFAULT:
114 		rcu_assign_pointer(net->ipv4.fib_default, tb);
115 		break;
116 	default:
117 		break;
118 	}
119 
120 	h = id & (FIB_TABLE_HASHSZ - 1);
121 	hlist_add_head_rcu(&tb->tb_hlist, &net->ipv4.fib_table_hash[h]);
122 
123 	spin_unlock(&net->ipv4.fib_table_hash_lock);
124 
125 	return tb;
126 }
127 EXPORT_SYMBOL_GPL(fib_new_table);
128 
129 struct fib_table *fib_get_table(struct net *net, u32 id)
130 {
131 	struct fib_table *tb = NULL;
132 	struct hlist_head *head;
133 	unsigned int h;
134 
135 	if (id == 0)
136 		id = RT_TABLE_MAIN;
137 	h = id & (FIB_TABLE_HASHSZ - 1);
138 	head = &net->ipv4.fib_table_hash[h];
139 
140 	/* fib_table is not destroyed until ip_fib_net_exit()
141 	 * except for the merged main/local table.
142 	 * fib_unmerge() is called under RTNL, so other readers
143 	 * under RTNL (e.g. fib_flush(), fib_info_notify_update())
144 	 * can safely traverse the list with rcu_dereference_raw().
145 	 */
146 	hlist_for_each_entry_rcu(tb, head, tb_hlist, true)
147 		if (tb->tb_id == id)
148 			break;
149 
150 	return tb;
151 }
152 #endif /* CONFIG_IP_MULTIPLE_TABLES */
153 
154 static void fib_replace_table(struct net *net, struct fib_table *old,
155 			      struct fib_table *new)
156 {
157 #ifdef CONFIG_IP_MULTIPLE_TABLES
158 	switch (new->tb_id) {
159 	case RT_TABLE_MAIN:
160 		rcu_assign_pointer(net->ipv4.fib_main, new);
161 		break;
162 	case RT_TABLE_DEFAULT:
163 		rcu_assign_pointer(net->ipv4.fib_default, new);
164 		break;
165 	default:
166 		break;
167 	}
168 
169 #endif
170 	/* replace the old table in the hlist */
171 	hlist_replace_rcu(&old->tb_hlist, &new->tb_hlist);
172 }
173 
174 int fib_unmerge(struct net *net)
175 {
176 	struct fib_table *old, *new, *main_table;
177 
178 	/* attempt to fetch local table if it has been allocated */
179 	old = fib_get_table(net, RT_TABLE_LOCAL);
180 	if (!old)
181 		return 0;
182 
183 	new = fib_trie_unmerge(old);
184 	if (!new)
185 		return -ENOMEM;
186 
187 	/* table is already unmerged */
188 	if (new == old)
189 		return 0;
190 
191 	/* replace merged table with clean table */
192 	fib_replace_table(net, old, new);
193 	fib_free_table(old);
194 
195 	/* attempt to fetch main table if it has been allocated */
196 	main_table = fib_get_table(net, RT_TABLE_MAIN);
197 	if (!main_table)
198 		return 0;
199 
200 	/* flush local entries from main table */
201 	fib_table_flush_external(main_table);
202 
203 	return 0;
204 }
205 
206 void fib_flush(struct net *net)
207 {
208 	int flushed = 0;
209 	unsigned int h;
210 
211 	for (h = 0; h < FIB_TABLE_HASHSZ; h++) {
212 		struct hlist_head *head = &net->ipv4.fib_table_hash[h];
213 		struct fib_table *tb;
214 
215 		hlist_for_each_entry_rcu(tb, head, tb_hlist, true)
216 			flushed += fib_table_flush(net, tb, false);
217 	}
218 
219 	if (flushed)
220 		rt_cache_flush(net);
221 }
222 
223 /*
224  * Find address type as if only "dev" was present in the system. If
225  * on_dev is NULL then all interfaces are taken into consideration.
226  */
227 static inline unsigned int __inet_dev_addr_type(struct net *net,
228 						const struct net_device *dev,
229 						__be32 addr, u32 tb_id)
230 {
231 	struct flowi4		fl4 = { .daddr = addr };
232 	struct fib_result	res;
233 	unsigned int ret = RTN_BROADCAST;
234 	struct fib_table *table;
235 
236 	if (ipv4_is_zeronet(addr) || ipv4_is_lbcast(addr))
237 		return RTN_BROADCAST;
238 	if (ipv4_is_multicast(addr))
239 		return RTN_MULTICAST;
240 
241 	rcu_read_lock();
242 
243 	table = fib_get_table(net, tb_id);
244 	if (table) {
245 		ret = RTN_UNICAST;
246 		if (!fib_table_lookup(net, table, &fl4, &res,
247 				      FIB_LOOKUP_NOREF)) {
248 			struct fib_nh_common *nhc = fib_info_nhc(res.fi, 0);
249 
250 			if (!dev || dev == nhc->nhc_dev)
251 				ret = res.type;
252 		}
253 	}
254 
255 	rcu_read_unlock();
256 	return ret;
257 }
258 
259 unsigned int inet_addr_type_table(struct net *net, __be32 addr, u32 tb_id)
260 {
261 	return __inet_dev_addr_type(net, NULL, addr, tb_id);
262 }
263 EXPORT_SYMBOL(inet_addr_type_table);
264 
265 unsigned int inet_addr_type(struct net *net, __be32 addr)
266 {
267 	return __inet_dev_addr_type(net, NULL, addr, RT_TABLE_LOCAL);
268 }
269 EXPORT_SYMBOL(inet_addr_type);
270 
271 unsigned int inet_dev_addr_type(struct net *net, const struct net_device *dev,
272 				__be32 addr)
273 {
274 	u32 rt_table = l3mdev_fib_table(dev) ? : RT_TABLE_LOCAL;
275 
276 	return __inet_dev_addr_type(net, dev, addr, rt_table);
277 }
278 EXPORT_SYMBOL(inet_dev_addr_type);
279 
280 /* inet_addr_type with dev == NULL but using the table from a dev
281  * if one is associated
282  */
283 unsigned int inet_addr_type_dev_table(struct net *net,
284 				      const struct net_device *dev,
285 				      __be32 addr)
286 {
287 	u32 rt_table = l3mdev_fib_table(dev) ? : RT_TABLE_LOCAL;
288 
289 	return __inet_dev_addr_type(net, NULL, addr, rt_table);
290 }
291 EXPORT_SYMBOL(inet_addr_type_dev_table);
292 
293 __be32 fib_compute_spec_dst(struct sk_buff *skb)
294 {
295 	struct net_device *dev = skb->dev;
296 	struct in_device *in_dev;
297 	struct fib_result res;
298 	struct rtable *rt;
299 	struct net *net;
300 	int scope;
301 
302 	rt = skb_rtable(skb);
303 	if ((rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST | RTCF_LOCAL)) ==
304 	    RTCF_LOCAL)
305 		return ip_hdr(skb)->daddr;
306 
307 	in_dev = __in_dev_get_rcu(dev);
308 
309 	net = dev_net(dev);
310 
311 	scope = RT_SCOPE_UNIVERSE;
312 	if (!ipv4_is_zeronet(ip_hdr(skb)->saddr)) {
313 		bool vmark = in_dev && IN_DEV_SRC_VMARK(in_dev);
314 		struct flowi4 fl4 = {
315 			.flowi4_iif = LOOPBACK_IFINDEX,
316 			.flowi4_l3mdev = l3mdev_master_ifindex_rcu(dev),
317 			.daddr = ip_hdr(skb)->saddr,
318 			.flowi4_dscp = ip4h_dscp(ip_hdr(skb)),
319 			.flowi4_scope = scope,
320 			.flowi4_mark = vmark ? skb->mark : 0,
321 		};
322 		if (!fib_lookup(net, &fl4, &res, 0))
323 			return fib_result_prefsrc(net, &res);
324 	} else {
325 		scope = RT_SCOPE_LINK;
326 	}
327 
328 	return inet_select_addr(dev, ip_hdr(skb)->saddr, scope);
329 }
330 
331 bool fib_info_nh_uses_dev(struct fib_info *fi, const struct net_device *dev)
332 {
333 	bool dev_match = false;
334 #ifdef CONFIG_IP_ROUTE_MULTIPATH
335 	if (unlikely(fi->nh)) {
336 		dev_match = nexthop_uses_dev(fi->nh, dev);
337 	} else {
338 		int ret;
339 
340 		for (ret = 0; ret < fib_info_num_path(fi); ret++) {
341 			const struct fib_nh_common *nhc = fib_info_nhc(fi, ret);
342 
343 			if (nhc_l3mdev_matches_dev(nhc, dev)) {
344 				dev_match = true;
345 				break;
346 			}
347 		}
348 	}
349 #else
350 	if (fib_info_nhc(fi, 0)->nhc_dev == dev)
351 		dev_match = true;
352 #endif
353 
354 	return dev_match;
355 }
356 EXPORT_SYMBOL_GPL(fib_info_nh_uses_dev);
357 
358 /* Given (packet source, input interface) and optional (dst, oif, tos):
359  * - (main) check, that source is valid i.e. not broadcast or our local
360  *   address.
361  * - figure out what "logical" interface this packet arrived
362  *   and calculate "specific destination" address.
363  * - check, that packet arrived from expected physical interface.
364  * called with rcu_read_lock()
365  */
366 static int __fib_validate_source(struct sk_buff *skb, __be32 src, __be32 dst,
367 				 dscp_t dscp, int oif, struct net_device *dev,
368 				 int rpf, struct in_device *idev, u32 *itag)
369 {
370 	struct net *net = dev_net(dev);
371 	enum skb_drop_reason reason;
372 	struct flow_keys flkeys;
373 	int ret, no_addr;
374 	struct fib_result res;
375 	struct flowi4 fl4;
376 	bool dev_match;
377 
378 	fl4.flowi4_oif = 0;
379 	fl4.flowi4_l3mdev = l3mdev_master_ifindex_rcu(dev);
380 	fl4.flowi4_iif = oif ? : LOOPBACK_IFINDEX;
381 	fl4.daddr = src;
382 	fl4.saddr = dst;
383 	fl4.flowi4_dscp = dscp;
384 	fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
385 	fl4.flowi4_tun_key.tun_id = 0;
386 	fl4.flowi4_flags = 0;
387 	fl4.flowi4_uid = sock_net_uid(net, NULL);
388 	fl4.flowi4_multipath_hash = 0;
389 
390 	no_addr = idev->ifa_list == NULL;
391 
392 	fl4.flowi4_mark = IN_DEV_SRC_VMARK(idev) ? skb->mark : 0;
393 	if (!fib4_rules_early_flow_dissect(net, skb, &fl4, &flkeys)) {
394 		fl4.flowi4_proto = 0;
395 		fl4.fl4_sport = 0;
396 		fl4.fl4_dport = 0;
397 	} else {
398 		swap(fl4.fl4_sport, fl4.fl4_dport);
399 	}
400 
401 	if (fib_lookup(net, &fl4, &res, 0))
402 		goto last_resort;
403 	if (res.type != RTN_UNICAST) {
404 		if (res.type != RTN_LOCAL) {
405 			reason = SKB_DROP_REASON_IP_INVALID_SOURCE;
406 			goto e_inval;
407 		} else if (!IN_DEV_ACCEPT_LOCAL(idev)) {
408 			reason = SKB_DROP_REASON_IP_LOCAL_SOURCE;
409 			goto e_inval;
410 		}
411 	}
412 	fib_combine_itag(itag, &res);
413 
414 	dev_match = fib_info_nh_uses_dev(res.fi, dev);
415 	/* This is not common, loopback packets retain skb_dst so normally they
416 	 * would not even hit this slow path.
417 	 */
418 	dev_match = dev_match || (res.type == RTN_LOCAL &&
419 				  dev == net->loopback_dev);
420 	if (dev_match) {
421 		ret = FIB_RES_NHC(res)->nhc_scope >= RT_SCOPE_HOST;
422 		return ret;
423 	}
424 	if (no_addr)
425 		goto last_resort;
426 	if (rpf == 1)
427 		goto e_rpf;
428 	fl4.flowi4_oif = dev->ifindex;
429 
430 	ret = 0;
431 	if (fib_lookup(net, &fl4, &res, FIB_LOOKUP_IGNORE_LINKSTATE) == 0) {
432 		if (res.type == RTN_UNICAST)
433 			ret = FIB_RES_NHC(res)->nhc_scope >= RT_SCOPE_HOST;
434 	}
435 	return ret;
436 
437 last_resort:
438 	if (rpf)
439 		goto e_rpf;
440 	*itag = 0;
441 	return 0;
442 
443 e_inval:
444 	return -reason;
445 e_rpf:
446 	return -SKB_DROP_REASON_IP_RPFILTER;
447 }
448 
449 /* Ignore rp_filter for packets protected by IPsec. */
450 int fib_validate_source(struct sk_buff *skb, __be32 src, __be32 dst,
451 			dscp_t dscp, int oif, struct net_device *dev,
452 			struct in_device *idev, u32 *itag)
453 {
454 	int r = secpath_exists(skb) ? 0 : IN_DEV_RPFILTER(idev);
455 	struct net *net = dev_net(dev);
456 
457 	if (!r && !fib_num_tclassid_users(net) &&
458 	    (dev->ifindex != oif || !IN_DEV_TX_REDIRECTS(idev))) {
459 		if (IN_DEV_ACCEPT_LOCAL(idev))
460 			goto ok;
461 		/* with custom local routes in place, checking local addresses
462 		 * only will be too optimistic, with custom rules, checking
463 		 * local addresses only can be too strict, e.g. due to vrf
464 		 */
465 		if (net->ipv4.fib_has_custom_local_routes ||
466 		    fib4_has_custom_rules(net))
467 			goto full_check;
468 		/* Within the same container, it is regarded as a martian source,
469 		 * and the same host but different containers are not.
470 		 */
471 		if (inet_lookup_ifaddr_rcu(net, src))
472 			return -SKB_DROP_REASON_IP_LOCAL_SOURCE;
473 
474 ok:
475 		*itag = 0;
476 		return 0;
477 	}
478 
479 full_check:
480 	return __fib_validate_source(skb, src, dst, dscp, oif, dev, r, idev,
481 				     itag);
482 }
483 
484 static inline __be32 sk_extract_addr(struct sockaddr *addr)
485 {
486 	return ((struct sockaddr_in *) addr)->sin_addr.s_addr;
487 }
488 
489 static int put_rtax(struct nlattr *mx, int len, int type, u32 value)
490 {
491 	struct nlattr *nla;
492 
493 	nla = (struct nlattr *) ((char *) mx + len);
494 	nla->nla_type = type;
495 	nla->nla_len = nla_attr_size(4);
496 	*(u32 *) nla_data(nla) = value;
497 
498 	return len + nla_total_size(4);
499 }
500 
501 static int rtentry_to_fib_config(struct net *net, int cmd, struct rtentry *rt,
502 				 struct fib_config *cfg)
503 {
504 	__be32 addr;
505 	int plen;
506 
507 	memset(cfg, 0, sizeof(*cfg));
508 	cfg->fc_nlinfo.nl_net = net;
509 
510 	if (rt->rt_dst.sa_family != AF_INET)
511 		return -EAFNOSUPPORT;
512 
513 	/*
514 	 * Check mask for validity:
515 	 * a) it must be contiguous.
516 	 * b) destination must have all host bits clear.
517 	 * c) if application forgot to set correct family (AF_INET),
518 	 *    reject request unless it is absolutely clear i.e.
519 	 *    both family and mask are zero.
520 	 */
521 	plen = 32;
522 	addr = sk_extract_addr(&rt->rt_dst);
523 	if (!(rt->rt_flags & RTF_HOST)) {
524 		__be32 mask = sk_extract_addr(&rt->rt_genmask);
525 
526 		if (rt->rt_genmask.sa_family != AF_INET) {
527 			if (mask || rt->rt_genmask.sa_family)
528 				return -EAFNOSUPPORT;
529 		}
530 
531 		if (bad_mask(mask, addr))
532 			return -EINVAL;
533 
534 		plen = inet_mask_len(mask);
535 	}
536 
537 	cfg->fc_dst_len = plen;
538 	cfg->fc_dst = addr;
539 
540 	if (cmd != SIOCDELRT) {
541 		cfg->fc_nlflags = NLM_F_CREATE;
542 		cfg->fc_protocol = RTPROT_BOOT;
543 	}
544 
545 	if (rt->rt_metric)
546 		cfg->fc_priority = rt->rt_metric - 1;
547 
548 	if (rt->rt_flags & RTF_REJECT) {
549 		cfg->fc_scope = RT_SCOPE_HOST;
550 		cfg->fc_type = RTN_UNREACHABLE;
551 		return 0;
552 	}
553 
554 	cfg->fc_scope = RT_SCOPE_NOWHERE;
555 	cfg->fc_type = RTN_UNICAST;
556 
557 	if (rt->rt_dev) {
558 		char *colon;
559 		struct net_device *dev;
560 		char devname[IFNAMSIZ];
561 
562 		if (copy_from_user(devname, rt->rt_dev, IFNAMSIZ-1))
563 			return -EFAULT;
564 
565 		devname[IFNAMSIZ-1] = 0;
566 		colon = strchr(devname, ':');
567 		if (colon)
568 			*colon = 0;
569 		dev = __dev_get_by_name(net, devname);
570 		if (!dev)
571 			return -ENODEV;
572 		cfg->fc_oif = dev->ifindex;
573 		cfg->fc_table = l3mdev_fib_table(dev);
574 		if (colon) {
575 			const struct in_ifaddr *ifa;
576 			struct in_device *in_dev;
577 
578 			in_dev = __in_dev_get_rtnl_net(dev);
579 			if (!in_dev)
580 				return -ENODEV;
581 
582 			*colon = ':';
583 
584 			in_dev_for_each_ifa_rtnl_net(net, ifa, in_dev) {
585 				if (strcmp(ifa->ifa_label, devname) == 0)
586 					break;
587 			}
588 
589 			if (!ifa)
590 				return -ENODEV;
591 			cfg->fc_prefsrc = ifa->ifa_local;
592 		}
593 	}
594 
595 	addr = sk_extract_addr(&rt->rt_gateway);
596 	if (rt->rt_gateway.sa_family == AF_INET && addr) {
597 		unsigned int addr_type;
598 
599 		cfg->fc_gw4 = addr;
600 		cfg->fc_gw_family = AF_INET;
601 		addr_type = inet_addr_type_table(net, addr, cfg->fc_table);
602 		if (rt->rt_flags & RTF_GATEWAY &&
603 		    addr_type == RTN_UNICAST)
604 			cfg->fc_scope = RT_SCOPE_UNIVERSE;
605 	}
606 
607 	if (!cfg->fc_table)
608 		cfg->fc_table = RT_TABLE_MAIN;
609 
610 	if (cmd == SIOCDELRT)
611 		return 0;
612 
613 	if (rt->rt_flags & RTF_GATEWAY && !cfg->fc_gw_family)
614 		return -EINVAL;
615 
616 	if (cfg->fc_scope == RT_SCOPE_NOWHERE)
617 		cfg->fc_scope = RT_SCOPE_LINK;
618 
619 	if (rt->rt_flags & (RTF_MTU | RTF_WINDOW | RTF_IRTT)) {
620 		struct nlattr *mx;
621 		int len = 0;
622 
623 		mx = kcalloc(3, nla_total_size(4), GFP_KERNEL);
624 		if (!mx)
625 			return -ENOMEM;
626 
627 		if (rt->rt_flags & RTF_MTU)
628 			len = put_rtax(mx, len, RTAX_ADVMSS, rt->rt_mtu - 40);
629 
630 		if (rt->rt_flags & RTF_WINDOW)
631 			len = put_rtax(mx, len, RTAX_WINDOW, rt->rt_window);
632 
633 		if (rt->rt_flags & RTF_IRTT)
634 			len = put_rtax(mx, len, RTAX_RTT, rt->rt_irtt << 3);
635 
636 		cfg->fc_mx = mx;
637 		cfg->fc_mx_len = len;
638 	}
639 
640 	return 0;
641 }
642 
643 /*
644  * Handle IP routing ioctl calls.
645  * These are used to manipulate the routing tables
646  */
647 int ip_rt_ioctl(struct net *net, unsigned int cmd, struct rtentry *rt)
648 {
649 	struct fib_config cfg;
650 	int err;
651 
652 	switch (cmd) {
653 	case SIOCADDRT:		/* Add a route */
654 	case SIOCDELRT:		/* Delete a route */
655 		if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
656 			return -EPERM;
657 
658 		rtnl_net_lock(net);
659 		err = rtentry_to_fib_config(net, cmd, rt, &cfg);
660 		if (err == 0) {
661 			struct fib_table *tb;
662 
663 			if (cmd == SIOCDELRT) {
664 				tb = fib_get_table(net, cfg.fc_table);
665 				if (tb)
666 					err = fib_table_delete(net, tb, &cfg,
667 							       NULL);
668 				else
669 					err = -ESRCH;
670 			} else {
671 				tb = fib_new_table(net, cfg.fc_table);
672 				if (tb)
673 					err = fib_table_insert(net, tb,
674 							       &cfg, NULL);
675 				else
676 					err = -ENOBUFS;
677 			}
678 
679 			/* allocated by rtentry_to_fib_config() */
680 			kfree(cfg.fc_mx);
681 		}
682 		rtnl_net_unlock(net);
683 		return err;
684 	}
685 	return -EINVAL;
686 }
687 
688 const struct nla_policy rtm_ipv4_policy[RTA_MAX + 1] = {
689 	[RTA_UNSPEC]		= { .strict_start_type = RTA_DPORT + 1 },
690 	[RTA_DST]		= { .type = NLA_U32 },
691 	[RTA_SRC]		= { .type = NLA_U32 },
692 	[RTA_IIF]		= { .type = NLA_U32 },
693 	[RTA_OIF]		= { .type = NLA_U32 },
694 	[RTA_GATEWAY]		= { .type = NLA_U32 },
695 	[RTA_PRIORITY]		= { .type = NLA_U32 },
696 	[RTA_PREFSRC]		= { .type = NLA_U32 },
697 	[RTA_METRICS]		= { .type = NLA_NESTED },
698 	[RTA_MULTIPATH]		= { .len = sizeof(struct rtnexthop) },
699 	[RTA_FLOW]		= { .type = NLA_U32 },
700 	[RTA_ENCAP_TYPE]	= { .type = NLA_U16 },
701 	[RTA_ENCAP]		= { .type = NLA_NESTED },
702 	[RTA_UID]		= { .type = NLA_U32 },
703 	[RTA_MARK]		= { .type = NLA_U32 },
704 	[RTA_TABLE]		= { .type = NLA_U32 },
705 	[RTA_IP_PROTO]		= { .type = NLA_U8 },
706 	[RTA_SPORT]		= { .type = NLA_U16 },
707 	[RTA_DPORT]		= { .type = NLA_U16 },
708 	[RTA_NH_ID]		= { .type = NLA_U32 },
709 };
710 
711 int fib_gw_from_via(struct fib_config *cfg, struct nlattr *nla,
712 		    struct netlink_ext_ack *extack)
713 {
714 	struct rtvia *via;
715 	int alen;
716 
717 	if (nla_len(nla) < offsetof(struct rtvia, rtvia_addr)) {
718 		NL_SET_ERR_MSG(extack, "Invalid attribute length for RTA_VIA");
719 		return -EINVAL;
720 	}
721 
722 	via = nla_data(nla);
723 	alen = nla_len(nla) - offsetof(struct rtvia, rtvia_addr);
724 
725 	switch (via->rtvia_family) {
726 	case AF_INET:
727 		if (alen != sizeof(__be32)) {
728 			NL_SET_ERR_MSG(extack, "Invalid IPv4 address in RTA_VIA");
729 			return -EINVAL;
730 		}
731 		cfg->fc_gw_family = AF_INET;
732 		cfg->fc_gw4 = *((__be32 *)via->rtvia_addr);
733 		break;
734 	case AF_INET6:
735 #if IS_ENABLED(CONFIG_IPV6)
736 		if (alen != sizeof(struct in6_addr)) {
737 			NL_SET_ERR_MSG(extack, "Invalid IPv6 address in RTA_VIA");
738 			return -EINVAL;
739 		}
740 		cfg->fc_gw_family = AF_INET6;
741 		cfg->fc_gw6 = *((struct in6_addr *)via->rtvia_addr);
742 #else
743 		NL_SET_ERR_MSG(extack, "IPv6 support not enabled in kernel");
744 		return -EINVAL;
745 #endif
746 		break;
747 	default:
748 		NL_SET_ERR_MSG(extack, "Unsupported address family in RTA_VIA");
749 		return -EINVAL;
750 	}
751 
752 	return 0;
753 }
754 
755 static int rtm_to_fib_config(struct net *net, struct sk_buff *skb,
756 			     struct nlmsghdr *nlh, struct fib_config *cfg,
757 			     struct netlink_ext_ack *extack)
758 {
759 	bool has_gw = false, has_via = false;
760 	struct nlattr *attr;
761 	int err, remaining;
762 	struct rtmsg *rtm;
763 
764 	err = nlmsg_validate_deprecated(nlh, sizeof(*rtm), RTA_MAX,
765 					rtm_ipv4_policy, extack);
766 	if (err < 0)
767 		goto errout;
768 
769 	memset(cfg, 0, sizeof(*cfg));
770 
771 	rtm = nlmsg_data(nlh);
772 
773 	if (!inet_validate_dscp(rtm->rtm_tos)) {
774 		NL_SET_ERR_MSG(extack,
775 			       "Invalid dsfield (tos): ECN bits must be 0");
776 		err = -EINVAL;
777 		goto errout;
778 	}
779 	cfg->fc_dscp = inet_dsfield_to_dscp(rtm->rtm_tos);
780 
781 	cfg->fc_dst_len = rtm->rtm_dst_len;
782 	cfg->fc_table = rtm->rtm_table;
783 	cfg->fc_protocol = rtm->rtm_protocol;
784 	cfg->fc_scope = rtm->rtm_scope;
785 	cfg->fc_type = rtm->rtm_type;
786 	cfg->fc_flags = rtm->rtm_flags;
787 	cfg->fc_nlflags = nlh->nlmsg_flags;
788 
789 	cfg->fc_nlinfo.portid = NETLINK_CB(skb).portid;
790 	cfg->fc_nlinfo.nlh = nlh;
791 	cfg->fc_nlinfo.nl_net = net;
792 
793 	if (cfg->fc_type > RTN_MAX) {
794 		NL_SET_ERR_MSG(extack, "Invalid route type");
795 		err = -EINVAL;
796 		goto errout;
797 	}
798 
799 	nlmsg_for_each_attr(attr, nlh, sizeof(struct rtmsg), remaining) {
800 		switch (nla_type(attr)) {
801 		case RTA_DST:
802 			cfg->fc_dst = nla_get_be32(attr);
803 			break;
804 		case RTA_OIF:
805 			cfg->fc_oif = nla_get_u32(attr);
806 			break;
807 		case RTA_GATEWAY:
808 			has_gw = true;
809 			cfg->fc_gw4 = nla_get_be32(attr);
810 			if (cfg->fc_gw4)
811 				cfg->fc_gw_family = AF_INET;
812 			break;
813 		case RTA_VIA:
814 			has_via = true;
815 			err = fib_gw_from_via(cfg, attr, extack);
816 			if (err)
817 				goto errout;
818 			break;
819 		case RTA_PRIORITY:
820 			cfg->fc_priority = nla_get_u32(attr);
821 			break;
822 		case RTA_PREFSRC:
823 			cfg->fc_prefsrc = nla_get_be32(attr);
824 			break;
825 		case RTA_METRICS:
826 			cfg->fc_mx = nla_data(attr);
827 			cfg->fc_mx_len = nla_len(attr);
828 			break;
829 		case RTA_MULTIPATH:
830 			err = lwtunnel_valid_encap_type_attr(nla_data(attr),
831 							     nla_len(attr),
832 							     extack);
833 			if (err < 0)
834 				goto errout;
835 			cfg->fc_mp = nla_data(attr);
836 			cfg->fc_mp_len = nla_len(attr);
837 			break;
838 		case RTA_FLOW:
839 			cfg->fc_flow = nla_get_u32(attr);
840 			break;
841 		case RTA_TABLE:
842 			cfg->fc_table = nla_get_u32(attr);
843 			break;
844 		case RTA_ENCAP:
845 			cfg->fc_encap = attr;
846 			break;
847 		case RTA_ENCAP_TYPE:
848 			cfg->fc_encap_type = nla_get_u16(attr);
849 			err = lwtunnel_valid_encap_type(cfg->fc_encap_type,
850 							extack);
851 			if (err < 0)
852 				goto errout;
853 			break;
854 		case RTA_NH_ID:
855 			cfg->fc_nh_id = nla_get_u32(attr);
856 			break;
857 		}
858 	}
859 
860 	if (cfg->fc_dst_len > 32) {
861 		NL_SET_ERR_MSG(extack, "Invalid prefix length");
862 		err = -EINVAL;
863 		goto errout;
864 	}
865 
866 	if (cfg->fc_dst_len < 32 && (ntohl(cfg->fc_dst) << cfg->fc_dst_len)) {
867 		NL_SET_ERR_MSG(extack, "Invalid prefix for given prefix length");
868 		err = -EINVAL;
869 		goto errout;
870 	}
871 
872 	if (cfg->fc_nh_id) {
873 		if (cfg->fc_oif || cfg->fc_gw_family ||
874 		    cfg->fc_encap || cfg->fc_mp) {
875 			NL_SET_ERR_MSG(extack,
876 				       "Nexthop specification and nexthop id are mutually exclusive");
877 			err = -EINVAL;
878 			goto errout;
879 		}
880 	}
881 
882 	if (has_gw && has_via) {
883 		NL_SET_ERR_MSG(extack,
884 			       "Nexthop configuration can not contain both GATEWAY and VIA");
885 		err = -EINVAL;
886 		goto errout;
887 	}
888 
889 	if (!cfg->fc_table)
890 		cfg->fc_table = RT_TABLE_MAIN;
891 
892 	return 0;
893 errout:
894 	return err;
895 }
896 
897 static int inet_rtm_delroute(struct sk_buff *skb, struct nlmsghdr *nlh,
898 			     struct netlink_ext_ack *extack)
899 {
900 	struct net *net = sock_net(skb->sk);
901 	struct fib_config cfg;
902 	struct fib_table *tb;
903 	int err;
904 
905 	err = rtm_to_fib_config(net, skb, nlh, &cfg, extack);
906 	if (err < 0)
907 		goto errout;
908 
909 	rtnl_net_lock(net);
910 
911 	if (cfg.fc_nh_id && !nexthop_find_by_id(net, cfg.fc_nh_id)) {
912 		NL_SET_ERR_MSG(extack, "Nexthop id does not exist");
913 		err = -EINVAL;
914 		goto unlock;
915 	}
916 
917 	tb = fib_get_table(net, cfg.fc_table);
918 	if (!tb) {
919 		NL_SET_ERR_MSG(extack, "FIB table does not exist");
920 		err = -ESRCH;
921 		goto unlock;
922 	}
923 
924 	err = fib_table_delete(net, tb, &cfg, extack);
925 unlock:
926 	rtnl_net_unlock(net);
927 errout:
928 	return err;
929 }
930 
931 static int inet_rtm_newroute(struct sk_buff *skb, struct nlmsghdr *nlh,
932 			     struct netlink_ext_ack *extack)
933 {
934 	struct net *net = sock_net(skb->sk);
935 	struct fib_config cfg;
936 	struct fib_table *tb;
937 	int err;
938 
939 	err = rtm_to_fib_config(net, skb, nlh, &cfg, extack);
940 	if (err < 0)
941 		goto errout;
942 
943 	rtnl_net_lock(net);
944 
945 	tb = fib_new_table(net, cfg.fc_table);
946 	if (!tb) {
947 		err = -ENOBUFS;
948 		goto unlock;
949 	}
950 
951 	err = fib_table_insert(net, tb, &cfg, extack);
952 	if (!err && cfg.fc_type == RTN_LOCAL)
953 		net->ipv4.fib_has_custom_local_routes = true;
954 
955 unlock:
956 	rtnl_net_unlock(net);
957 errout:
958 	return err;
959 }
960 
961 int ip_valid_fib_dump_req(struct net *net, const struct nlmsghdr *nlh,
962 			  struct fib_dump_filter *filter,
963 			  struct netlink_callback *cb)
964 {
965 	struct netlink_ext_ack *extack = cb->extack;
966 	struct nlattr *tb[RTA_MAX + 1];
967 	struct rtmsg *rtm;
968 	int err, i;
969 
970 	rtm = nlmsg_payload(nlh, sizeof(*rtm));
971 	if (!rtm) {
972 		NL_SET_ERR_MSG(extack, "Invalid header for FIB dump request");
973 		return -EINVAL;
974 	}
975 
976 	if (rtm->rtm_dst_len || rtm->rtm_src_len  || rtm->rtm_tos   ||
977 	    rtm->rtm_scope) {
978 		NL_SET_ERR_MSG(extack, "Invalid values in header for FIB dump request");
979 		return -EINVAL;
980 	}
981 
982 	if (rtm->rtm_flags & ~(RTM_F_CLONED | RTM_F_PREFIX)) {
983 		NL_SET_ERR_MSG(extack, "Invalid flags for FIB dump request");
984 		return -EINVAL;
985 	}
986 	if (rtm->rtm_flags & RTM_F_CLONED)
987 		filter->dump_routes = false;
988 	else
989 		filter->dump_exceptions = false;
990 
991 	filter->flags    = rtm->rtm_flags;
992 	filter->protocol = rtm->rtm_protocol;
993 	filter->rt_type  = rtm->rtm_type;
994 	filter->table_id = rtm->rtm_table;
995 
996 	err = nlmsg_parse_deprecated_strict(nlh, sizeof(*rtm), tb, RTA_MAX,
997 					    rtm_ipv4_policy, extack);
998 	if (err < 0)
999 		return err;
1000 
1001 	for (i = 0; i <= RTA_MAX; ++i) {
1002 		int ifindex;
1003 
1004 		if (!tb[i])
1005 			continue;
1006 
1007 		switch (i) {
1008 		case RTA_TABLE:
1009 			filter->table_id = nla_get_u32(tb[i]);
1010 			break;
1011 		case RTA_OIF:
1012 			ifindex = nla_get_u32(tb[i]);
1013 
1014 			filter->dev = dev_get_by_index_rcu(net, ifindex);
1015 			if (!filter->dev)
1016 				return -ENODEV;
1017 			break;
1018 		default:
1019 			NL_SET_ERR_MSG(extack, "Unsupported attribute in dump request");
1020 			return -EINVAL;
1021 		}
1022 	}
1023 
1024 	if (filter->flags || filter->protocol || filter->rt_type ||
1025 	    filter->table_id || filter->dev) {
1026 		filter->filter_set = 1;
1027 		cb->answer_flags = NLM_F_DUMP_FILTERED;
1028 	}
1029 
1030 	return 0;
1031 }
1032 EXPORT_SYMBOL_GPL(ip_valid_fib_dump_req);
1033 
1034 static int inet_dump_fib(struct sk_buff *skb, struct netlink_callback *cb)
1035 {
1036 	const struct nlmsghdr *nlh = cb->nlh;
1037 	struct net *net = sock_net(skb->sk);
1038 	struct fib_dump_filter filter = {
1039 		.dump_routes = true,
1040 		.dump_exceptions = true,
1041 	};
1042 	struct hlist_head *head;
1043 	int dumped = 0, err = 0;
1044 	struct fib_table *tb;
1045 	unsigned int h, s_h;
1046 	u32 s_id;
1047 
1048 	rcu_read_lock();
1049 	if (cb->strict_check) {
1050 		err = ip_valid_fib_dump_req(net, nlh, &filter, cb);
1051 		if (err < 0)
1052 			goto unlock;
1053 	} else if (nlmsg_len(nlh) >= sizeof(struct rtmsg)) {
1054 		struct rtmsg *rtm = nlmsg_data(nlh);
1055 
1056 		filter.flags = rtm->rtm_flags & (RTM_F_PREFIX | RTM_F_CLONED);
1057 	}
1058 
1059 	/* ipv4 does not use prefix flag */
1060 	if (filter.flags & RTM_F_PREFIX)
1061 		goto unlock;
1062 
1063 	if (filter.table_id) {
1064 		tb = fib_get_table(net, filter.table_id);
1065 		if (!tb) {
1066 			if (rtnl_msg_family(cb->nlh) != PF_INET)
1067 				goto unlock;
1068 
1069 			NL_SET_ERR_MSG(cb->extack, "ipv4: FIB table does not exist");
1070 			err = -ENOENT;
1071 			goto unlock;
1072 		}
1073 		err = fib_table_dump(tb, skb, cb, &filter);
1074 		goto unlock;
1075 	}
1076 
1077 	s_h = cb->args[0];
1078 	s_id = cb->args[1];
1079 
1080 	err = 0;
1081 	for (h = s_h; h < FIB_TABLE_HASHSZ; h++, s_id = 0) {
1082 		head = &net->ipv4.fib_table_hash[h];
1083 		hlist_for_each_entry_rcu(tb, head, tb_hlist) {
1084 			if (s_id && tb->tb_id != s_id)
1085 				continue;
1086 
1087 			s_id = 0;
1088 			if (dumped)
1089 				memset(&cb->args[2], 0, sizeof(cb->args) -
1090 						 2 * sizeof(cb->args[0]));
1091 			cb->args[1] = tb->tb_id;
1092 			err = fib_table_dump(tb, skb, cb, &filter);
1093 			if (err < 0)
1094 				goto out;
1095 			dumped = 1;
1096 		}
1097 	}
1098 out:
1099 
1100 	cb->args[0] = h;
1101 
1102 unlock:
1103 	rcu_read_unlock();
1104 	return err;
1105 }
1106 
1107 /* Prepare and feed intra-kernel routing request.
1108  * Really, it should be netlink message, but :-( netlink
1109  * can be not configured, so that we feed it directly
1110  * to fib engine. It is legal, because all events occur
1111  * only when netlink is already locked.
1112  */
1113 static void fib_magic(int cmd, int type, __be32 dst, int dst_len,
1114 		      struct in_ifaddr *ifa, u32 rt_priority)
1115 {
1116 	struct net *net = dev_net(ifa->ifa_dev->dev);
1117 	u32 tb_id = l3mdev_fib_table(ifa->ifa_dev->dev);
1118 	struct fib_table *tb;
1119 	struct fib_config cfg = {
1120 		.fc_protocol = RTPROT_KERNEL,
1121 		.fc_type = type,
1122 		.fc_dst = dst,
1123 		.fc_dst_len = dst_len,
1124 		.fc_priority = rt_priority,
1125 		.fc_prefsrc = ifa->ifa_local,
1126 		.fc_oif = ifa->ifa_dev->dev->ifindex,
1127 		.fc_nlflags = NLM_F_CREATE | NLM_F_APPEND,
1128 		.fc_nlinfo = {
1129 			.nl_net = net,
1130 		},
1131 	};
1132 
1133 	if (!tb_id)
1134 		tb_id = (type == RTN_UNICAST) ? RT_TABLE_MAIN : RT_TABLE_LOCAL;
1135 
1136 	tb = fib_new_table(net, tb_id);
1137 	if (!tb)
1138 		return;
1139 
1140 	cfg.fc_table = tb->tb_id;
1141 
1142 	if (type != RTN_LOCAL)
1143 		cfg.fc_scope = RT_SCOPE_LINK;
1144 	else
1145 		cfg.fc_scope = RT_SCOPE_HOST;
1146 
1147 	if (cmd == RTM_NEWROUTE)
1148 		fib_table_insert(net, tb, &cfg, NULL);
1149 	else
1150 		fib_table_delete(net, tb, &cfg, NULL);
1151 }
1152 
1153 void fib_add_ifaddr(struct in_ifaddr *ifa)
1154 {
1155 	struct in_device *in_dev = ifa->ifa_dev;
1156 	struct net_device *dev = in_dev->dev;
1157 	struct in_ifaddr *prim = ifa;
1158 	__be32 mask = ifa->ifa_mask;
1159 	__be32 addr = ifa->ifa_local;
1160 	__be32 prefix = ifa->ifa_address & mask;
1161 
1162 	if (ifa->ifa_flags & IFA_F_SECONDARY) {
1163 		prim = inet_ifa_byprefix(in_dev, prefix, mask);
1164 		if (!prim) {
1165 			pr_warn("%s: bug: prim == NULL\n", __func__);
1166 			return;
1167 		}
1168 	}
1169 
1170 	fib_magic(RTM_NEWROUTE, RTN_LOCAL, addr, 32, prim, 0);
1171 
1172 	if (!(dev->flags & IFF_UP))
1173 		return;
1174 
1175 	/* Add broadcast address, if it is explicitly assigned. */
1176 	if (ifa->ifa_broadcast && ifa->ifa_broadcast != htonl(0xFFFFFFFF)) {
1177 		fib_magic(RTM_NEWROUTE, RTN_BROADCAST, ifa->ifa_broadcast, 32,
1178 			  prim, 0);
1179 		arp_invalidate(dev, ifa->ifa_broadcast, false);
1180 	}
1181 
1182 	if (!ipv4_is_zeronet(prefix) && !(ifa->ifa_flags & IFA_F_SECONDARY) &&
1183 	    (prefix != addr || ifa->ifa_prefixlen < 32)) {
1184 		if (!(ifa->ifa_flags & IFA_F_NOPREFIXROUTE))
1185 			fib_magic(RTM_NEWROUTE,
1186 				  dev->flags & IFF_LOOPBACK ? RTN_LOCAL : RTN_UNICAST,
1187 				  prefix, ifa->ifa_prefixlen, prim,
1188 				  ifa->ifa_rt_priority);
1189 
1190 		/* Add the network broadcast address, when it makes sense */
1191 		if (ifa->ifa_prefixlen < 31) {
1192 			fib_magic(RTM_NEWROUTE, RTN_BROADCAST, prefix | ~mask,
1193 				  32, prim, 0);
1194 			arp_invalidate(dev, prefix | ~mask, false);
1195 		}
1196 	}
1197 }
1198 
1199 void fib_modify_prefix_metric(struct in_ifaddr *ifa, u32 new_metric)
1200 {
1201 	__be32 prefix = ifa->ifa_address & ifa->ifa_mask;
1202 	struct in_device *in_dev = ifa->ifa_dev;
1203 	struct net_device *dev = in_dev->dev;
1204 
1205 	if (!(dev->flags & IFF_UP) ||
1206 	    ifa->ifa_flags & (IFA_F_SECONDARY | IFA_F_NOPREFIXROUTE) ||
1207 	    ipv4_is_zeronet(prefix) ||
1208 	    (prefix == ifa->ifa_local && ifa->ifa_prefixlen == 32))
1209 		return;
1210 
1211 	/* add the new */
1212 	fib_magic(RTM_NEWROUTE,
1213 		  dev->flags & IFF_LOOPBACK ? RTN_LOCAL : RTN_UNICAST,
1214 		  prefix, ifa->ifa_prefixlen, ifa, new_metric);
1215 
1216 	/* delete the old */
1217 	fib_magic(RTM_DELROUTE,
1218 		  dev->flags & IFF_LOOPBACK ? RTN_LOCAL : RTN_UNICAST,
1219 		  prefix, ifa->ifa_prefixlen, ifa, ifa->ifa_rt_priority);
1220 }
1221 
1222 /* Delete primary or secondary address.
1223  * Optionally, on secondary address promotion consider the addresses
1224  * from subnet iprim as deleted, even if they are in device list.
1225  * In this case the secondary ifa can be in device list.
1226  */
1227 void fib_del_ifaddr(struct in_ifaddr *ifa, struct in_ifaddr *iprim)
1228 {
1229 	struct in_device *in_dev = ifa->ifa_dev;
1230 	struct net_device *dev = in_dev->dev;
1231 	struct in_ifaddr *ifa1;
1232 	struct in_ifaddr *prim = ifa, *prim1 = NULL;
1233 	__be32 brd = ifa->ifa_address | ~ifa->ifa_mask;
1234 	__be32 any = ifa->ifa_address & ifa->ifa_mask;
1235 #define LOCAL_OK	1
1236 #define BRD_OK		2
1237 #define BRD0_OK		4
1238 #define BRD1_OK		8
1239 	unsigned int ok = 0;
1240 	int subnet = 0;		/* Primary network */
1241 	int gone = 1;		/* Address is missing */
1242 	int same_prefsrc = 0;	/* Another primary with same IP */
1243 
1244 	if (ifa->ifa_flags & IFA_F_SECONDARY) {
1245 		prim = inet_ifa_byprefix(in_dev, any, ifa->ifa_mask);
1246 		if (!prim) {
1247 			/* if the device has been deleted, we don't perform
1248 			 * address promotion
1249 			 */
1250 			if (!in_dev->dead)
1251 				pr_warn("%s: bug: prim == NULL\n", __func__);
1252 			return;
1253 		}
1254 		if (iprim && iprim != prim) {
1255 			pr_warn("%s: bug: iprim != prim\n", __func__);
1256 			return;
1257 		}
1258 	} else if (!ipv4_is_zeronet(any) &&
1259 		   (any != ifa->ifa_local || ifa->ifa_prefixlen < 32)) {
1260 		if (!(ifa->ifa_flags & IFA_F_NOPREFIXROUTE))
1261 			fib_magic(RTM_DELROUTE,
1262 				  dev->flags & IFF_LOOPBACK ? RTN_LOCAL : RTN_UNICAST,
1263 				  any, ifa->ifa_prefixlen, prim, 0);
1264 		subnet = 1;
1265 	}
1266 
1267 	if (in_dev->dead)
1268 		goto no_promotions;
1269 
1270 	/* Deletion is more complicated than add.
1271 	 * We should take care of not to delete too much :-)
1272 	 *
1273 	 * Scan address list to be sure that addresses are really gone.
1274 	 */
1275 	rcu_read_lock();
1276 	in_dev_for_each_ifa_rcu(ifa1, in_dev) {
1277 		if (ifa1 == ifa) {
1278 			/* promotion, keep the IP */
1279 			gone = 0;
1280 			continue;
1281 		}
1282 		/* Ignore IFAs from our subnet */
1283 		if (iprim && ifa1->ifa_mask == iprim->ifa_mask &&
1284 		    inet_ifa_match(ifa1->ifa_address, iprim))
1285 			continue;
1286 
1287 		/* Ignore ifa1 if it uses different primary IP (prefsrc) */
1288 		if (ifa1->ifa_flags & IFA_F_SECONDARY) {
1289 			/* Another address from our subnet? */
1290 			if (ifa1->ifa_mask == prim->ifa_mask &&
1291 			    inet_ifa_match(ifa1->ifa_address, prim))
1292 				prim1 = prim;
1293 			else {
1294 				/* We reached the secondaries, so
1295 				 * same_prefsrc should be determined.
1296 				 */
1297 				if (!same_prefsrc)
1298 					continue;
1299 				/* Search new prim1 if ifa1 is not
1300 				 * using the current prim1
1301 				 */
1302 				if (!prim1 ||
1303 				    ifa1->ifa_mask != prim1->ifa_mask ||
1304 				    !inet_ifa_match(ifa1->ifa_address, prim1))
1305 					prim1 = inet_ifa_byprefix(in_dev,
1306 							ifa1->ifa_address,
1307 							ifa1->ifa_mask);
1308 				if (!prim1)
1309 					continue;
1310 				if (prim1->ifa_local != prim->ifa_local)
1311 					continue;
1312 			}
1313 		} else {
1314 			if (prim->ifa_local != ifa1->ifa_local)
1315 				continue;
1316 			prim1 = ifa1;
1317 			if (prim != prim1)
1318 				same_prefsrc = 1;
1319 		}
1320 		if (ifa->ifa_local == ifa1->ifa_local)
1321 			ok |= LOCAL_OK;
1322 		if (ifa->ifa_broadcast == ifa1->ifa_broadcast)
1323 			ok |= BRD_OK;
1324 		if (brd == ifa1->ifa_broadcast)
1325 			ok |= BRD1_OK;
1326 		if (any == ifa1->ifa_broadcast)
1327 			ok |= BRD0_OK;
1328 		/* primary has network specific broadcasts */
1329 		if (prim1 == ifa1 && ifa1->ifa_prefixlen < 31) {
1330 			__be32 brd1 = ifa1->ifa_address | ~ifa1->ifa_mask;
1331 			__be32 any1 = ifa1->ifa_address & ifa1->ifa_mask;
1332 
1333 			if (!ipv4_is_zeronet(any1)) {
1334 				if (ifa->ifa_broadcast == brd1 ||
1335 				    ifa->ifa_broadcast == any1)
1336 					ok |= BRD_OK;
1337 				if (brd == brd1 || brd == any1)
1338 					ok |= BRD1_OK;
1339 				if (any == brd1 || any == any1)
1340 					ok |= BRD0_OK;
1341 			}
1342 		}
1343 	}
1344 	rcu_read_unlock();
1345 
1346 no_promotions:
1347 	if (!(ok & BRD_OK))
1348 		fib_magic(RTM_DELROUTE, RTN_BROADCAST, ifa->ifa_broadcast, 32,
1349 			  prim, 0);
1350 	if (subnet && ifa->ifa_prefixlen < 31) {
1351 		if (!(ok & BRD1_OK))
1352 			fib_magic(RTM_DELROUTE, RTN_BROADCAST, brd, 32,
1353 				  prim, 0);
1354 		if (!(ok & BRD0_OK))
1355 			fib_magic(RTM_DELROUTE, RTN_BROADCAST, any, 32,
1356 				  prim, 0);
1357 	}
1358 	if (!(ok & LOCAL_OK)) {
1359 		unsigned int addr_type;
1360 
1361 		fib_magic(RTM_DELROUTE, RTN_LOCAL, ifa->ifa_local, 32, prim, 0);
1362 
1363 		/* Check, that this local address finally disappeared. */
1364 		addr_type = inet_addr_type_dev_table(dev_net(dev), dev,
1365 						     ifa->ifa_local);
1366 		if (gone && addr_type != RTN_LOCAL) {
1367 			/* And the last, but not the least thing.
1368 			 * We must flush stray FIB entries.
1369 			 *
1370 			 * First of all, we scan fib_info list searching
1371 			 * for stray nexthop entries, then ignite fib_flush.
1372 			 */
1373 			if (fib_sync_down_addr(dev, ifa->ifa_local))
1374 				fib_flush(dev_net(dev));
1375 		}
1376 	}
1377 #undef LOCAL_OK
1378 #undef BRD_OK
1379 #undef BRD0_OK
1380 #undef BRD1_OK
1381 }
1382 
1383 static void nl_fib_lookup(struct net *net, struct fib_result_nl *frn)
1384 {
1385 
1386 	struct fib_result       res;
1387 	struct flowi4           fl4 = {
1388 		.flowi4_mark = frn->fl_mark,
1389 		.daddr = frn->fl_addr,
1390 		.flowi4_dscp = inet_dsfield_to_dscp(frn->fl_tos),
1391 		.flowi4_scope = frn->fl_scope,
1392 	};
1393 	struct fib_table *tb;
1394 
1395 	rcu_read_lock();
1396 
1397 	tb = fib_get_table(net, frn->tb_id_in);
1398 
1399 	frn->err = -ENOENT;
1400 	if (tb) {
1401 		local_bh_disable();
1402 
1403 		frn->tb_id = tb->tb_id;
1404 		frn->err = fib_table_lookup(net, tb, &fl4, &res,
1405 					    FIB_LOOKUP_NOREF);
1406 
1407 		if (!frn->err) {
1408 			frn->prefixlen = res.prefixlen;
1409 			frn->nh_sel = res.nh_sel;
1410 			frn->type = res.type;
1411 			frn->scope = res.scope;
1412 		}
1413 		local_bh_enable();
1414 	}
1415 
1416 	rcu_read_unlock();
1417 }
1418 
1419 static void nl_fib_input(struct sk_buff *skb)
1420 {
1421 	struct net *net;
1422 	struct fib_result_nl *frn;
1423 	struct nlmsghdr *nlh;
1424 	u32 portid;
1425 
1426 	net = sock_net(skb->sk);
1427 	nlh = nlmsg_hdr(skb);
1428 	if (skb->len < nlmsg_total_size(sizeof(*frn)) ||
1429 	    skb->len < nlh->nlmsg_len ||
1430 	    nlmsg_len(nlh) < sizeof(*frn))
1431 		return;
1432 
1433 	skb = netlink_skb_clone(skb, GFP_KERNEL);
1434 	if (!skb)
1435 		return;
1436 	nlh = nlmsg_hdr(skb);
1437 
1438 	frn = nlmsg_data(nlh);
1439 	nl_fib_lookup(net, frn);
1440 
1441 	portid = NETLINK_CB(skb).portid;      /* netlink portid */
1442 	NETLINK_CB(skb).portid = 0;        /* from kernel */
1443 	NETLINK_CB(skb).dst_group = 0;  /* unicast */
1444 	nlmsg_unicast(net->ipv4.fibnl, skb, portid);
1445 }
1446 
1447 static int __net_init nl_fib_lookup_init(struct net *net)
1448 {
1449 	struct sock *sk;
1450 	struct netlink_kernel_cfg cfg = {
1451 		.input	= nl_fib_input,
1452 	};
1453 
1454 	sk = netlink_kernel_create(net, NETLINK_FIB_LOOKUP, &cfg);
1455 	if (!sk)
1456 		return -EAFNOSUPPORT;
1457 	net->ipv4.fibnl = sk;
1458 	return 0;
1459 }
1460 
1461 static void nl_fib_lookup_exit(struct net *net)
1462 {
1463 	netlink_kernel_release(net->ipv4.fibnl);
1464 	net->ipv4.fibnl = NULL;
1465 }
1466 
1467 static void fib_disable_ip(struct net_device *dev, unsigned long event,
1468 			   bool force)
1469 {
1470 	if (fib_sync_down_dev(dev, event, force))
1471 		fib_flush(dev_net(dev));
1472 	else
1473 		rt_cache_flush(dev_net(dev));
1474 	arp_ifdown(dev);
1475 }
1476 
1477 static int fib_inetaddr_event(struct notifier_block *this, unsigned long event, void *ptr)
1478 {
1479 	struct in_ifaddr *ifa = ptr;
1480 	struct net_device *dev = ifa->ifa_dev->dev;
1481 	struct net *net = dev_net(dev);
1482 
1483 	switch (event) {
1484 	case NETDEV_UP:
1485 		fib_add_ifaddr(ifa);
1486 #ifdef CONFIG_IP_ROUTE_MULTIPATH
1487 		fib_sync_up(dev, RTNH_F_DEAD);
1488 #endif
1489 		atomic_inc(&net->ipv4.dev_addr_genid);
1490 		rt_cache_flush(net);
1491 		break;
1492 	case NETDEV_DOWN:
1493 		fib_del_ifaddr(ifa, NULL);
1494 		atomic_inc(&net->ipv4.dev_addr_genid);
1495 		if (!ifa->ifa_dev->ifa_list) {
1496 			/* Last address was deleted from this interface.
1497 			 * Disable IP.
1498 			 */
1499 			fib_disable_ip(dev, event, true);
1500 		} else {
1501 			rt_cache_flush(net);
1502 		}
1503 		break;
1504 	}
1505 	return NOTIFY_DONE;
1506 }
1507 
1508 static int fib_netdev_event(struct notifier_block *this, unsigned long event, void *ptr)
1509 {
1510 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1511 	struct netdev_notifier_changeupper_info *upper_info = ptr;
1512 	struct netdev_notifier_info_ext *info_ext = ptr;
1513 	struct in_device *in_dev;
1514 	struct net *net = dev_net(dev);
1515 	struct in_ifaddr *ifa;
1516 	unsigned int flags;
1517 
1518 	if (event == NETDEV_UNREGISTER) {
1519 		fib_disable_ip(dev, event, true);
1520 		rt_flush_dev(dev);
1521 		return NOTIFY_DONE;
1522 	}
1523 
1524 	in_dev = __in_dev_get_rtnl(dev);
1525 	if (!in_dev)
1526 		return NOTIFY_DONE;
1527 
1528 	switch (event) {
1529 	case NETDEV_UP:
1530 		in_dev_for_each_ifa_rtnl(ifa, in_dev) {
1531 			fib_add_ifaddr(ifa);
1532 		}
1533 #ifdef CONFIG_IP_ROUTE_MULTIPATH
1534 		fib_sync_up(dev, RTNH_F_DEAD);
1535 #endif
1536 		atomic_inc(&net->ipv4.dev_addr_genid);
1537 		rt_cache_flush(net);
1538 		break;
1539 	case NETDEV_DOWN:
1540 		fib_disable_ip(dev, event, false);
1541 		break;
1542 	case NETDEV_CHANGE:
1543 		flags = netif_get_flags(dev);
1544 		if (flags & (IFF_RUNNING | IFF_LOWER_UP))
1545 			fib_sync_up(dev, RTNH_F_LINKDOWN);
1546 		else
1547 			fib_sync_down_dev(dev, event, false);
1548 		rt_cache_flush(net);
1549 		break;
1550 	case NETDEV_CHANGEMTU:
1551 		fib_sync_mtu(dev, info_ext->ext.mtu);
1552 		rt_cache_flush(net);
1553 		break;
1554 	case NETDEV_CHANGEUPPER:
1555 		upper_info = ptr;
1556 		/* flush all routes if dev is linked to or unlinked from
1557 		 * an L3 master device (e.g., VRF)
1558 		 */
1559 		if (upper_info->upper_dev &&
1560 		    netif_is_l3_master(upper_info->upper_dev))
1561 			fib_disable_ip(dev, NETDEV_DOWN, true);
1562 		break;
1563 	}
1564 	return NOTIFY_DONE;
1565 }
1566 
1567 static struct notifier_block fib_inetaddr_notifier = {
1568 	.notifier_call = fib_inetaddr_event,
1569 };
1570 
1571 static struct notifier_block fib_netdev_notifier = {
1572 	.notifier_call = fib_netdev_event,
1573 };
1574 
1575 static int __net_init ip_fib_net_init(struct net *net)
1576 {
1577 	int err;
1578 	size_t size = sizeof(struct hlist_head) * FIB_TABLE_HASHSZ;
1579 
1580 	err = fib4_notifier_init(net);
1581 	if (err)
1582 		return err;
1583 
1584 #ifdef CONFIG_IP_ROUTE_MULTIPATH
1585 	/* Default to 3-tuple */
1586 	net->ipv4.sysctl_fib_multipath_hash_fields =
1587 		FIB_MULTIPATH_HASH_FIELD_DEFAULT_MASK;
1588 #endif
1589 
1590 #ifdef CONFIG_IP_MULTIPLE_TABLES
1591 	spin_lock_init(&net->ipv4.fib_table_hash_lock);
1592 #endif
1593 
1594 	/* Avoid false sharing : Use at least a full cache line */
1595 	size = max_t(size_t, size, L1_CACHE_BYTES);
1596 
1597 	net->ipv4.fib_table_hash = kzalloc(size, GFP_KERNEL);
1598 	if (!net->ipv4.fib_table_hash) {
1599 		err = -ENOMEM;
1600 		goto err_table_hash_alloc;
1601 	}
1602 
1603 	err = fib4_rules_init(net);
1604 	if (err < 0)
1605 		goto err_rules_init;
1606 	return 0;
1607 
1608 err_rules_init:
1609 	kfree(net->ipv4.fib_table_hash);
1610 err_table_hash_alloc:
1611 	fib4_notifier_exit(net);
1612 	return err;
1613 }
1614 
1615 static void ip_fib_net_exit(struct net *net)
1616 {
1617 	int i;
1618 
1619 	ASSERT_RTNL_NET(net);
1620 #ifdef CONFIG_IP_MULTIPLE_TABLES
1621 	RCU_INIT_POINTER(net->ipv4.fib_main, NULL);
1622 	RCU_INIT_POINTER(net->ipv4.fib_default, NULL);
1623 #endif
1624 	/* Destroy the tables in reverse order to guarantee that the
1625 	 * local table, ID 255, is destroyed before the main table, ID
1626 	 * 254. This is necessary as the local table may contain
1627 	 * references to data contained in the main table.
1628 	 */
1629 	for (i = FIB_TABLE_HASHSZ - 1; i >= 0; i--) {
1630 		struct hlist_head *head = &net->ipv4.fib_table_hash[i];
1631 		struct hlist_node *tmp;
1632 		struct fib_table *tb;
1633 
1634 		hlist_for_each_entry_safe(tb, tmp, head, tb_hlist) {
1635 			hlist_del_rcu(&tb->tb_hlist);
1636 			fib_table_flush(net, tb, true);
1637 			fib_free_table(tb);
1638 		}
1639 	}
1640 }
1641 
1642 static int __net_init fib_net_init(struct net *net)
1643 {
1644 	int error;
1645 
1646 #ifdef CONFIG_IP_ROUTE_CLASSID
1647 	atomic_set(&net->ipv4.fib_num_tclassid_users, 0);
1648 #endif
1649 	error = ip_fib_net_init(net);
1650 	if (error < 0)
1651 		goto out;
1652 
1653 	error = fib4_semantics_init(net);
1654 	if (error)
1655 		goto out_semantics;
1656 
1657 	error = nl_fib_lookup_init(net);
1658 	if (error < 0)
1659 		goto out_nlfl;
1660 
1661 	error = fib_proc_init(net);
1662 	if (error < 0)
1663 		goto out_proc;
1664 out:
1665 	return error;
1666 
1667 out_proc:
1668 	nl_fib_lookup_exit(net);
1669 out_nlfl:
1670 	fib4_semantics_exit(net);
1671 out_semantics:
1672 	rtnl_net_lock(net);
1673 	ip_fib_net_exit(net);
1674 	rtnl_net_unlock(net);
1675 
1676 #ifdef CONFIG_IP_MULTIPLE_TABLES
1677 	fib4_rules_exit(net);
1678 #endif
1679 	kfree(net->ipv4.fib_table_hash);
1680 	fib4_notifier_exit(net);
1681 	goto out;
1682 }
1683 
1684 static void __net_exit fib_net_pre_exit(struct net *net)
1685 {
1686 	fib_proc_exit(net);
1687 	nl_fib_lookup_exit(net);
1688 }
1689 
1690 static void __net_exit fib_net_exit_rtnl(struct net *net,
1691 					 struct list_head *dev_kill_list)
1692 {
1693 	ip_fib_net_exit(net);
1694 }
1695 
1696 static void __net_exit fib_net_exit(struct net *net)
1697 {
1698 #ifdef CONFIG_IP_MULTIPLE_TABLES
1699 	fib4_rules_exit(net);
1700 #endif
1701 	kfree(net->ipv4.fib_table_hash);
1702 	fib4_notifier_exit(net);
1703 	fib4_semantics_exit(net);
1704 }
1705 
1706 static struct pernet_operations fib_net_ops = {
1707 	.init = fib_net_init,
1708 	.pre_exit = fib_net_pre_exit,
1709 	.exit_rtnl = fib_net_exit_rtnl,
1710 	.exit = fib_net_exit,
1711 };
1712 
1713 static const struct rtnl_msg_handler fib_rtnl_msg_handlers[] __initconst = {
1714 	{.protocol = PF_INET, .msgtype = RTM_NEWROUTE,
1715 	 .doit = inet_rtm_newroute, .flags = RTNL_FLAG_DOIT_PERNET},
1716 	{.protocol = PF_INET, .msgtype = RTM_DELROUTE,
1717 	 .doit = inet_rtm_delroute, .flags = RTNL_FLAG_DOIT_PERNET},
1718 	{.protocol = PF_INET, .msgtype = RTM_GETROUTE, .dumpit = inet_dump_fib,
1719 	 .flags = RTNL_FLAG_DUMP_UNLOCKED | RTNL_FLAG_DUMP_SPLIT_NLM_DONE},
1720 };
1721 
1722 void __init ip_fib_init(void)
1723 {
1724 	fib_trie_init();
1725 
1726 	register_pernet_subsys(&fib_net_ops);
1727 
1728 	register_netdevice_notifier(&fib_netdev_notifier);
1729 	register_inetaddr_notifier(&fib_inetaddr_notifier);
1730 
1731 	rtnl_register_many(fib_rtnl_msg_handlers);
1732 }
1733