xref: /linux/net/ipv4/route.c (revision 83869019c74cc2d01c96a3be2463a4eebe362224)
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  *		ROUTE - implementation of the IP router.
8  *
9  * Authors:	Ross Biro
10  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
11  *		Alan Cox, <gw4pts@gw4pts.ampr.org>
12  *		Linus Torvalds, <Linus.Torvalds@helsinki.fi>
13  *		Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
14  *
15  * Fixes:
16  *		Alan Cox	:	Verify area fixes.
17  *		Alan Cox	:	cli() protects routing changes
18  *		Rui Oliveira	:	ICMP routing table updates
19  *		(rco@di.uminho.pt)	Routing table insertion and update
20  *		Linus Torvalds	:	Rewrote bits to be sensible
21  *		Alan Cox	:	Added BSD route gw semantics
22  *		Alan Cox	:	Super /proc >4K
23  *		Alan Cox	:	MTU in route table
24  *		Alan Cox	:	MSS actually. Also added the window
25  *					clamper.
26  *		Sam Lantinga	:	Fixed route matching in rt_del()
27  *		Alan Cox	:	Routing cache support.
28  *		Alan Cox	:	Removed compatibility cruft.
29  *		Alan Cox	:	RTF_REJECT support.
30  *		Alan Cox	:	TCP irtt support.
31  *		Jonathan Naylor	:	Added Metric support.
32  *	Miquel van Smoorenburg	:	BSD API fixes.
33  *	Miquel van Smoorenburg	:	Metrics.
34  *		Alan Cox	:	Use __u32 properly
35  *		Alan Cox	:	Aligned routing errors more closely with BSD
36  *					our system is still very different.
37  *		Alan Cox	:	Faster /proc handling
38  *	Alexey Kuznetsov	:	Massive rework to support tree based routing,
39  *					routing caches and better behaviour.
40  *
41  *		Olaf Erb	:	irtt wasn't being copied right.
42  *		Bjorn Ekwall	:	Kerneld route support.
43  *		Alan Cox	:	Multicast fixed (I hope)
44  *		Pavel Krauz	:	Limited broadcast fixed
45  *		Mike McLagan	:	Routing by source
46  *	Alexey Kuznetsov	:	End of old history. Split to fib.c and
47  *					route.c and rewritten from scratch.
48  *		Andi Kleen	:	Load-limit warning messages.
49  *	Vitaly E. Lavrov	:	Transparent proxy revived after year coma.
50  *	Vitaly E. Lavrov	:	Race condition in ip_route_input_slow.
51  *	Tobias Ringstrom	:	Uninitialized res.type in ip_route_output_slow.
52  *	Vladimir V. Ivanov	:	IP rule info (flowid) is really useful.
53  *		Marc Boucher	:	routing by fwmark
54  *	Robert Olsson		:	Added rt_cache statistics
55  *	Arnaldo C. Melo		:	Convert proc stuff to seq_file
56  *	Eric Dumazet		:	hashed spinlocks and rt_check_expire() fixes.
57  *	Ilia Sotnikov		:	Ignore TOS on PMTUD and Redirect
58  *	Ilia Sotnikov		:	Removed TOS from hash calculations
59  */
60 
61 #define pr_fmt(fmt) "IPv4: " fmt
62 
63 #include <linux/module.h>
64 #include <linux/bitops.h>
65 #include <linux/kernel.h>
66 #include <linux/mm.h>
67 #include <linux/memblock.h>
68 #include <linux/socket.h>
69 #include <linux/errno.h>
70 #include <linux/in.h>
71 #include <linux/inet.h>
72 #include <linux/netdevice.h>
73 #include <linux/proc_fs.h>
74 #include <linux/init.h>
75 #include <linux/skbuff.h>
76 #include <linux/inetdevice.h>
77 #include <linux/igmp.h>
78 #include <linux/pkt_sched.h>
79 #include <linux/mroute.h>
80 #include <linux/netfilter_ipv4.h>
81 #include <linux/random.h>
82 #include <linux/rcupdate.h>
83 #include <linux/slab.h>
84 #include <linux/jhash.h>
85 #include <net/dst.h>
86 #include <net/dst_metadata.h>
87 #include <net/net_namespace.h>
88 #include <net/ip.h>
89 #include <net/route.h>
90 #include <net/inetpeer.h>
91 #include <net/sock.h>
92 #include <net/ip_fib.h>
93 #include <net/nexthop.h>
94 #include <net/tcp.h>
95 #include <net/icmp.h>
96 #include <net/xfrm.h>
97 #include <net/lwtunnel.h>
98 #include <net/netevent.h>
99 #include <net/rtnetlink.h>
100 #ifdef CONFIG_SYSCTL
101 #include <linux/sysctl.h>
102 #endif
103 #include <net/secure_seq.h>
104 #include <net/ip_tunnels.h>
105 
106 #include "fib_lookup.h"
107 
108 #define RT_FL_TOS(oldflp4) \
109 	((oldflp4)->flowi4_tos & (IPTOS_RT_MASK | RTO_ONLINK))
110 
111 #define RT_GC_TIMEOUT (300*HZ)
112 
113 static int ip_rt_max_size;
114 static int ip_rt_redirect_number __read_mostly	= 9;
115 static int ip_rt_redirect_load __read_mostly	= HZ / 50;
116 static int ip_rt_redirect_silence __read_mostly	= ((HZ / 50) << (9 + 1));
117 static int ip_rt_error_cost __read_mostly	= HZ;
118 static int ip_rt_error_burst __read_mostly	= 5 * HZ;
119 static int ip_rt_mtu_expires __read_mostly	= 10 * 60 * HZ;
120 static u32 ip_rt_min_pmtu __read_mostly		= 512 + 20 + 20;
121 static int ip_rt_min_advmss __read_mostly	= 256;
122 
123 static int ip_rt_gc_timeout __read_mostly	= RT_GC_TIMEOUT;
124 
125 /*
126  *	Interface to generic destination cache.
127  */
128 
129 INDIRECT_CALLABLE_SCOPE
130 struct dst_entry	*ipv4_dst_check(struct dst_entry *dst, u32 cookie);
131 static unsigned int	 ipv4_default_advmss(const struct dst_entry *dst);
132 INDIRECT_CALLABLE_SCOPE
133 unsigned int		ipv4_mtu(const struct dst_entry *dst);
134 static struct dst_entry *ipv4_negative_advice(struct dst_entry *dst);
135 static void		 ipv4_link_failure(struct sk_buff *skb);
136 static void		 ip_rt_update_pmtu(struct dst_entry *dst, struct sock *sk,
137 					   struct sk_buff *skb, u32 mtu,
138 					   bool confirm_neigh);
139 static void		 ip_do_redirect(struct dst_entry *dst, struct sock *sk,
140 					struct sk_buff *skb);
141 static void		ipv4_dst_destroy(struct dst_entry *dst);
142 
143 static u32 *ipv4_cow_metrics(struct dst_entry *dst, unsigned long old)
144 {
145 	WARN_ON(1);
146 	return NULL;
147 }
148 
149 static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst,
150 					   struct sk_buff *skb,
151 					   const void *daddr);
152 static void ipv4_confirm_neigh(const struct dst_entry *dst, const void *daddr);
153 
154 static struct dst_ops ipv4_dst_ops = {
155 	.family =		AF_INET,
156 	.check =		ipv4_dst_check,
157 	.default_advmss =	ipv4_default_advmss,
158 	.mtu =			ipv4_mtu,
159 	.cow_metrics =		ipv4_cow_metrics,
160 	.destroy =		ipv4_dst_destroy,
161 	.negative_advice =	ipv4_negative_advice,
162 	.link_failure =		ipv4_link_failure,
163 	.update_pmtu =		ip_rt_update_pmtu,
164 	.redirect =		ip_do_redirect,
165 	.local_out =		__ip_local_out,
166 	.neigh_lookup =		ipv4_neigh_lookup,
167 	.confirm_neigh =	ipv4_confirm_neigh,
168 };
169 
170 #define ECN_OR_COST(class)	TC_PRIO_##class
171 
172 const __u8 ip_tos2prio[16] = {
173 	TC_PRIO_BESTEFFORT,
174 	ECN_OR_COST(BESTEFFORT),
175 	TC_PRIO_BESTEFFORT,
176 	ECN_OR_COST(BESTEFFORT),
177 	TC_PRIO_BULK,
178 	ECN_OR_COST(BULK),
179 	TC_PRIO_BULK,
180 	ECN_OR_COST(BULK),
181 	TC_PRIO_INTERACTIVE,
182 	ECN_OR_COST(INTERACTIVE),
183 	TC_PRIO_INTERACTIVE,
184 	ECN_OR_COST(INTERACTIVE),
185 	TC_PRIO_INTERACTIVE_BULK,
186 	ECN_OR_COST(INTERACTIVE_BULK),
187 	TC_PRIO_INTERACTIVE_BULK,
188 	ECN_OR_COST(INTERACTIVE_BULK)
189 };
190 EXPORT_SYMBOL(ip_tos2prio);
191 
192 static DEFINE_PER_CPU(struct rt_cache_stat, rt_cache_stat);
193 #define RT_CACHE_STAT_INC(field) raw_cpu_inc(rt_cache_stat.field)
194 
195 #ifdef CONFIG_PROC_FS
196 static void *rt_cache_seq_start(struct seq_file *seq, loff_t *pos)
197 {
198 	if (*pos)
199 		return NULL;
200 	return SEQ_START_TOKEN;
201 }
202 
203 static void *rt_cache_seq_next(struct seq_file *seq, void *v, loff_t *pos)
204 {
205 	++*pos;
206 	return NULL;
207 }
208 
209 static void rt_cache_seq_stop(struct seq_file *seq, void *v)
210 {
211 }
212 
213 static int rt_cache_seq_show(struct seq_file *seq, void *v)
214 {
215 	if (v == SEQ_START_TOKEN)
216 		seq_printf(seq, "%-127s\n",
217 			   "Iface\tDestination\tGateway \tFlags\t\tRefCnt\tUse\t"
218 			   "Metric\tSource\t\tMTU\tWindow\tIRTT\tTOS\tHHRef\t"
219 			   "HHUptod\tSpecDst");
220 	return 0;
221 }
222 
223 static const struct seq_operations rt_cache_seq_ops = {
224 	.start  = rt_cache_seq_start,
225 	.next   = rt_cache_seq_next,
226 	.stop   = rt_cache_seq_stop,
227 	.show   = rt_cache_seq_show,
228 };
229 
230 static void *rt_cpu_seq_start(struct seq_file *seq, loff_t *pos)
231 {
232 	int cpu;
233 
234 	if (*pos == 0)
235 		return SEQ_START_TOKEN;
236 
237 	for (cpu = *pos-1; cpu < nr_cpu_ids; ++cpu) {
238 		if (!cpu_possible(cpu))
239 			continue;
240 		*pos = cpu+1;
241 		return &per_cpu(rt_cache_stat, cpu);
242 	}
243 	return NULL;
244 }
245 
246 static void *rt_cpu_seq_next(struct seq_file *seq, void *v, loff_t *pos)
247 {
248 	int cpu;
249 
250 	for (cpu = *pos; cpu < nr_cpu_ids; ++cpu) {
251 		if (!cpu_possible(cpu))
252 			continue;
253 		*pos = cpu+1;
254 		return &per_cpu(rt_cache_stat, cpu);
255 	}
256 	(*pos)++;
257 	return NULL;
258 
259 }
260 
261 static void rt_cpu_seq_stop(struct seq_file *seq, void *v)
262 {
263 
264 }
265 
266 static int rt_cpu_seq_show(struct seq_file *seq, void *v)
267 {
268 	struct rt_cache_stat *st = v;
269 
270 	if (v == SEQ_START_TOKEN) {
271 		seq_puts(seq, "entries  in_hit   in_slow_tot in_slow_mc in_no_route in_brd   in_martian_dst in_martian_src out_hit  out_slow_tot out_slow_mc gc_total gc_ignored gc_goal_miss gc_dst_overflow in_hlist_search out_hlist_search\n");
272 		return 0;
273 	}
274 
275 	seq_printf(seq, "%08x %08x %08x    %08x   %08x    %08x %08x       "
276 			"%08x       %08x %08x     %08x    %08x %08x   "
277 			"%08x     %08x        %08x        %08x\n",
278 		   dst_entries_get_slow(&ipv4_dst_ops),
279 		   0, /* st->in_hit */
280 		   st->in_slow_tot,
281 		   st->in_slow_mc,
282 		   st->in_no_route,
283 		   st->in_brd,
284 		   st->in_martian_dst,
285 		   st->in_martian_src,
286 
287 		   0, /* st->out_hit */
288 		   st->out_slow_tot,
289 		   st->out_slow_mc,
290 
291 		   0, /* st->gc_total */
292 		   0, /* st->gc_ignored */
293 		   0, /* st->gc_goal_miss */
294 		   0, /* st->gc_dst_overflow */
295 		   0, /* st->in_hlist_search */
296 		   0  /* st->out_hlist_search */
297 		);
298 	return 0;
299 }
300 
301 static const struct seq_operations rt_cpu_seq_ops = {
302 	.start  = rt_cpu_seq_start,
303 	.next   = rt_cpu_seq_next,
304 	.stop   = rt_cpu_seq_stop,
305 	.show   = rt_cpu_seq_show,
306 };
307 
308 #ifdef CONFIG_IP_ROUTE_CLASSID
309 static int rt_acct_proc_show(struct seq_file *m, void *v)
310 {
311 	struct ip_rt_acct *dst, *src;
312 	unsigned int i, j;
313 
314 	dst = kcalloc(256, sizeof(struct ip_rt_acct), GFP_KERNEL);
315 	if (!dst)
316 		return -ENOMEM;
317 
318 	for_each_possible_cpu(i) {
319 		src = (struct ip_rt_acct *)per_cpu_ptr(ip_rt_acct, i);
320 		for (j = 0; j < 256; j++) {
321 			dst[j].o_bytes   += src[j].o_bytes;
322 			dst[j].o_packets += src[j].o_packets;
323 			dst[j].i_bytes   += src[j].i_bytes;
324 			dst[j].i_packets += src[j].i_packets;
325 		}
326 	}
327 
328 	seq_write(m, dst, 256 * sizeof(struct ip_rt_acct));
329 	kfree(dst);
330 	return 0;
331 }
332 #endif
333 
334 static int __net_init ip_rt_do_proc_init(struct net *net)
335 {
336 	struct proc_dir_entry *pde;
337 
338 	pde = proc_create_seq("rt_cache", 0444, net->proc_net,
339 			      &rt_cache_seq_ops);
340 	if (!pde)
341 		goto err1;
342 
343 	pde = proc_create_seq("rt_cache", 0444, net->proc_net_stat,
344 			      &rt_cpu_seq_ops);
345 	if (!pde)
346 		goto err2;
347 
348 #ifdef CONFIG_IP_ROUTE_CLASSID
349 	pde = proc_create_single("rt_acct", 0, net->proc_net,
350 			rt_acct_proc_show);
351 	if (!pde)
352 		goto err3;
353 #endif
354 	return 0;
355 
356 #ifdef CONFIG_IP_ROUTE_CLASSID
357 err3:
358 	remove_proc_entry("rt_cache", net->proc_net_stat);
359 #endif
360 err2:
361 	remove_proc_entry("rt_cache", net->proc_net);
362 err1:
363 	return -ENOMEM;
364 }
365 
366 static void __net_exit ip_rt_do_proc_exit(struct net *net)
367 {
368 	remove_proc_entry("rt_cache", net->proc_net_stat);
369 	remove_proc_entry("rt_cache", net->proc_net);
370 #ifdef CONFIG_IP_ROUTE_CLASSID
371 	remove_proc_entry("rt_acct", net->proc_net);
372 #endif
373 }
374 
375 static struct pernet_operations ip_rt_proc_ops __net_initdata =  {
376 	.init = ip_rt_do_proc_init,
377 	.exit = ip_rt_do_proc_exit,
378 };
379 
380 static int __init ip_rt_proc_init(void)
381 {
382 	return register_pernet_subsys(&ip_rt_proc_ops);
383 }
384 
385 #else
386 static inline int ip_rt_proc_init(void)
387 {
388 	return 0;
389 }
390 #endif /* CONFIG_PROC_FS */
391 
392 static inline bool rt_is_expired(const struct rtable *rth)
393 {
394 	return rth->rt_genid != rt_genid_ipv4(dev_net(rth->dst.dev));
395 }
396 
397 void rt_cache_flush(struct net *net)
398 {
399 	rt_genid_bump_ipv4(net);
400 }
401 
402 static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst,
403 					   struct sk_buff *skb,
404 					   const void *daddr)
405 {
406 	const struct rtable *rt = container_of(dst, struct rtable, dst);
407 	struct net_device *dev = dst->dev;
408 	struct neighbour *n;
409 
410 	rcu_read_lock_bh();
411 
412 	if (likely(rt->rt_gw_family == AF_INET)) {
413 		n = ip_neigh_gw4(dev, rt->rt_gw4);
414 	} else if (rt->rt_gw_family == AF_INET6) {
415 		n = ip_neigh_gw6(dev, &rt->rt_gw6);
416         } else {
417 		__be32 pkey;
418 
419 		pkey = skb ? ip_hdr(skb)->daddr : *((__be32 *) daddr);
420 		n = ip_neigh_gw4(dev, pkey);
421 	}
422 
423 	if (!IS_ERR(n) && !refcount_inc_not_zero(&n->refcnt))
424 		n = NULL;
425 
426 	rcu_read_unlock_bh();
427 
428 	return n;
429 }
430 
431 static void ipv4_confirm_neigh(const struct dst_entry *dst, const void *daddr)
432 {
433 	const struct rtable *rt = container_of(dst, struct rtable, dst);
434 	struct net_device *dev = dst->dev;
435 	const __be32 *pkey = daddr;
436 
437 	if (rt->rt_gw_family == AF_INET) {
438 		pkey = (const __be32 *)&rt->rt_gw4;
439 	} else if (rt->rt_gw_family == AF_INET6) {
440 		return __ipv6_confirm_neigh_stub(dev, &rt->rt_gw6);
441 	} else if (!daddr ||
442 		 (rt->rt_flags &
443 		  (RTCF_MULTICAST | RTCF_BROADCAST | RTCF_LOCAL))) {
444 		return;
445 	}
446 	__ipv4_confirm_neigh(dev, *(__force u32 *)pkey);
447 }
448 
449 /* Hash tables of size 2048..262144 depending on RAM size.
450  * Each bucket uses 8 bytes.
451  */
452 static u32 ip_idents_mask __read_mostly;
453 static atomic_t *ip_idents __read_mostly;
454 static u32 *ip_tstamps __read_mostly;
455 
456 /* In order to protect privacy, we add a perturbation to identifiers
457  * if one generator is seldom used. This makes hard for an attacker
458  * to infer how many packets were sent between two points in time.
459  */
460 u32 ip_idents_reserve(u32 hash, int segs)
461 {
462 	u32 bucket, old, now = (u32)jiffies;
463 	atomic_t *p_id;
464 	u32 *p_tstamp;
465 	u32 delta = 0;
466 
467 	bucket = hash & ip_idents_mask;
468 	p_tstamp = ip_tstamps + bucket;
469 	p_id = ip_idents + bucket;
470 	old = READ_ONCE(*p_tstamp);
471 
472 	if (old != now && cmpxchg(p_tstamp, old, now) == old)
473 		delta = prandom_u32_max(now - old);
474 
475 	/* If UBSAN reports an error there, please make sure your compiler
476 	 * supports -fno-strict-overflow before reporting it that was a bug
477 	 * in UBSAN, and it has been fixed in GCC-8.
478 	 */
479 	return atomic_add_return(segs + delta, p_id) - segs;
480 }
481 EXPORT_SYMBOL(ip_idents_reserve);
482 
483 void __ip_select_ident(struct net *net, struct iphdr *iph, int segs)
484 {
485 	u32 hash, id;
486 
487 	/* Note the following code is not safe, but this is okay. */
488 	if (unlikely(siphash_key_is_zero(&net->ipv4.ip_id_key)))
489 		get_random_bytes(&net->ipv4.ip_id_key,
490 				 sizeof(net->ipv4.ip_id_key));
491 
492 	hash = siphash_3u32((__force u32)iph->daddr,
493 			    (__force u32)iph->saddr,
494 			    iph->protocol,
495 			    &net->ipv4.ip_id_key);
496 	id = ip_idents_reserve(hash, segs);
497 	iph->id = htons(id);
498 }
499 EXPORT_SYMBOL(__ip_select_ident);
500 
501 static void __build_flow_key(const struct net *net, struct flowi4 *fl4,
502 			     const struct sock *sk,
503 			     const struct iphdr *iph,
504 			     int oif, u8 tos,
505 			     u8 prot, u32 mark, int flow_flags)
506 {
507 	if (sk) {
508 		const struct inet_sock *inet = inet_sk(sk);
509 
510 		oif = sk->sk_bound_dev_if;
511 		mark = sk->sk_mark;
512 		tos = RT_CONN_FLAGS(sk);
513 		prot = inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol;
514 	}
515 	flowi4_init_output(fl4, oif, mark, tos,
516 			   RT_SCOPE_UNIVERSE, prot,
517 			   flow_flags,
518 			   iph->daddr, iph->saddr, 0, 0,
519 			   sock_net_uid(net, sk));
520 }
521 
522 static void build_skb_flow_key(struct flowi4 *fl4, const struct sk_buff *skb,
523 			       const struct sock *sk)
524 {
525 	const struct net *net = dev_net(skb->dev);
526 	const struct iphdr *iph = ip_hdr(skb);
527 	int oif = skb->dev->ifindex;
528 	u8 tos = RT_TOS(iph->tos);
529 	u8 prot = iph->protocol;
530 	u32 mark = skb->mark;
531 
532 	__build_flow_key(net, fl4, sk, iph, oif, tos, prot, mark, 0);
533 }
534 
535 static void build_sk_flow_key(struct flowi4 *fl4, const struct sock *sk)
536 {
537 	const struct inet_sock *inet = inet_sk(sk);
538 	const struct ip_options_rcu *inet_opt;
539 	__be32 daddr = inet->inet_daddr;
540 
541 	rcu_read_lock();
542 	inet_opt = rcu_dereference(inet->inet_opt);
543 	if (inet_opt && inet_opt->opt.srr)
544 		daddr = inet_opt->opt.faddr;
545 	flowi4_init_output(fl4, sk->sk_bound_dev_if, sk->sk_mark,
546 			   RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
547 			   inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol,
548 			   inet_sk_flowi_flags(sk),
549 			   daddr, inet->inet_saddr, 0, 0, sk->sk_uid);
550 	rcu_read_unlock();
551 }
552 
553 static void ip_rt_build_flow_key(struct flowi4 *fl4, const struct sock *sk,
554 				 const struct sk_buff *skb)
555 {
556 	if (skb)
557 		build_skb_flow_key(fl4, skb, sk);
558 	else
559 		build_sk_flow_key(fl4, sk);
560 }
561 
562 static DEFINE_SPINLOCK(fnhe_lock);
563 
564 static void fnhe_flush_routes(struct fib_nh_exception *fnhe)
565 {
566 	struct rtable *rt;
567 
568 	rt = rcu_dereference(fnhe->fnhe_rth_input);
569 	if (rt) {
570 		RCU_INIT_POINTER(fnhe->fnhe_rth_input, NULL);
571 		dst_dev_put(&rt->dst);
572 		dst_release(&rt->dst);
573 	}
574 	rt = rcu_dereference(fnhe->fnhe_rth_output);
575 	if (rt) {
576 		RCU_INIT_POINTER(fnhe->fnhe_rth_output, NULL);
577 		dst_dev_put(&rt->dst);
578 		dst_release(&rt->dst);
579 	}
580 }
581 
582 static void fnhe_remove_oldest(struct fnhe_hash_bucket *hash)
583 {
584 	struct fib_nh_exception __rcu **fnhe_p, **oldest_p;
585 	struct fib_nh_exception *fnhe, *oldest = NULL;
586 
587 	for (fnhe_p = &hash->chain; ; fnhe_p = &fnhe->fnhe_next) {
588 		fnhe = rcu_dereference_protected(*fnhe_p,
589 						 lockdep_is_held(&fnhe_lock));
590 		if (!fnhe)
591 			break;
592 		if (!oldest ||
593 		    time_before(fnhe->fnhe_stamp, oldest->fnhe_stamp)) {
594 			oldest = fnhe;
595 			oldest_p = fnhe_p;
596 		}
597 	}
598 	fnhe_flush_routes(oldest);
599 	*oldest_p = oldest->fnhe_next;
600 	kfree_rcu(oldest, rcu);
601 }
602 
603 static u32 fnhe_hashfun(__be32 daddr)
604 {
605 	static siphash_key_t fnhe_hash_key __read_mostly;
606 	u64 hval;
607 
608 	net_get_random_once(&fnhe_hash_key, sizeof(fnhe_hash_key));
609 	hval = siphash_1u32((__force u32)daddr, &fnhe_hash_key);
610 	return hash_64(hval, FNHE_HASH_SHIFT);
611 }
612 
613 static void fill_route_from_fnhe(struct rtable *rt, struct fib_nh_exception *fnhe)
614 {
615 	rt->rt_pmtu = fnhe->fnhe_pmtu;
616 	rt->rt_mtu_locked = fnhe->fnhe_mtu_locked;
617 	rt->dst.expires = fnhe->fnhe_expires;
618 
619 	if (fnhe->fnhe_gw) {
620 		rt->rt_flags |= RTCF_REDIRECTED;
621 		rt->rt_uses_gateway = 1;
622 		rt->rt_gw_family = AF_INET;
623 		rt->rt_gw4 = fnhe->fnhe_gw;
624 	}
625 }
626 
627 static void update_or_create_fnhe(struct fib_nh_common *nhc, __be32 daddr,
628 				  __be32 gw, u32 pmtu, bool lock,
629 				  unsigned long expires)
630 {
631 	struct fnhe_hash_bucket *hash;
632 	struct fib_nh_exception *fnhe;
633 	struct rtable *rt;
634 	u32 genid, hval;
635 	unsigned int i;
636 	int depth;
637 
638 	genid = fnhe_genid(dev_net(nhc->nhc_dev));
639 	hval = fnhe_hashfun(daddr);
640 
641 	spin_lock_bh(&fnhe_lock);
642 
643 	hash = rcu_dereference(nhc->nhc_exceptions);
644 	if (!hash) {
645 		hash = kcalloc(FNHE_HASH_SIZE, sizeof(*hash), GFP_ATOMIC);
646 		if (!hash)
647 			goto out_unlock;
648 		rcu_assign_pointer(nhc->nhc_exceptions, hash);
649 	}
650 
651 	hash += hval;
652 
653 	depth = 0;
654 	for (fnhe = rcu_dereference(hash->chain); fnhe;
655 	     fnhe = rcu_dereference(fnhe->fnhe_next)) {
656 		if (fnhe->fnhe_daddr == daddr)
657 			break;
658 		depth++;
659 	}
660 
661 	if (fnhe) {
662 		if (fnhe->fnhe_genid != genid)
663 			fnhe->fnhe_genid = genid;
664 		if (gw)
665 			fnhe->fnhe_gw = gw;
666 		if (pmtu) {
667 			fnhe->fnhe_pmtu = pmtu;
668 			fnhe->fnhe_mtu_locked = lock;
669 		}
670 		fnhe->fnhe_expires = max(1UL, expires);
671 		/* Update all cached dsts too */
672 		rt = rcu_dereference(fnhe->fnhe_rth_input);
673 		if (rt)
674 			fill_route_from_fnhe(rt, fnhe);
675 		rt = rcu_dereference(fnhe->fnhe_rth_output);
676 		if (rt)
677 			fill_route_from_fnhe(rt, fnhe);
678 	} else {
679 		/* Randomize max depth to avoid some side channels attacks. */
680 		int max_depth = FNHE_RECLAIM_DEPTH +
681 				prandom_u32_max(FNHE_RECLAIM_DEPTH);
682 
683 		while (depth > max_depth) {
684 			fnhe_remove_oldest(hash);
685 			depth--;
686 		}
687 
688 		fnhe = kzalloc(sizeof(*fnhe), GFP_ATOMIC);
689 		if (!fnhe)
690 			goto out_unlock;
691 
692 		fnhe->fnhe_next = hash->chain;
693 
694 		fnhe->fnhe_genid = genid;
695 		fnhe->fnhe_daddr = daddr;
696 		fnhe->fnhe_gw = gw;
697 		fnhe->fnhe_pmtu = pmtu;
698 		fnhe->fnhe_mtu_locked = lock;
699 		fnhe->fnhe_expires = max(1UL, expires);
700 
701 		rcu_assign_pointer(hash->chain, fnhe);
702 
703 		/* Exception created; mark the cached routes for the nexthop
704 		 * stale, so anyone caching it rechecks if this exception
705 		 * applies to them.
706 		 */
707 		rt = rcu_dereference(nhc->nhc_rth_input);
708 		if (rt)
709 			rt->dst.obsolete = DST_OBSOLETE_KILL;
710 
711 		for_each_possible_cpu(i) {
712 			struct rtable __rcu **prt;
713 
714 			prt = per_cpu_ptr(nhc->nhc_pcpu_rth_output, i);
715 			rt = rcu_dereference(*prt);
716 			if (rt)
717 				rt->dst.obsolete = DST_OBSOLETE_KILL;
718 		}
719 	}
720 
721 	fnhe->fnhe_stamp = jiffies;
722 
723 out_unlock:
724 	spin_unlock_bh(&fnhe_lock);
725 }
726 
727 static void __ip_do_redirect(struct rtable *rt, struct sk_buff *skb, struct flowi4 *fl4,
728 			     bool kill_route)
729 {
730 	__be32 new_gw = icmp_hdr(skb)->un.gateway;
731 	__be32 old_gw = ip_hdr(skb)->saddr;
732 	struct net_device *dev = skb->dev;
733 	struct in_device *in_dev;
734 	struct fib_result res;
735 	struct neighbour *n;
736 	struct net *net;
737 
738 	switch (icmp_hdr(skb)->code & 7) {
739 	case ICMP_REDIR_NET:
740 	case ICMP_REDIR_NETTOS:
741 	case ICMP_REDIR_HOST:
742 	case ICMP_REDIR_HOSTTOS:
743 		break;
744 
745 	default:
746 		return;
747 	}
748 
749 	if (rt->rt_gw_family != AF_INET || rt->rt_gw4 != old_gw)
750 		return;
751 
752 	in_dev = __in_dev_get_rcu(dev);
753 	if (!in_dev)
754 		return;
755 
756 	net = dev_net(dev);
757 	if (new_gw == old_gw || !IN_DEV_RX_REDIRECTS(in_dev) ||
758 	    ipv4_is_multicast(new_gw) || ipv4_is_lbcast(new_gw) ||
759 	    ipv4_is_zeronet(new_gw))
760 		goto reject_redirect;
761 
762 	if (!IN_DEV_SHARED_MEDIA(in_dev)) {
763 		if (!inet_addr_onlink(in_dev, new_gw, old_gw))
764 			goto reject_redirect;
765 		if (IN_DEV_SEC_REDIRECTS(in_dev) && ip_fib_check_default(new_gw, dev))
766 			goto reject_redirect;
767 	} else {
768 		if (inet_addr_type(net, new_gw) != RTN_UNICAST)
769 			goto reject_redirect;
770 	}
771 
772 	n = __ipv4_neigh_lookup(rt->dst.dev, new_gw);
773 	if (!n)
774 		n = neigh_create(&arp_tbl, &new_gw, rt->dst.dev);
775 	if (!IS_ERR(n)) {
776 		if (!(n->nud_state & NUD_VALID)) {
777 			neigh_event_send(n, NULL);
778 		} else {
779 			if (fib_lookup(net, fl4, &res, 0) == 0) {
780 				struct fib_nh_common *nhc;
781 
782 				fib_select_path(net, &res, fl4, skb);
783 				nhc = FIB_RES_NHC(res);
784 				update_or_create_fnhe(nhc, fl4->daddr, new_gw,
785 						0, false,
786 						jiffies + ip_rt_gc_timeout);
787 			}
788 			if (kill_route)
789 				rt->dst.obsolete = DST_OBSOLETE_KILL;
790 			call_netevent_notifiers(NETEVENT_NEIGH_UPDATE, n);
791 		}
792 		neigh_release(n);
793 	}
794 	return;
795 
796 reject_redirect:
797 #ifdef CONFIG_IP_ROUTE_VERBOSE
798 	if (IN_DEV_LOG_MARTIANS(in_dev)) {
799 		const struct iphdr *iph = (const struct iphdr *) skb->data;
800 		__be32 daddr = iph->daddr;
801 		__be32 saddr = iph->saddr;
802 
803 		net_info_ratelimited("Redirect from %pI4 on %s about %pI4 ignored\n"
804 				     "  Advised path = %pI4 -> %pI4\n",
805 				     &old_gw, dev->name, &new_gw,
806 				     &saddr, &daddr);
807 	}
808 #endif
809 	;
810 }
811 
812 static void ip_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb)
813 {
814 	struct rtable *rt;
815 	struct flowi4 fl4;
816 	const struct iphdr *iph = (const struct iphdr *) skb->data;
817 	struct net *net = dev_net(skb->dev);
818 	int oif = skb->dev->ifindex;
819 	u8 tos = RT_TOS(iph->tos);
820 	u8 prot = iph->protocol;
821 	u32 mark = skb->mark;
822 
823 	rt = (struct rtable *) dst;
824 
825 	__build_flow_key(net, &fl4, sk, iph, oif, tos, prot, mark, 0);
826 	__ip_do_redirect(rt, skb, &fl4, true);
827 }
828 
829 static struct dst_entry *ipv4_negative_advice(struct dst_entry *dst)
830 {
831 	struct rtable *rt = (struct rtable *)dst;
832 	struct dst_entry *ret = dst;
833 
834 	if (rt) {
835 		if (dst->obsolete > 0) {
836 			ip_rt_put(rt);
837 			ret = NULL;
838 		} else if ((rt->rt_flags & RTCF_REDIRECTED) ||
839 			   rt->dst.expires) {
840 			ip_rt_put(rt);
841 			ret = NULL;
842 		}
843 	}
844 	return ret;
845 }
846 
847 /*
848  * Algorithm:
849  *	1. The first ip_rt_redirect_number redirects are sent
850  *	   with exponential backoff, then we stop sending them at all,
851  *	   assuming that the host ignores our redirects.
852  *	2. If we did not see packets requiring redirects
853  *	   during ip_rt_redirect_silence, we assume that the host
854  *	   forgot redirected route and start to send redirects again.
855  *
856  * This algorithm is much cheaper and more intelligent than dumb load limiting
857  * in icmp.c.
858  *
859  * NOTE. Do not forget to inhibit load limiting for redirects (redundant)
860  * and "frag. need" (breaks PMTU discovery) in icmp.c.
861  */
862 
863 void ip_rt_send_redirect(struct sk_buff *skb)
864 {
865 	struct rtable *rt = skb_rtable(skb);
866 	struct in_device *in_dev;
867 	struct inet_peer *peer;
868 	struct net *net;
869 	int log_martians;
870 	int vif;
871 
872 	rcu_read_lock();
873 	in_dev = __in_dev_get_rcu(rt->dst.dev);
874 	if (!in_dev || !IN_DEV_TX_REDIRECTS(in_dev)) {
875 		rcu_read_unlock();
876 		return;
877 	}
878 	log_martians = IN_DEV_LOG_MARTIANS(in_dev);
879 	vif = l3mdev_master_ifindex_rcu(rt->dst.dev);
880 	rcu_read_unlock();
881 
882 	net = dev_net(rt->dst.dev);
883 	peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, vif, 1);
884 	if (!peer) {
885 		icmp_send(skb, ICMP_REDIRECT, ICMP_REDIR_HOST,
886 			  rt_nexthop(rt, ip_hdr(skb)->daddr));
887 		return;
888 	}
889 
890 	/* No redirected packets during ip_rt_redirect_silence;
891 	 * reset the algorithm.
892 	 */
893 	if (time_after(jiffies, peer->rate_last + ip_rt_redirect_silence)) {
894 		peer->rate_tokens = 0;
895 		peer->n_redirects = 0;
896 	}
897 
898 	/* Too many ignored redirects; do not send anything
899 	 * set dst.rate_last to the last seen redirected packet.
900 	 */
901 	if (peer->n_redirects >= ip_rt_redirect_number) {
902 		peer->rate_last = jiffies;
903 		goto out_put_peer;
904 	}
905 
906 	/* Check for load limit; set rate_last to the latest sent
907 	 * redirect.
908 	 */
909 	if (peer->n_redirects == 0 ||
910 	    time_after(jiffies,
911 		       (peer->rate_last +
912 			(ip_rt_redirect_load << peer->n_redirects)))) {
913 		__be32 gw = rt_nexthop(rt, ip_hdr(skb)->daddr);
914 
915 		icmp_send(skb, ICMP_REDIRECT, ICMP_REDIR_HOST, gw);
916 		peer->rate_last = jiffies;
917 		++peer->n_redirects;
918 #ifdef CONFIG_IP_ROUTE_VERBOSE
919 		if (log_martians &&
920 		    peer->n_redirects == ip_rt_redirect_number)
921 			net_warn_ratelimited("host %pI4/if%d ignores redirects for %pI4 to %pI4\n",
922 					     &ip_hdr(skb)->saddr, inet_iif(skb),
923 					     &ip_hdr(skb)->daddr, &gw);
924 #endif
925 	}
926 out_put_peer:
927 	inet_putpeer(peer);
928 }
929 
930 static int ip_error(struct sk_buff *skb)
931 {
932 	struct rtable *rt = skb_rtable(skb);
933 	struct net_device *dev = skb->dev;
934 	struct in_device *in_dev;
935 	struct inet_peer *peer;
936 	unsigned long now;
937 	struct net *net;
938 	bool send;
939 	int code;
940 
941 	if (netif_is_l3_master(skb->dev)) {
942 		dev = __dev_get_by_index(dev_net(skb->dev), IPCB(skb)->iif);
943 		if (!dev)
944 			goto out;
945 	}
946 
947 	in_dev = __in_dev_get_rcu(dev);
948 
949 	/* IP on this device is disabled. */
950 	if (!in_dev)
951 		goto out;
952 
953 	net = dev_net(rt->dst.dev);
954 	if (!IN_DEV_FORWARD(in_dev)) {
955 		switch (rt->dst.error) {
956 		case EHOSTUNREACH:
957 			__IP_INC_STATS(net, IPSTATS_MIB_INADDRERRORS);
958 			break;
959 
960 		case ENETUNREACH:
961 			__IP_INC_STATS(net, IPSTATS_MIB_INNOROUTES);
962 			break;
963 		}
964 		goto out;
965 	}
966 
967 	switch (rt->dst.error) {
968 	case EINVAL:
969 	default:
970 		goto out;
971 	case EHOSTUNREACH:
972 		code = ICMP_HOST_UNREACH;
973 		break;
974 	case ENETUNREACH:
975 		code = ICMP_NET_UNREACH;
976 		__IP_INC_STATS(net, IPSTATS_MIB_INNOROUTES);
977 		break;
978 	case EACCES:
979 		code = ICMP_PKT_FILTERED;
980 		break;
981 	}
982 
983 	peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr,
984 			       l3mdev_master_ifindex(skb->dev), 1);
985 
986 	send = true;
987 	if (peer) {
988 		now = jiffies;
989 		peer->rate_tokens += now - peer->rate_last;
990 		if (peer->rate_tokens > ip_rt_error_burst)
991 			peer->rate_tokens = ip_rt_error_burst;
992 		peer->rate_last = now;
993 		if (peer->rate_tokens >= ip_rt_error_cost)
994 			peer->rate_tokens -= ip_rt_error_cost;
995 		else
996 			send = false;
997 		inet_putpeer(peer);
998 	}
999 	if (send)
1000 		icmp_send(skb, ICMP_DEST_UNREACH, code, 0);
1001 
1002 out:	kfree_skb(skb);
1003 	return 0;
1004 }
1005 
1006 static void __ip_rt_update_pmtu(struct rtable *rt, struct flowi4 *fl4, u32 mtu)
1007 {
1008 	struct dst_entry *dst = &rt->dst;
1009 	struct net *net = dev_net(dst->dev);
1010 	struct fib_result res;
1011 	bool lock = false;
1012 	u32 old_mtu;
1013 
1014 	if (ip_mtu_locked(dst))
1015 		return;
1016 
1017 	old_mtu = ipv4_mtu(dst);
1018 	if (old_mtu < mtu)
1019 		return;
1020 
1021 	if (mtu < ip_rt_min_pmtu) {
1022 		lock = true;
1023 		mtu = min(old_mtu, ip_rt_min_pmtu);
1024 	}
1025 
1026 	if (rt->rt_pmtu == mtu && !lock &&
1027 	    time_before(jiffies, dst->expires - ip_rt_mtu_expires / 2))
1028 		return;
1029 
1030 	rcu_read_lock();
1031 	if (fib_lookup(net, fl4, &res, 0) == 0) {
1032 		struct fib_nh_common *nhc;
1033 
1034 		fib_select_path(net, &res, fl4, NULL);
1035 		nhc = FIB_RES_NHC(res);
1036 		update_or_create_fnhe(nhc, fl4->daddr, 0, mtu, lock,
1037 				      jiffies + ip_rt_mtu_expires);
1038 	}
1039 	rcu_read_unlock();
1040 }
1041 
1042 static void ip_rt_update_pmtu(struct dst_entry *dst, struct sock *sk,
1043 			      struct sk_buff *skb, u32 mtu,
1044 			      bool confirm_neigh)
1045 {
1046 	struct rtable *rt = (struct rtable *) dst;
1047 	struct flowi4 fl4;
1048 
1049 	ip_rt_build_flow_key(&fl4, sk, skb);
1050 
1051 	/* Don't make lookup fail for bridged encapsulations */
1052 	if (skb && netif_is_any_bridge_port(skb->dev))
1053 		fl4.flowi4_oif = 0;
1054 
1055 	__ip_rt_update_pmtu(rt, &fl4, mtu);
1056 }
1057 
1058 void ipv4_update_pmtu(struct sk_buff *skb, struct net *net, u32 mtu,
1059 		      int oif, u8 protocol)
1060 {
1061 	const struct iphdr *iph = (const struct iphdr *)skb->data;
1062 	struct flowi4 fl4;
1063 	struct rtable *rt;
1064 	u32 mark = IP4_REPLY_MARK(net, skb->mark);
1065 
1066 	__build_flow_key(net, &fl4, NULL, iph, oif,
1067 			 RT_TOS(iph->tos), protocol, mark, 0);
1068 	rt = __ip_route_output_key(net, &fl4);
1069 	if (!IS_ERR(rt)) {
1070 		__ip_rt_update_pmtu(rt, &fl4, mtu);
1071 		ip_rt_put(rt);
1072 	}
1073 }
1074 EXPORT_SYMBOL_GPL(ipv4_update_pmtu);
1075 
1076 static void __ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu)
1077 {
1078 	const struct iphdr *iph = (const struct iphdr *)skb->data;
1079 	struct flowi4 fl4;
1080 	struct rtable *rt;
1081 
1082 	__build_flow_key(sock_net(sk), &fl4, sk, iph, 0, 0, 0, 0, 0);
1083 
1084 	if (!fl4.flowi4_mark)
1085 		fl4.flowi4_mark = IP4_REPLY_MARK(sock_net(sk), skb->mark);
1086 
1087 	rt = __ip_route_output_key(sock_net(sk), &fl4);
1088 	if (!IS_ERR(rt)) {
1089 		__ip_rt_update_pmtu(rt, &fl4, mtu);
1090 		ip_rt_put(rt);
1091 	}
1092 }
1093 
1094 void ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu)
1095 {
1096 	const struct iphdr *iph = (const struct iphdr *)skb->data;
1097 	struct flowi4 fl4;
1098 	struct rtable *rt;
1099 	struct dst_entry *odst = NULL;
1100 	bool new = false;
1101 	struct net *net = sock_net(sk);
1102 
1103 	bh_lock_sock(sk);
1104 
1105 	if (!ip_sk_accept_pmtu(sk))
1106 		goto out;
1107 
1108 	odst = sk_dst_get(sk);
1109 
1110 	if (sock_owned_by_user(sk) || !odst) {
1111 		__ipv4_sk_update_pmtu(skb, sk, mtu);
1112 		goto out;
1113 	}
1114 
1115 	__build_flow_key(net, &fl4, sk, iph, 0, 0, 0, 0, 0);
1116 
1117 	rt = (struct rtable *)odst;
1118 	if (odst->obsolete && !odst->ops->check(odst, 0)) {
1119 		rt = ip_route_output_flow(sock_net(sk), &fl4, sk);
1120 		if (IS_ERR(rt))
1121 			goto out;
1122 
1123 		new = true;
1124 	}
1125 
1126 	__ip_rt_update_pmtu((struct rtable *)xfrm_dst_path(&rt->dst), &fl4, mtu);
1127 
1128 	if (!dst_check(&rt->dst, 0)) {
1129 		if (new)
1130 			dst_release(&rt->dst);
1131 
1132 		rt = ip_route_output_flow(sock_net(sk), &fl4, sk);
1133 		if (IS_ERR(rt))
1134 			goto out;
1135 
1136 		new = true;
1137 	}
1138 
1139 	if (new)
1140 		sk_dst_set(sk, &rt->dst);
1141 
1142 out:
1143 	bh_unlock_sock(sk);
1144 	dst_release(odst);
1145 }
1146 EXPORT_SYMBOL_GPL(ipv4_sk_update_pmtu);
1147 
1148 void ipv4_redirect(struct sk_buff *skb, struct net *net,
1149 		   int oif, u8 protocol)
1150 {
1151 	const struct iphdr *iph = (const struct iphdr *)skb->data;
1152 	struct flowi4 fl4;
1153 	struct rtable *rt;
1154 
1155 	__build_flow_key(net, &fl4, NULL, iph, oif,
1156 			 RT_TOS(iph->tos), protocol, 0, 0);
1157 	rt = __ip_route_output_key(net, &fl4);
1158 	if (!IS_ERR(rt)) {
1159 		__ip_do_redirect(rt, skb, &fl4, false);
1160 		ip_rt_put(rt);
1161 	}
1162 }
1163 EXPORT_SYMBOL_GPL(ipv4_redirect);
1164 
1165 void ipv4_sk_redirect(struct sk_buff *skb, struct sock *sk)
1166 {
1167 	const struct iphdr *iph = (const struct iphdr *)skb->data;
1168 	struct flowi4 fl4;
1169 	struct rtable *rt;
1170 	struct net *net = sock_net(sk);
1171 
1172 	__build_flow_key(net, &fl4, sk, iph, 0, 0, 0, 0, 0);
1173 	rt = __ip_route_output_key(net, &fl4);
1174 	if (!IS_ERR(rt)) {
1175 		__ip_do_redirect(rt, skb, &fl4, false);
1176 		ip_rt_put(rt);
1177 	}
1178 }
1179 EXPORT_SYMBOL_GPL(ipv4_sk_redirect);
1180 
1181 INDIRECT_CALLABLE_SCOPE struct dst_entry *ipv4_dst_check(struct dst_entry *dst,
1182 							 u32 cookie)
1183 {
1184 	struct rtable *rt = (struct rtable *) dst;
1185 
1186 	/* All IPV4 dsts are created with ->obsolete set to the value
1187 	 * DST_OBSOLETE_FORCE_CHK which forces validation calls down
1188 	 * into this function always.
1189 	 *
1190 	 * When a PMTU/redirect information update invalidates a route,
1191 	 * this is indicated by setting obsolete to DST_OBSOLETE_KILL or
1192 	 * DST_OBSOLETE_DEAD.
1193 	 */
1194 	if (dst->obsolete != DST_OBSOLETE_FORCE_CHK || rt_is_expired(rt))
1195 		return NULL;
1196 	return dst;
1197 }
1198 EXPORT_INDIRECT_CALLABLE(ipv4_dst_check);
1199 
1200 static void ipv4_send_dest_unreach(struct sk_buff *skb)
1201 {
1202 	struct ip_options opt;
1203 	int res;
1204 
1205 	/* Recompile ip options since IPCB may not be valid anymore.
1206 	 * Also check we have a reasonable ipv4 header.
1207 	 */
1208 	if (!pskb_network_may_pull(skb, sizeof(struct iphdr)) ||
1209 	    ip_hdr(skb)->version != 4 || ip_hdr(skb)->ihl < 5)
1210 		return;
1211 
1212 	memset(&opt, 0, sizeof(opt));
1213 	if (ip_hdr(skb)->ihl > 5) {
1214 		if (!pskb_network_may_pull(skb, ip_hdr(skb)->ihl * 4))
1215 			return;
1216 		opt.optlen = ip_hdr(skb)->ihl * 4 - sizeof(struct iphdr);
1217 
1218 		rcu_read_lock();
1219 		res = __ip_options_compile(dev_net(skb->dev), &opt, skb, NULL);
1220 		rcu_read_unlock();
1221 
1222 		if (res)
1223 			return;
1224 	}
1225 	__icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, 0, &opt);
1226 }
1227 
1228 static void ipv4_link_failure(struct sk_buff *skb)
1229 {
1230 	struct rtable *rt;
1231 
1232 	ipv4_send_dest_unreach(skb);
1233 
1234 	rt = skb_rtable(skb);
1235 	if (rt)
1236 		dst_set_expires(&rt->dst, 0);
1237 }
1238 
1239 static int ip_rt_bug(struct net *net, struct sock *sk, struct sk_buff *skb)
1240 {
1241 	pr_debug("%s: %pI4 -> %pI4, %s\n",
1242 		 __func__, &ip_hdr(skb)->saddr, &ip_hdr(skb)->daddr,
1243 		 skb->dev ? skb->dev->name : "?");
1244 	kfree_skb(skb);
1245 	WARN_ON(1);
1246 	return 0;
1247 }
1248 
1249 /*
1250  * We do not cache source address of outgoing interface,
1251  * because it is used only by IP RR, TS and SRR options,
1252  * so that it out of fast path.
1253  *
1254  * BTW remember: "addr" is allowed to be not aligned
1255  * in IP options!
1256  */
1257 
1258 void ip_rt_get_source(u8 *addr, struct sk_buff *skb, struct rtable *rt)
1259 {
1260 	__be32 src;
1261 
1262 	if (rt_is_output_route(rt))
1263 		src = ip_hdr(skb)->saddr;
1264 	else {
1265 		struct fib_result res;
1266 		struct iphdr *iph = ip_hdr(skb);
1267 		struct flowi4 fl4 = {
1268 			.daddr = iph->daddr,
1269 			.saddr = iph->saddr,
1270 			.flowi4_tos = RT_TOS(iph->tos),
1271 			.flowi4_oif = rt->dst.dev->ifindex,
1272 			.flowi4_iif = skb->dev->ifindex,
1273 			.flowi4_mark = skb->mark,
1274 		};
1275 
1276 		rcu_read_lock();
1277 		if (fib_lookup(dev_net(rt->dst.dev), &fl4, &res, 0) == 0)
1278 			src = fib_result_prefsrc(dev_net(rt->dst.dev), &res);
1279 		else
1280 			src = inet_select_addr(rt->dst.dev,
1281 					       rt_nexthop(rt, iph->daddr),
1282 					       RT_SCOPE_UNIVERSE);
1283 		rcu_read_unlock();
1284 	}
1285 	memcpy(addr, &src, 4);
1286 }
1287 
1288 #ifdef CONFIG_IP_ROUTE_CLASSID
1289 static void set_class_tag(struct rtable *rt, u32 tag)
1290 {
1291 	if (!(rt->dst.tclassid & 0xFFFF))
1292 		rt->dst.tclassid |= tag & 0xFFFF;
1293 	if (!(rt->dst.tclassid & 0xFFFF0000))
1294 		rt->dst.tclassid |= tag & 0xFFFF0000;
1295 }
1296 #endif
1297 
1298 static unsigned int ipv4_default_advmss(const struct dst_entry *dst)
1299 {
1300 	unsigned int header_size = sizeof(struct tcphdr) + sizeof(struct iphdr);
1301 	unsigned int advmss = max_t(unsigned int, ipv4_mtu(dst) - header_size,
1302 				    ip_rt_min_advmss);
1303 
1304 	return min(advmss, IPV4_MAX_PMTU - header_size);
1305 }
1306 
1307 INDIRECT_CALLABLE_SCOPE unsigned int ipv4_mtu(const struct dst_entry *dst)
1308 {
1309 	return ip_dst_mtu_maybe_forward(dst, false);
1310 }
1311 EXPORT_INDIRECT_CALLABLE(ipv4_mtu);
1312 
1313 static void ip_del_fnhe(struct fib_nh_common *nhc, __be32 daddr)
1314 {
1315 	struct fnhe_hash_bucket *hash;
1316 	struct fib_nh_exception *fnhe, __rcu **fnhe_p;
1317 	u32 hval = fnhe_hashfun(daddr);
1318 
1319 	spin_lock_bh(&fnhe_lock);
1320 
1321 	hash = rcu_dereference_protected(nhc->nhc_exceptions,
1322 					 lockdep_is_held(&fnhe_lock));
1323 	hash += hval;
1324 
1325 	fnhe_p = &hash->chain;
1326 	fnhe = rcu_dereference_protected(*fnhe_p, lockdep_is_held(&fnhe_lock));
1327 	while (fnhe) {
1328 		if (fnhe->fnhe_daddr == daddr) {
1329 			rcu_assign_pointer(*fnhe_p, rcu_dereference_protected(
1330 				fnhe->fnhe_next, lockdep_is_held(&fnhe_lock)));
1331 			/* set fnhe_daddr to 0 to ensure it won't bind with
1332 			 * new dsts in rt_bind_exception().
1333 			 */
1334 			fnhe->fnhe_daddr = 0;
1335 			fnhe_flush_routes(fnhe);
1336 			kfree_rcu(fnhe, rcu);
1337 			break;
1338 		}
1339 		fnhe_p = &fnhe->fnhe_next;
1340 		fnhe = rcu_dereference_protected(fnhe->fnhe_next,
1341 						 lockdep_is_held(&fnhe_lock));
1342 	}
1343 
1344 	spin_unlock_bh(&fnhe_lock);
1345 }
1346 
1347 static struct fib_nh_exception *find_exception(struct fib_nh_common *nhc,
1348 					       __be32 daddr)
1349 {
1350 	struct fnhe_hash_bucket *hash = rcu_dereference(nhc->nhc_exceptions);
1351 	struct fib_nh_exception *fnhe;
1352 	u32 hval;
1353 
1354 	if (!hash)
1355 		return NULL;
1356 
1357 	hval = fnhe_hashfun(daddr);
1358 
1359 	for (fnhe = rcu_dereference(hash[hval].chain); fnhe;
1360 	     fnhe = rcu_dereference(fnhe->fnhe_next)) {
1361 		if (fnhe->fnhe_daddr == daddr) {
1362 			if (fnhe->fnhe_expires &&
1363 			    time_after(jiffies, fnhe->fnhe_expires)) {
1364 				ip_del_fnhe(nhc, daddr);
1365 				break;
1366 			}
1367 			return fnhe;
1368 		}
1369 	}
1370 	return NULL;
1371 }
1372 
1373 /* MTU selection:
1374  * 1. mtu on route is locked - use it
1375  * 2. mtu from nexthop exception
1376  * 3. mtu from egress device
1377  */
1378 
1379 u32 ip_mtu_from_fib_result(struct fib_result *res, __be32 daddr)
1380 {
1381 	struct fib_nh_common *nhc = res->nhc;
1382 	struct net_device *dev = nhc->nhc_dev;
1383 	struct fib_info *fi = res->fi;
1384 	u32 mtu = 0;
1385 
1386 	if (dev_net(dev)->ipv4.sysctl_ip_fwd_use_pmtu ||
1387 	    fi->fib_metrics->metrics[RTAX_LOCK - 1] & (1 << RTAX_MTU))
1388 		mtu = fi->fib_mtu;
1389 
1390 	if (likely(!mtu)) {
1391 		struct fib_nh_exception *fnhe;
1392 
1393 		fnhe = find_exception(nhc, daddr);
1394 		if (fnhe && !time_after_eq(jiffies, fnhe->fnhe_expires))
1395 			mtu = fnhe->fnhe_pmtu;
1396 	}
1397 
1398 	if (likely(!mtu))
1399 		mtu = min(READ_ONCE(dev->mtu), IP_MAX_MTU);
1400 
1401 	return mtu - lwtunnel_headroom(nhc->nhc_lwtstate, mtu);
1402 }
1403 
1404 static bool rt_bind_exception(struct rtable *rt, struct fib_nh_exception *fnhe,
1405 			      __be32 daddr, const bool do_cache)
1406 {
1407 	bool ret = false;
1408 
1409 	spin_lock_bh(&fnhe_lock);
1410 
1411 	if (daddr == fnhe->fnhe_daddr) {
1412 		struct rtable __rcu **porig;
1413 		struct rtable *orig;
1414 		int genid = fnhe_genid(dev_net(rt->dst.dev));
1415 
1416 		if (rt_is_input_route(rt))
1417 			porig = &fnhe->fnhe_rth_input;
1418 		else
1419 			porig = &fnhe->fnhe_rth_output;
1420 		orig = rcu_dereference(*porig);
1421 
1422 		if (fnhe->fnhe_genid != genid) {
1423 			fnhe->fnhe_genid = genid;
1424 			fnhe->fnhe_gw = 0;
1425 			fnhe->fnhe_pmtu = 0;
1426 			fnhe->fnhe_expires = 0;
1427 			fnhe->fnhe_mtu_locked = false;
1428 			fnhe_flush_routes(fnhe);
1429 			orig = NULL;
1430 		}
1431 		fill_route_from_fnhe(rt, fnhe);
1432 		if (!rt->rt_gw4) {
1433 			rt->rt_gw4 = daddr;
1434 			rt->rt_gw_family = AF_INET;
1435 		}
1436 
1437 		if (do_cache) {
1438 			dst_hold(&rt->dst);
1439 			rcu_assign_pointer(*porig, rt);
1440 			if (orig) {
1441 				dst_dev_put(&orig->dst);
1442 				dst_release(&orig->dst);
1443 			}
1444 			ret = true;
1445 		}
1446 
1447 		fnhe->fnhe_stamp = jiffies;
1448 	}
1449 	spin_unlock_bh(&fnhe_lock);
1450 
1451 	return ret;
1452 }
1453 
1454 static bool rt_cache_route(struct fib_nh_common *nhc, struct rtable *rt)
1455 {
1456 	struct rtable *orig, *prev, **p;
1457 	bool ret = true;
1458 
1459 	if (rt_is_input_route(rt)) {
1460 		p = (struct rtable **)&nhc->nhc_rth_input;
1461 	} else {
1462 		p = (struct rtable **)raw_cpu_ptr(nhc->nhc_pcpu_rth_output);
1463 	}
1464 	orig = *p;
1465 
1466 	/* hold dst before doing cmpxchg() to avoid race condition
1467 	 * on this dst
1468 	 */
1469 	dst_hold(&rt->dst);
1470 	prev = cmpxchg(p, orig, rt);
1471 	if (prev == orig) {
1472 		if (orig) {
1473 			rt_add_uncached_list(orig);
1474 			dst_release(&orig->dst);
1475 		}
1476 	} else {
1477 		dst_release(&rt->dst);
1478 		ret = false;
1479 	}
1480 
1481 	return ret;
1482 }
1483 
1484 struct uncached_list {
1485 	spinlock_t		lock;
1486 	struct list_head	head;
1487 };
1488 
1489 static DEFINE_PER_CPU_ALIGNED(struct uncached_list, rt_uncached_list);
1490 
1491 void rt_add_uncached_list(struct rtable *rt)
1492 {
1493 	struct uncached_list *ul = raw_cpu_ptr(&rt_uncached_list);
1494 
1495 	rt->rt_uncached_list = ul;
1496 
1497 	spin_lock_bh(&ul->lock);
1498 	list_add_tail(&rt->rt_uncached, &ul->head);
1499 	spin_unlock_bh(&ul->lock);
1500 }
1501 
1502 void rt_del_uncached_list(struct rtable *rt)
1503 {
1504 	if (!list_empty(&rt->rt_uncached)) {
1505 		struct uncached_list *ul = rt->rt_uncached_list;
1506 
1507 		spin_lock_bh(&ul->lock);
1508 		list_del(&rt->rt_uncached);
1509 		spin_unlock_bh(&ul->lock);
1510 	}
1511 }
1512 
1513 static void ipv4_dst_destroy(struct dst_entry *dst)
1514 {
1515 	struct rtable *rt = (struct rtable *)dst;
1516 
1517 	ip_dst_metrics_put(dst);
1518 	rt_del_uncached_list(rt);
1519 }
1520 
1521 void rt_flush_dev(struct net_device *dev)
1522 {
1523 	struct rtable *rt;
1524 	int cpu;
1525 
1526 	for_each_possible_cpu(cpu) {
1527 		struct uncached_list *ul = &per_cpu(rt_uncached_list, cpu);
1528 
1529 		spin_lock_bh(&ul->lock);
1530 		list_for_each_entry(rt, &ul->head, rt_uncached) {
1531 			if (rt->dst.dev != dev)
1532 				continue;
1533 			rt->dst.dev = blackhole_netdev;
1534 			dev_hold(rt->dst.dev);
1535 			dev_put(dev);
1536 		}
1537 		spin_unlock_bh(&ul->lock);
1538 	}
1539 }
1540 
1541 static bool rt_cache_valid(const struct rtable *rt)
1542 {
1543 	return	rt &&
1544 		rt->dst.obsolete == DST_OBSOLETE_FORCE_CHK &&
1545 		!rt_is_expired(rt);
1546 }
1547 
1548 static void rt_set_nexthop(struct rtable *rt, __be32 daddr,
1549 			   const struct fib_result *res,
1550 			   struct fib_nh_exception *fnhe,
1551 			   struct fib_info *fi, u16 type, u32 itag,
1552 			   const bool do_cache)
1553 {
1554 	bool cached = false;
1555 
1556 	if (fi) {
1557 		struct fib_nh_common *nhc = FIB_RES_NHC(*res);
1558 
1559 		if (nhc->nhc_gw_family && nhc->nhc_scope == RT_SCOPE_LINK) {
1560 			rt->rt_uses_gateway = 1;
1561 			rt->rt_gw_family = nhc->nhc_gw_family;
1562 			/* only INET and INET6 are supported */
1563 			if (likely(nhc->nhc_gw_family == AF_INET))
1564 				rt->rt_gw4 = nhc->nhc_gw.ipv4;
1565 			else
1566 				rt->rt_gw6 = nhc->nhc_gw.ipv6;
1567 		}
1568 
1569 		ip_dst_init_metrics(&rt->dst, fi->fib_metrics);
1570 
1571 #ifdef CONFIG_IP_ROUTE_CLASSID
1572 		if (nhc->nhc_family == AF_INET) {
1573 			struct fib_nh *nh;
1574 
1575 			nh = container_of(nhc, struct fib_nh, nh_common);
1576 			rt->dst.tclassid = nh->nh_tclassid;
1577 		}
1578 #endif
1579 		rt->dst.lwtstate = lwtstate_get(nhc->nhc_lwtstate);
1580 		if (unlikely(fnhe))
1581 			cached = rt_bind_exception(rt, fnhe, daddr, do_cache);
1582 		else if (do_cache)
1583 			cached = rt_cache_route(nhc, rt);
1584 		if (unlikely(!cached)) {
1585 			/* Routes we intend to cache in nexthop exception or
1586 			 * FIB nexthop have the DST_NOCACHE bit clear.
1587 			 * However, if we are unsuccessful at storing this
1588 			 * route into the cache we really need to set it.
1589 			 */
1590 			if (!rt->rt_gw4) {
1591 				rt->rt_gw_family = AF_INET;
1592 				rt->rt_gw4 = daddr;
1593 			}
1594 			rt_add_uncached_list(rt);
1595 		}
1596 	} else
1597 		rt_add_uncached_list(rt);
1598 
1599 #ifdef CONFIG_IP_ROUTE_CLASSID
1600 #ifdef CONFIG_IP_MULTIPLE_TABLES
1601 	set_class_tag(rt, res->tclassid);
1602 #endif
1603 	set_class_tag(rt, itag);
1604 #endif
1605 }
1606 
1607 struct rtable *rt_dst_alloc(struct net_device *dev,
1608 			    unsigned int flags, u16 type,
1609 			    bool nopolicy, bool noxfrm)
1610 {
1611 	struct rtable *rt;
1612 
1613 	rt = dst_alloc(&ipv4_dst_ops, dev, 1, DST_OBSOLETE_FORCE_CHK,
1614 		       (nopolicy ? DST_NOPOLICY : 0) |
1615 		       (noxfrm ? DST_NOXFRM : 0));
1616 
1617 	if (rt) {
1618 		rt->rt_genid = rt_genid_ipv4(dev_net(dev));
1619 		rt->rt_flags = flags;
1620 		rt->rt_type = type;
1621 		rt->rt_is_input = 0;
1622 		rt->rt_iif = 0;
1623 		rt->rt_pmtu = 0;
1624 		rt->rt_mtu_locked = 0;
1625 		rt->rt_uses_gateway = 0;
1626 		rt->rt_gw_family = 0;
1627 		rt->rt_gw4 = 0;
1628 		INIT_LIST_HEAD(&rt->rt_uncached);
1629 
1630 		rt->dst.output = ip_output;
1631 		if (flags & RTCF_LOCAL)
1632 			rt->dst.input = ip_local_deliver;
1633 	}
1634 
1635 	return rt;
1636 }
1637 EXPORT_SYMBOL(rt_dst_alloc);
1638 
1639 struct rtable *rt_dst_clone(struct net_device *dev, struct rtable *rt)
1640 {
1641 	struct rtable *new_rt;
1642 
1643 	new_rt = dst_alloc(&ipv4_dst_ops, dev, 1, DST_OBSOLETE_FORCE_CHK,
1644 			   rt->dst.flags);
1645 
1646 	if (new_rt) {
1647 		new_rt->rt_genid = rt_genid_ipv4(dev_net(dev));
1648 		new_rt->rt_flags = rt->rt_flags;
1649 		new_rt->rt_type = rt->rt_type;
1650 		new_rt->rt_is_input = rt->rt_is_input;
1651 		new_rt->rt_iif = rt->rt_iif;
1652 		new_rt->rt_pmtu = rt->rt_pmtu;
1653 		new_rt->rt_mtu_locked = rt->rt_mtu_locked;
1654 		new_rt->rt_gw_family = rt->rt_gw_family;
1655 		if (rt->rt_gw_family == AF_INET)
1656 			new_rt->rt_gw4 = rt->rt_gw4;
1657 		else if (rt->rt_gw_family == AF_INET6)
1658 			new_rt->rt_gw6 = rt->rt_gw6;
1659 		INIT_LIST_HEAD(&new_rt->rt_uncached);
1660 
1661 		new_rt->dst.input = rt->dst.input;
1662 		new_rt->dst.output = rt->dst.output;
1663 		new_rt->dst.error = rt->dst.error;
1664 		new_rt->dst.lastuse = jiffies;
1665 		new_rt->dst.lwtstate = lwtstate_get(rt->dst.lwtstate);
1666 	}
1667 	return new_rt;
1668 }
1669 EXPORT_SYMBOL(rt_dst_clone);
1670 
1671 /* called in rcu_read_lock() section */
1672 int ip_mc_validate_source(struct sk_buff *skb, __be32 daddr, __be32 saddr,
1673 			  u8 tos, struct net_device *dev,
1674 			  struct in_device *in_dev, u32 *itag)
1675 {
1676 	int err;
1677 
1678 	/* Primary sanity checks. */
1679 	if (!in_dev)
1680 		return -EINVAL;
1681 
1682 	if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr) ||
1683 	    skb->protocol != htons(ETH_P_IP))
1684 		return -EINVAL;
1685 
1686 	if (ipv4_is_loopback(saddr) && !IN_DEV_ROUTE_LOCALNET(in_dev))
1687 		return -EINVAL;
1688 
1689 	if (ipv4_is_zeronet(saddr)) {
1690 		if (!ipv4_is_local_multicast(daddr) &&
1691 		    ip_hdr(skb)->protocol != IPPROTO_IGMP)
1692 			return -EINVAL;
1693 	} else {
1694 		err = fib_validate_source(skb, saddr, 0, tos, 0, dev,
1695 					  in_dev, itag);
1696 		if (err < 0)
1697 			return err;
1698 	}
1699 	return 0;
1700 }
1701 
1702 /* called in rcu_read_lock() section */
1703 static int ip_route_input_mc(struct sk_buff *skb, __be32 daddr, __be32 saddr,
1704 			     u8 tos, struct net_device *dev, int our)
1705 {
1706 	struct in_device *in_dev = __in_dev_get_rcu(dev);
1707 	unsigned int flags = RTCF_MULTICAST;
1708 	struct rtable *rth;
1709 	u32 itag = 0;
1710 	int err;
1711 
1712 	err = ip_mc_validate_source(skb, daddr, saddr, tos, dev, in_dev, &itag);
1713 	if (err)
1714 		return err;
1715 
1716 	if (our)
1717 		flags |= RTCF_LOCAL;
1718 
1719 	rth = rt_dst_alloc(dev_net(dev)->loopback_dev, flags, RTN_MULTICAST,
1720 			   IN_DEV_ORCONF(in_dev, NOPOLICY), false);
1721 	if (!rth)
1722 		return -ENOBUFS;
1723 
1724 #ifdef CONFIG_IP_ROUTE_CLASSID
1725 	rth->dst.tclassid = itag;
1726 #endif
1727 	rth->dst.output = ip_rt_bug;
1728 	rth->rt_is_input= 1;
1729 
1730 #ifdef CONFIG_IP_MROUTE
1731 	if (!ipv4_is_local_multicast(daddr) && IN_DEV_MFORWARD(in_dev))
1732 		rth->dst.input = ip_mr_input;
1733 #endif
1734 	RT_CACHE_STAT_INC(in_slow_mc);
1735 
1736 	skb_dst_set(skb, &rth->dst);
1737 	return 0;
1738 }
1739 
1740 
1741 static void ip_handle_martian_source(struct net_device *dev,
1742 				     struct in_device *in_dev,
1743 				     struct sk_buff *skb,
1744 				     __be32 daddr,
1745 				     __be32 saddr)
1746 {
1747 	RT_CACHE_STAT_INC(in_martian_src);
1748 #ifdef CONFIG_IP_ROUTE_VERBOSE
1749 	if (IN_DEV_LOG_MARTIANS(in_dev) && net_ratelimit()) {
1750 		/*
1751 		 *	RFC1812 recommendation, if source is martian,
1752 		 *	the only hint is MAC header.
1753 		 */
1754 		pr_warn("martian source %pI4 from %pI4, on dev %s\n",
1755 			&daddr, &saddr, dev->name);
1756 		if (dev->hard_header_len && skb_mac_header_was_set(skb)) {
1757 			print_hex_dump(KERN_WARNING, "ll header: ",
1758 				       DUMP_PREFIX_OFFSET, 16, 1,
1759 				       skb_mac_header(skb),
1760 				       dev->hard_header_len, false);
1761 		}
1762 	}
1763 #endif
1764 }
1765 
1766 /* called in rcu_read_lock() section */
1767 static int __mkroute_input(struct sk_buff *skb,
1768 			   const struct fib_result *res,
1769 			   struct in_device *in_dev,
1770 			   __be32 daddr, __be32 saddr, u32 tos)
1771 {
1772 	struct fib_nh_common *nhc = FIB_RES_NHC(*res);
1773 	struct net_device *dev = nhc->nhc_dev;
1774 	struct fib_nh_exception *fnhe;
1775 	struct rtable *rth;
1776 	int err;
1777 	struct in_device *out_dev;
1778 	bool do_cache;
1779 	u32 itag = 0;
1780 
1781 	/* get a working reference to the output device */
1782 	out_dev = __in_dev_get_rcu(dev);
1783 	if (!out_dev) {
1784 		net_crit_ratelimited("Bug in ip_route_input_slow(). Please report.\n");
1785 		return -EINVAL;
1786 	}
1787 
1788 	err = fib_validate_source(skb, saddr, daddr, tos, FIB_RES_OIF(*res),
1789 				  in_dev->dev, in_dev, &itag);
1790 	if (err < 0) {
1791 		ip_handle_martian_source(in_dev->dev, in_dev, skb, daddr,
1792 					 saddr);
1793 
1794 		goto cleanup;
1795 	}
1796 
1797 	do_cache = res->fi && !itag;
1798 	if (out_dev == in_dev && err && IN_DEV_TX_REDIRECTS(out_dev) &&
1799 	    skb->protocol == htons(ETH_P_IP)) {
1800 		__be32 gw;
1801 
1802 		gw = nhc->nhc_gw_family == AF_INET ? nhc->nhc_gw.ipv4 : 0;
1803 		if (IN_DEV_SHARED_MEDIA(out_dev) ||
1804 		    inet_addr_onlink(out_dev, saddr, gw))
1805 			IPCB(skb)->flags |= IPSKB_DOREDIRECT;
1806 	}
1807 
1808 	if (skb->protocol != htons(ETH_P_IP)) {
1809 		/* Not IP (i.e. ARP). Do not create route, if it is
1810 		 * invalid for proxy arp. DNAT routes are always valid.
1811 		 *
1812 		 * Proxy arp feature have been extended to allow, ARP
1813 		 * replies back to the same interface, to support
1814 		 * Private VLAN switch technologies. See arp.c.
1815 		 */
1816 		if (out_dev == in_dev &&
1817 		    IN_DEV_PROXY_ARP_PVLAN(in_dev) == 0) {
1818 			err = -EINVAL;
1819 			goto cleanup;
1820 		}
1821 	}
1822 
1823 	fnhe = find_exception(nhc, daddr);
1824 	if (do_cache) {
1825 		if (fnhe)
1826 			rth = rcu_dereference(fnhe->fnhe_rth_input);
1827 		else
1828 			rth = rcu_dereference(nhc->nhc_rth_input);
1829 		if (rt_cache_valid(rth)) {
1830 			skb_dst_set_noref(skb, &rth->dst);
1831 			goto out;
1832 		}
1833 	}
1834 
1835 	rth = rt_dst_alloc(out_dev->dev, 0, res->type,
1836 			   IN_DEV_ORCONF(in_dev, NOPOLICY),
1837 			   IN_DEV_ORCONF(out_dev, NOXFRM));
1838 	if (!rth) {
1839 		err = -ENOBUFS;
1840 		goto cleanup;
1841 	}
1842 
1843 	rth->rt_is_input = 1;
1844 	RT_CACHE_STAT_INC(in_slow_tot);
1845 
1846 	rth->dst.input = ip_forward;
1847 
1848 	rt_set_nexthop(rth, daddr, res, fnhe, res->fi, res->type, itag,
1849 		       do_cache);
1850 	lwtunnel_set_redirect(&rth->dst);
1851 	skb_dst_set(skb, &rth->dst);
1852 out:
1853 	err = 0;
1854  cleanup:
1855 	return err;
1856 }
1857 
1858 #ifdef CONFIG_IP_ROUTE_MULTIPATH
1859 /* To make ICMP packets follow the right flow, the multipath hash is
1860  * calculated from the inner IP addresses.
1861  */
1862 static void ip_multipath_l3_keys(const struct sk_buff *skb,
1863 				 struct flow_keys *hash_keys)
1864 {
1865 	const struct iphdr *outer_iph = ip_hdr(skb);
1866 	const struct iphdr *key_iph = outer_iph;
1867 	const struct iphdr *inner_iph;
1868 	const struct icmphdr *icmph;
1869 	struct iphdr _inner_iph;
1870 	struct icmphdr _icmph;
1871 
1872 	if (likely(outer_iph->protocol != IPPROTO_ICMP))
1873 		goto out;
1874 
1875 	if (unlikely((outer_iph->frag_off & htons(IP_OFFSET)) != 0))
1876 		goto out;
1877 
1878 	icmph = skb_header_pointer(skb, outer_iph->ihl * 4, sizeof(_icmph),
1879 				   &_icmph);
1880 	if (!icmph)
1881 		goto out;
1882 
1883 	if (!icmp_is_err(icmph->type))
1884 		goto out;
1885 
1886 	inner_iph = skb_header_pointer(skb,
1887 				       outer_iph->ihl * 4 + sizeof(_icmph),
1888 				       sizeof(_inner_iph), &_inner_iph);
1889 	if (!inner_iph)
1890 		goto out;
1891 
1892 	key_iph = inner_iph;
1893 out:
1894 	hash_keys->addrs.v4addrs.src = key_iph->saddr;
1895 	hash_keys->addrs.v4addrs.dst = key_iph->daddr;
1896 }
1897 
1898 static u32 fib_multipath_custom_hash_outer(const struct net *net,
1899 					   const struct sk_buff *skb,
1900 					   bool *p_has_inner)
1901 {
1902 	u32 hash_fields = net->ipv4.sysctl_fib_multipath_hash_fields;
1903 	struct flow_keys keys, hash_keys;
1904 
1905 	if (!(hash_fields & FIB_MULTIPATH_HASH_FIELD_OUTER_MASK))
1906 		return 0;
1907 
1908 	memset(&hash_keys, 0, sizeof(hash_keys));
1909 	skb_flow_dissect_flow_keys(skb, &keys, FLOW_DISSECTOR_F_STOP_AT_ENCAP);
1910 
1911 	hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
1912 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_SRC_IP)
1913 		hash_keys.addrs.v4addrs.src = keys.addrs.v4addrs.src;
1914 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_DST_IP)
1915 		hash_keys.addrs.v4addrs.dst = keys.addrs.v4addrs.dst;
1916 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_IP_PROTO)
1917 		hash_keys.basic.ip_proto = keys.basic.ip_proto;
1918 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_SRC_PORT)
1919 		hash_keys.ports.src = keys.ports.src;
1920 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_DST_PORT)
1921 		hash_keys.ports.dst = keys.ports.dst;
1922 
1923 	*p_has_inner = !!(keys.control.flags & FLOW_DIS_ENCAPSULATION);
1924 	return flow_hash_from_keys(&hash_keys);
1925 }
1926 
1927 static u32 fib_multipath_custom_hash_inner(const struct net *net,
1928 					   const struct sk_buff *skb,
1929 					   bool has_inner)
1930 {
1931 	u32 hash_fields = net->ipv4.sysctl_fib_multipath_hash_fields;
1932 	struct flow_keys keys, hash_keys;
1933 
1934 	/* We assume the packet carries an encapsulation, but if none was
1935 	 * encountered during dissection of the outer flow, then there is no
1936 	 * point in calling the flow dissector again.
1937 	 */
1938 	if (!has_inner)
1939 		return 0;
1940 
1941 	if (!(hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_MASK))
1942 		return 0;
1943 
1944 	memset(&hash_keys, 0, sizeof(hash_keys));
1945 	skb_flow_dissect_flow_keys(skb, &keys, 0);
1946 
1947 	if (!(keys.control.flags & FLOW_DIS_ENCAPSULATION))
1948 		return 0;
1949 
1950 	if (keys.control.addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
1951 		hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
1952 		if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_SRC_IP)
1953 			hash_keys.addrs.v4addrs.src = keys.addrs.v4addrs.src;
1954 		if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_DST_IP)
1955 			hash_keys.addrs.v4addrs.dst = keys.addrs.v4addrs.dst;
1956 	} else if (keys.control.addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
1957 		hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
1958 		if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_SRC_IP)
1959 			hash_keys.addrs.v6addrs.src = keys.addrs.v6addrs.src;
1960 		if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_DST_IP)
1961 			hash_keys.addrs.v6addrs.dst = keys.addrs.v6addrs.dst;
1962 		if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_FLOWLABEL)
1963 			hash_keys.tags.flow_label = keys.tags.flow_label;
1964 	}
1965 
1966 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_IP_PROTO)
1967 		hash_keys.basic.ip_proto = keys.basic.ip_proto;
1968 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_SRC_PORT)
1969 		hash_keys.ports.src = keys.ports.src;
1970 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_INNER_DST_PORT)
1971 		hash_keys.ports.dst = keys.ports.dst;
1972 
1973 	return flow_hash_from_keys(&hash_keys);
1974 }
1975 
1976 static u32 fib_multipath_custom_hash_skb(const struct net *net,
1977 					 const struct sk_buff *skb)
1978 {
1979 	u32 mhash, mhash_inner;
1980 	bool has_inner = true;
1981 
1982 	mhash = fib_multipath_custom_hash_outer(net, skb, &has_inner);
1983 	mhash_inner = fib_multipath_custom_hash_inner(net, skb, has_inner);
1984 
1985 	return jhash_2words(mhash, mhash_inner, 0);
1986 }
1987 
1988 static u32 fib_multipath_custom_hash_fl4(const struct net *net,
1989 					 const struct flowi4 *fl4)
1990 {
1991 	u32 hash_fields = net->ipv4.sysctl_fib_multipath_hash_fields;
1992 	struct flow_keys hash_keys;
1993 
1994 	if (!(hash_fields & FIB_MULTIPATH_HASH_FIELD_OUTER_MASK))
1995 		return 0;
1996 
1997 	memset(&hash_keys, 0, sizeof(hash_keys));
1998 	hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
1999 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_SRC_IP)
2000 		hash_keys.addrs.v4addrs.src = fl4->saddr;
2001 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_DST_IP)
2002 		hash_keys.addrs.v4addrs.dst = fl4->daddr;
2003 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_IP_PROTO)
2004 		hash_keys.basic.ip_proto = fl4->flowi4_proto;
2005 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_SRC_PORT)
2006 		hash_keys.ports.src = fl4->fl4_sport;
2007 	if (hash_fields & FIB_MULTIPATH_HASH_FIELD_DST_PORT)
2008 		hash_keys.ports.dst = fl4->fl4_dport;
2009 
2010 	return flow_hash_from_keys(&hash_keys);
2011 }
2012 
2013 /* if skb is set it will be used and fl4 can be NULL */
2014 int fib_multipath_hash(const struct net *net, const struct flowi4 *fl4,
2015 		       const struct sk_buff *skb, struct flow_keys *flkeys)
2016 {
2017 	u32 multipath_hash = fl4 ? fl4->flowi4_multipath_hash : 0;
2018 	struct flow_keys hash_keys;
2019 	u32 mhash = 0;
2020 
2021 	switch (net->ipv4.sysctl_fib_multipath_hash_policy) {
2022 	case 0:
2023 		memset(&hash_keys, 0, sizeof(hash_keys));
2024 		hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
2025 		if (skb) {
2026 			ip_multipath_l3_keys(skb, &hash_keys);
2027 		} else {
2028 			hash_keys.addrs.v4addrs.src = fl4->saddr;
2029 			hash_keys.addrs.v4addrs.dst = fl4->daddr;
2030 		}
2031 		mhash = flow_hash_from_keys(&hash_keys);
2032 		break;
2033 	case 1:
2034 		/* skb is currently provided only when forwarding */
2035 		if (skb) {
2036 			unsigned int flag = FLOW_DISSECTOR_F_STOP_AT_ENCAP;
2037 			struct flow_keys keys;
2038 
2039 			/* short-circuit if we already have L4 hash present */
2040 			if (skb->l4_hash)
2041 				return skb_get_hash_raw(skb) >> 1;
2042 
2043 			memset(&hash_keys, 0, sizeof(hash_keys));
2044 
2045 			if (!flkeys) {
2046 				skb_flow_dissect_flow_keys(skb, &keys, flag);
2047 				flkeys = &keys;
2048 			}
2049 
2050 			hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
2051 			hash_keys.addrs.v4addrs.src = flkeys->addrs.v4addrs.src;
2052 			hash_keys.addrs.v4addrs.dst = flkeys->addrs.v4addrs.dst;
2053 			hash_keys.ports.src = flkeys->ports.src;
2054 			hash_keys.ports.dst = flkeys->ports.dst;
2055 			hash_keys.basic.ip_proto = flkeys->basic.ip_proto;
2056 		} else {
2057 			memset(&hash_keys, 0, sizeof(hash_keys));
2058 			hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
2059 			hash_keys.addrs.v4addrs.src = fl4->saddr;
2060 			hash_keys.addrs.v4addrs.dst = fl4->daddr;
2061 			hash_keys.ports.src = fl4->fl4_sport;
2062 			hash_keys.ports.dst = fl4->fl4_dport;
2063 			hash_keys.basic.ip_proto = fl4->flowi4_proto;
2064 		}
2065 		mhash = flow_hash_from_keys(&hash_keys);
2066 		break;
2067 	case 2:
2068 		memset(&hash_keys, 0, sizeof(hash_keys));
2069 		/* skb is currently provided only when forwarding */
2070 		if (skb) {
2071 			struct flow_keys keys;
2072 
2073 			skb_flow_dissect_flow_keys(skb, &keys, 0);
2074 			/* Inner can be v4 or v6 */
2075 			if (keys.control.addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
2076 				hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
2077 				hash_keys.addrs.v4addrs.src = keys.addrs.v4addrs.src;
2078 				hash_keys.addrs.v4addrs.dst = keys.addrs.v4addrs.dst;
2079 			} else if (keys.control.addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
2080 				hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
2081 				hash_keys.addrs.v6addrs.src = keys.addrs.v6addrs.src;
2082 				hash_keys.addrs.v6addrs.dst = keys.addrs.v6addrs.dst;
2083 				hash_keys.tags.flow_label = keys.tags.flow_label;
2084 				hash_keys.basic.ip_proto = keys.basic.ip_proto;
2085 			} else {
2086 				/* Same as case 0 */
2087 				hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
2088 				ip_multipath_l3_keys(skb, &hash_keys);
2089 			}
2090 		} else {
2091 			/* Same as case 0 */
2092 			hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
2093 			hash_keys.addrs.v4addrs.src = fl4->saddr;
2094 			hash_keys.addrs.v4addrs.dst = fl4->daddr;
2095 		}
2096 		mhash = flow_hash_from_keys(&hash_keys);
2097 		break;
2098 	case 3:
2099 		if (skb)
2100 			mhash = fib_multipath_custom_hash_skb(net, skb);
2101 		else
2102 			mhash = fib_multipath_custom_hash_fl4(net, fl4);
2103 		break;
2104 	}
2105 
2106 	if (multipath_hash)
2107 		mhash = jhash_2words(mhash, multipath_hash, 0);
2108 
2109 	return mhash >> 1;
2110 }
2111 #endif /* CONFIG_IP_ROUTE_MULTIPATH */
2112 
2113 static int ip_mkroute_input(struct sk_buff *skb,
2114 			    struct fib_result *res,
2115 			    struct in_device *in_dev,
2116 			    __be32 daddr, __be32 saddr, u32 tos,
2117 			    struct flow_keys *hkeys)
2118 {
2119 #ifdef CONFIG_IP_ROUTE_MULTIPATH
2120 	if (res->fi && fib_info_num_path(res->fi) > 1) {
2121 		int h = fib_multipath_hash(res->fi->fib_net, NULL, skb, hkeys);
2122 
2123 		fib_select_multipath(res, h);
2124 	}
2125 #endif
2126 
2127 	/* create a routing cache entry */
2128 	return __mkroute_input(skb, res, in_dev, daddr, saddr, tos);
2129 }
2130 
2131 /* Implements all the saddr-related checks as ip_route_input_slow(),
2132  * assuming daddr is valid and the destination is not a local broadcast one.
2133  * Uses the provided hint instead of performing a route lookup.
2134  */
2135 int ip_route_use_hint(struct sk_buff *skb, __be32 daddr, __be32 saddr,
2136 		      u8 tos, struct net_device *dev,
2137 		      const struct sk_buff *hint)
2138 {
2139 	struct in_device *in_dev = __in_dev_get_rcu(dev);
2140 	struct rtable *rt = skb_rtable(hint);
2141 	struct net *net = dev_net(dev);
2142 	int err = -EINVAL;
2143 	u32 tag = 0;
2144 
2145 	if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr))
2146 		goto martian_source;
2147 
2148 	if (ipv4_is_zeronet(saddr))
2149 		goto martian_source;
2150 
2151 	if (ipv4_is_loopback(saddr) && !IN_DEV_NET_ROUTE_LOCALNET(in_dev, net))
2152 		goto martian_source;
2153 
2154 	if (rt->rt_type != RTN_LOCAL)
2155 		goto skip_validate_source;
2156 
2157 	tos &= IPTOS_RT_MASK;
2158 	err = fib_validate_source(skb, saddr, daddr, tos, 0, dev, in_dev, &tag);
2159 	if (err < 0)
2160 		goto martian_source;
2161 
2162 skip_validate_source:
2163 	skb_dst_copy(skb, hint);
2164 	return 0;
2165 
2166 martian_source:
2167 	ip_handle_martian_source(dev, in_dev, skb, daddr, saddr);
2168 	return err;
2169 }
2170 
2171 /* get device for dst_alloc with local routes */
2172 static struct net_device *ip_rt_get_dev(struct net *net,
2173 					const struct fib_result *res)
2174 {
2175 	struct fib_nh_common *nhc = res->fi ? res->nhc : NULL;
2176 	struct net_device *dev = NULL;
2177 
2178 	if (nhc)
2179 		dev = l3mdev_master_dev_rcu(nhc->nhc_dev);
2180 
2181 	return dev ? : net->loopback_dev;
2182 }
2183 
2184 /*
2185  *	NOTE. We drop all the packets that has local source
2186  *	addresses, because every properly looped back packet
2187  *	must have correct destination already attached by output routine.
2188  *	Changes in the enforced policies must be applied also to
2189  *	ip_route_use_hint().
2190  *
2191  *	Such approach solves two big problems:
2192  *	1. Not simplex devices are handled properly.
2193  *	2. IP spoofing attempts are filtered with 100% of guarantee.
2194  *	called with rcu_read_lock()
2195  */
2196 
2197 static int ip_route_input_slow(struct sk_buff *skb, __be32 daddr, __be32 saddr,
2198 			       u8 tos, struct net_device *dev,
2199 			       struct fib_result *res)
2200 {
2201 	struct in_device *in_dev = __in_dev_get_rcu(dev);
2202 	struct flow_keys *flkeys = NULL, _flkeys;
2203 	struct net    *net = dev_net(dev);
2204 	struct ip_tunnel_info *tun_info;
2205 	int		err = -EINVAL;
2206 	unsigned int	flags = 0;
2207 	u32		itag = 0;
2208 	struct rtable	*rth;
2209 	struct flowi4	fl4;
2210 	bool do_cache = true;
2211 
2212 	/* IP on this device is disabled. */
2213 
2214 	if (!in_dev)
2215 		goto out;
2216 
2217 	/* Check for the most weird martians, which can be not detected
2218 	 * by fib_lookup.
2219 	 */
2220 
2221 	tun_info = skb_tunnel_info(skb);
2222 	if (tun_info && !(tun_info->mode & IP_TUNNEL_INFO_TX))
2223 		fl4.flowi4_tun_key.tun_id = tun_info->key.tun_id;
2224 	else
2225 		fl4.flowi4_tun_key.tun_id = 0;
2226 	skb_dst_drop(skb);
2227 
2228 	if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr))
2229 		goto martian_source;
2230 
2231 	res->fi = NULL;
2232 	res->table = NULL;
2233 	if (ipv4_is_lbcast(daddr) || (saddr == 0 && daddr == 0))
2234 		goto brd_input;
2235 
2236 	/* Accept zero addresses only to limited broadcast;
2237 	 * I even do not know to fix it or not. Waiting for complains :-)
2238 	 */
2239 	if (ipv4_is_zeronet(saddr))
2240 		goto martian_source;
2241 
2242 	if (ipv4_is_zeronet(daddr))
2243 		goto martian_destination;
2244 
2245 	/* Following code try to avoid calling IN_DEV_NET_ROUTE_LOCALNET(),
2246 	 * and call it once if daddr or/and saddr are loopback addresses
2247 	 */
2248 	if (ipv4_is_loopback(daddr)) {
2249 		if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net))
2250 			goto martian_destination;
2251 	} else if (ipv4_is_loopback(saddr)) {
2252 		if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net))
2253 			goto martian_source;
2254 	}
2255 
2256 	/*
2257 	 *	Now we are ready to route packet.
2258 	 */
2259 	fl4.flowi4_oif = 0;
2260 	fl4.flowi4_iif = dev->ifindex;
2261 	fl4.flowi4_mark = skb->mark;
2262 	fl4.flowi4_tos = tos;
2263 	fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
2264 	fl4.flowi4_flags = 0;
2265 	fl4.daddr = daddr;
2266 	fl4.saddr = saddr;
2267 	fl4.flowi4_uid = sock_net_uid(net, NULL);
2268 	fl4.flowi4_multipath_hash = 0;
2269 
2270 	if (fib4_rules_early_flow_dissect(net, skb, &fl4, &_flkeys)) {
2271 		flkeys = &_flkeys;
2272 	} else {
2273 		fl4.flowi4_proto = 0;
2274 		fl4.fl4_sport = 0;
2275 		fl4.fl4_dport = 0;
2276 	}
2277 
2278 	err = fib_lookup(net, &fl4, res, 0);
2279 	if (err != 0) {
2280 		if (!IN_DEV_FORWARD(in_dev))
2281 			err = -EHOSTUNREACH;
2282 		goto no_route;
2283 	}
2284 
2285 	if (res->type == RTN_BROADCAST) {
2286 		if (IN_DEV_BFORWARD(in_dev))
2287 			goto make_route;
2288 		/* not do cache if bc_forwarding is enabled */
2289 		if (IPV4_DEVCONF_ALL(net, BC_FORWARDING))
2290 			do_cache = false;
2291 		goto brd_input;
2292 	}
2293 
2294 	if (res->type == RTN_LOCAL) {
2295 		err = fib_validate_source(skb, saddr, daddr, tos,
2296 					  0, dev, in_dev, &itag);
2297 		if (err < 0)
2298 			goto martian_source;
2299 		goto local_input;
2300 	}
2301 
2302 	if (!IN_DEV_FORWARD(in_dev)) {
2303 		err = -EHOSTUNREACH;
2304 		goto no_route;
2305 	}
2306 	if (res->type != RTN_UNICAST)
2307 		goto martian_destination;
2308 
2309 make_route:
2310 	err = ip_mkroute_input(skb, res, in_dev, daddr, saddr, tos, flkeys);
2311 out:	return err;
2312 
2313 brd_input:
2314 	if (skb->protocol != htons(ETH_P_IP))
2315 		goto e_inval;
2316 
2317 	if (!ipv4_is_zeronet(saddr)) {
2318 		err = fib_validate_source(skb, saddr, 0, tos, 0, dev,
2319 					  in_dev, &itag);
2320 		if (err < 0)
2321 			goto martian_source;
2322 	}
2323 	flags |= RTCF_BROADCAST;
2324 	res->type = RTN_BROADCAST;
2325 	RT_CACHE_STAT_INC(in_brd);
2326 
2327 local_input:
2328 	do_cache &= res->fi && !itag;
2329 	if (do_cache) {
2330 		struct fib_nh_common *nhc = FIB_RES_NHC(*res);
2331 
2332 		rth = rcu_dereference(nhc->nhc_rth_input);
2333 		if (rt_cache_valid(rth)) {
2334 			skb_dst_set_noref(skb, &rth->dst);
2335 			err = 0;
2336 			goto out;
2337 		}
2338 	}
2339 
2340 	rth = rt_dst_alloc(ip_rt_get_dev(net, res),
2341 			   flags | RTCF_LOCAL, res->type,
2342 			   IN_DEV_ORCONF(in_dev, NOPOLICY), false);
2343 	if (!rth)
2344 		goto e_nobufs;
2345 
2346 	rth->dst.output= ip_rt_bug;
2347 #ifdef CONFIG_IP_ROUTE_CLASSID
2348 	rth->dst.tclassid = itag;
2349 #endif
2350 	rth->rt_is_input = 1;
2351 
2352 	RT_CACHE_STAT_INC(in_slow_tot);
2353 	if (res->type == RTN_UNREACHABLE) {
2354 		rth->dst.input= ip_error;
2355 		rth->dst.error= -err;
2356 		rth->rt_flags	&= ~RTCF_LOCAL;
2357 	}
2358 
2359 	if (do_cache) {
2360 		struct fib_nh_common *nhc = FIB_RES_NHC(*res);
2361 
2362 		rth->dst.lwtstate = lwtstate_get(nhc->nhc_lwtstate);
2363 		if (lwtunnel_input_redirect(rth->dst.lwtstate)) {
2364 			WARN_ON(rth->dst.input == lwtunnel_input);
2365 			rth->dst.lwtstate->orig_input = rth->dst.input;
2366 			rth->dst.input = lwtunnel_input;
2367 		}
2368 
2369 		if (unlikely(!rt_cache_route(nhc, rth)))
2370 			rt_add_uncached_list(rth);
2371 	}
2372 	skb_dst_set(skb, &rth->dst);
2373 	err = 0;
2374 	goto out;
2375 
2376 no_route:
2377 	RT_CACHE_STAT_INC(in_no_route);
2378 	res->type = RTN_UNREACHABLE;
2379 	res->fi = NULL;
2380 	res->table = NULL;
2381 	goto local_input;
2382 
2383 	/*
2384 	 *	Do not cache martian addresses: they should be logged (RFC1812)
2385 	 */
2386 martian_destination:
2387 	RT_CACHE_STAT_INC(in_martian_dst);
2388 #ifdef CONFIG_IP_ROUTE_VERBOSE
2389 	if (IN_DEV_LOG_MARTIANS(in_dev))
2390 		net_warn_ratelimited("martian destination %pI4 from %pI4, dev %s\n",
2391 				     &daddr, &saddr, dev->name);
2392 #endif
2393 
2394 e_inval:
2395 	err = -EINVAL;
2396 	goto out;
2397 
2398 e_nobufs:
2399 	err = -ENOBUFS;
2400 	goto out;
2401 
2402 martian_source:
2403 	ip_handle_martian_source(dev, in_dev, skb, daddr, saddr);
2404 	goto out;
2405 }
2406 
2407 int ip_route_input_noref(struct sk_buff *skb, __be32 daddr, __be32 saddr,
2408 			 u8 tos, struct net_device *dev)
2409 {
2410 	struct fib_result res;
2411 	int err;
2412 
2413 	tos &= IPTOS_RT_MASK;
2414 	rcu_read_lock();
2415 	err = ip_route_input_rcu(skb, daddr, saddr, tos, dev, &res);
2416 	rcu_read_unlock();
2417 
2418 	return err;
2419 }
2420 EXPORT_SYMBOL(ip_route_input_noref);
2421 
2422 /* called with rcu_read_lock held */
2423 int ip_route_input_rcu(struct sk_buff *skb, __be32 daddr, __be32 saddr,
2424 		       u8 tos, struct net_device *dev, struct fib_result *res)
2425 {
2426 	/* Multicast recognition logic is moved from route cache to here.
2427 	 * The problem was that too many Ethernet cards have broken/missing
2428 	 * hardware multicast filters :-( As result the host on multicasting
2429 	 * network acquires a lot of useless route cache entries, sort of
2430 	 * SDR messages from all the world. Now we try to get rid of them.
2431 	 * Really, provided software IP multicast filter is organized
2432 	 * reasonably (at least, hashed), it does not result in a slowdown
2433 	 * comparing with route cache reject entries.
2434 	 * Note, that multicast routers are not affected, because
2435 	 * route cache entry is created eventually.
2436 	 */
2437 	if (ipv4_is_multicast(daddr)) {
2438 		struct in_device *in_dev = __in_dev_get_rcu(dev);
2439 		int our = 0;
2440 		int err = -EINVAL;
2441 
2442 		if (!in_dev)
2443 			return err;
2444 		our = ip_check_mc_rcu(in_dev, daddr, saddr,
2445 				      ip_hdr(skb)->protocol);
2446 
2447 		/* check l3 master if no match yet */
2448 		if (!our && netif_is_l3_slave(dev)) {
2449 			struct in_device *l3_in_dev;
2450 
2451 			l3_in_dev = __in_dev_get_rcu(skb->dev);
2452 			if (l3_in_dev)
2453 				our = ip_check_mc_rcu(l3_in_dev, daddr, saddr,
2454 						      ip_hdr(skb)->protocol);
2455 		}
2456 
2457 		if (our
2458 #ifdef CONFIG_IP_MROUTE
2459 			||
2460 		    (!ipv4_is_local_multicast(daddr) &&
2461 		     IN_DEV_MFORWARD(in_dev))
2462 #endif
2463 		   ) {
2464 			err = ip_route_input_mc(skb, daddr, saddr,
2465 						tos, dev, our);
2466 		}
2467 		return err;
2468 	}
2469 
2470 	return ip_route_input_slow(skb, daddr, saddr, tos, dev, res);
2471 }
2472 
2473 /* called with rcu_read_lock() */
2474 static struct rtable *__mkroute_output(const struct fib_result *res,
2475 				       const struct flowi4 *fl4, int orig_oif,
2476 				       struct net_device *dev_out,
2477 				       unsigned int flags)
2478 {
2479 	struct fib_info *fi = res->fi;
2480 	struct fib_nh_exception *fnhe;
2481 	struct in_device *in_dev;
2482 	u16 type = res->type;
2483 	struct rtable *rth;
2484 	bool do_cache;
2485 
2486 	in_dev = __in_dev_get_rcu(dev_out);
2487 	if (!in_dev)
2488 		return ERR_PTR(-EINVAL);
2489 
2490 	if (likely(!IN_DEV_ROUTE_LOCALNET(in_dev)))
2491 		if (ipv4_is_loopback(fl4->saddr) &&
2492 		    !(dev_out->flags & IFF_LOOPBACK) &&
2493 		    !netif_is_l3_master(dev_out))
2494 			return ERR_PTR(-EINVAL);
2495 
2496 	if (ipv4_is_lbcast(fl4->daddr))
2497 		type = RTN_BROADCAST;
2498 	else if (ipv4_is_multicast(fl4->daddr))
2499 		type = RTN_MULTICAST;
2500 	else if (ipv4_is_zeronet(fl4->daddr))
2501 		return ERR_PTR(-EINVAL);
2502 
2503 	if (dev_out->flags & IFF_LOOPBACK)
2504 		flags |= RTCF_LOCAL;
2505 
2506 	do_cache = true;
2507 	if (type == RTN_BROADCAST) {
2508 		flags |= RTCF_BROADCAST | RTCF_LOCAL;
2509 		fi = NULL;
2510 	} else if (type == RTN_MULTICAST) {
2511 		flags |= RTCF_MULTICAST | RTCF_LOCAL;
2512 		if (!ip_check_mc_rcu(in_dev, fl4->daddr, fl4->saddr,
2513 				     fl4->flowi4_proto))
2514 			flags &= ~RTCF_LOCAL;
2515 		else
2516 			do_cache = false;
2517 		/* If multicast route do not exist use
2518 		 * default one, but do not gateway in this case.
2519 		 * Yes, it is hack.
2520 		 */
2521 		if (fi && res->prefixlen < 4)
2522 			fi = NULL;
2523 	} else if ((type == RTN_LOCAL) && (orig_oif != 0) &&
2524 		   (orig_oif != dev_out->ifindex)) {
2525 		/* For local routes that require a particular output interface
2526 		 * we do not want to cache the result.  Caching the result
2527 		 * causes incorrect behaviour when there are multiple source
2528 		 * addresses on the interface, the end result being that if the
2529 		 * intended recipient is waiting on that interface for the
2530 		 * packet he won't receive it because it will be delivered on
2531 		 * the loopback interface and the IP_PKTINFO ipi_ifindex will
2532 		 * be set to the loopback interface as well.
2533 		 */
2534 		do_cache = false;
2535 	}
2536 
2537 	fnhe = NULL;
2538 	do_cache &= fi != NULL;
2539 	if (fi) {
2540 		struct fib_nh_common *nhc = FIB_RES_NHC(*res);
2541 		struct rtable __rcu **prth;
2542 
2543 		fnhe = find_exception(nhc, fl4->daddr);
2544 		if (!do_cache)
2545 			goto add;
2546 		if (fnhe) {
2547 			prth = &fnhe->fnhe_rth_output;
2548 		} else {
2549 			if (unlikely(fl4->flowi4_flags &
2550 				     FLOWI_FLAG_KNOWN_NH &&
2551 				     !(nhc->nhc_gw_family &&
2552 				       nhc->nhc_scope == RT_SCOPE_LINK))) {
2553 				do_cache = false;
2554 				goto add;
2555 			}
2556 			prth = raw_cpu_ptr(nhc->nhc_pcpu_rth_output);
2557 		}
2558 		rth = rcu_dereference(*prth);
2559 		if (rt_cache_valid(rth) && dst_hold_safe(&rth->dst))
2560 			return rth;
2561 	}
2562 
2563 add:
2564 	rth = rt_dst_alloc(dev_out, flags, type,
2565 			   IN_DEV_ORCONF(in_dev, NOPOLICY),
2566 			   IN_DEV_ORCONF(in_dev, NOXFRM));
2567 	if (!rth)
2568 		return ERR_PTR(-ENOBUFS);
2569 
2570 	rth->rt_iif = orig_oif;
2571 
2572 	RT_CACHE_STAT_INC(out_slow_tot);
2573 
2574 	if (flags & (RTCF_BROADCAST | RTCF_MULTICAST)) {
2575 		if (flags & RTCF_LOCAL &&
2576 		    !(dev_out->flags & IFF_LOOPBACK)) {
2577 			rth->dst.output = ip_mc_output;
2578 			RT_CACHE_STAT_INC(out_slow_mc);
2579 		}
2580 #ifdef CONFIG_IP_MROUTE
2581 		if (type == RTN_MULTICAST) {
2582 			if (IN_DEV_MFORWARD(in_dev) &&
2583 			    !ipv4_is_local_multicast(fl4->daddr)) {
2584 				rth->dst.input = ip_mr_input;
2585 				rth->dst.output = ip_mc_output;
2586 			}
2587 		}
2588 #endif
2589 	}
2590 
2591 	rt_set_nexthop(rth, fl4->daddr, res, fnhe, fi, type, 0, do_cache);
2592 	lwtunnel_set_redirect(&rth->dst);
2593 
2594 	return rth;
2595 }
2596 
2597 /*
2598  * Major route resolver routine.
2599  */
2600 
2601 struct rtable *ip_route_output_key_hash(struct net *net, struct flowi4 *fl4,
2602 					const struct sk_buff *skb)
2603 {
2604 	__u8 tos = RT_FL_TOS(fl4);
2605 	struct fib_result res = {
2606 		.type		= RTN_UNSPEC,
2607 		.fi		= NULL,
2608 		.table		= NULL,
2609 		.tclassid	= 0,
2610 	};
2611 	struct rtable *rth;
2612 
2613 	fl4->flowi4_iif = LOOPBACK_IFINDEX;
2614 	fl4->flowi4_tos = tos & IPTOS_RT_MASK;
2615 	fl4->flowi4_scope = ((tos & RTO_ONLINK) ?
2616 			 RT_SCOPE_LINK : RT_SCOPE_UNIVERSE);
2617 
2618 	rcu_read_lock();
2619 	rth = ip_route_output_key_hash_rcu(net, fl4, &res, skb);
2620 	rcu_read_unlock();
2621 
2622 	return rth;
2623 }
2624 EXPORT_SYMBOL_GPL(ip_route_output_key_hash);
2625 
2626 struct rtable *ip_route_output_key_hash_rcu(struct net *net, struct flowi4 *fl4,
2627 					    struct fib_result *res,
2628 					    const struct sk_buff *skb)
2629 {
2630 	struct net_device *dev_out = NULL;
2631 	int orig_oif = fl4->flowi4_oif;
2632 	unsigned int flags = 0;
2633 	struct rtable *rth;
2634 	int err;
2635 
2636 	if (fl4->saddr) {
2637 		if (ipv4_is_multicast(fl4->saddr) ||
2638 		    ipv4_is_lbcast(fl4->saddr) ||
2639 		    ipv4_is_zeronet(fl4->saddr)) {
2640 			rth = ERR_PTR(-EINVAL);
2641 			goto out;
2642 		}
2643 
2644 		rth = ERR_PTR(-ENETUNREACH);
2645 
2646 		/* I removed check for oif == dev_out->oif here.
2647 		 * It was wrong for two reasons:
2648 		 * 1. ip_dev_find(net, saddr) can return wrong iface, if saddr
2649 		 *    is assigned to multiple interfaces.
2650 		 * 2. Moreover, we are allowed to send packets with saddr
2651 		 *    of another iface. --ANK
2652 		 */
2653 
2654 		if (fl4->flowi4_oif == 0 &&
2655 		    (ipv4_is_multicast(fl4->daddr) ||
2656 		     ipv4_is_lbcast(fl4->daddr))) {
2657 			/* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */
2658 			dev_out = __ip_dev_find(net, fl4->saddr, false);
2659 			if (!dev_out)
2660 				goto out;
2661 
2662 			/* Special hack: user can direct multicasts
2663 			 * and limited broadcast via necessary interface
2664 			 * without fiddling with IP_MULTICAST_IF or IP_PKTINFO.
2665 			 * This hack is not just for fun, it allows
2666 			 * vic,vat and friends to work.
2667 			 * They bind socket to loopback, set ttl to zero
2668 			 * and expect that it will work.
2669 			 * From the viewpoint of routing cache they are broken,
2670 			 * because we are not allowed to build multicast path
2671 			 * with loopback source addr (look, routing cache
2672 			 * cannot know, that ttl is zero, so that packet
2673 			 * will not leave this host and route is valid).
2674 			 * Luckily, this hack is good workaround.
2675 			 */
2676 
2677 			fl4->flowi4_oif = dev_out->ifindex;
2678 			goto make_route;
2679 		}
2680 
2681 		if (!(fl4->flowi4_flags & FLOWI_FLAG_ANYSRC)) {
2682 			/* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */
2683 			if (!__ip_dev_find(net, fl4->saddr, false))
2684 				goto out;
2685 		}
2686 	}
2687 
2688 
2689 	if (fl4->flowi4_oif) {
2690 		dev_out = dev_get_by_index_rcu(net, fl4->flowi4_oif);
2691 		rth = ERR_PTR(-ENODEV);
2692 		if (!dev_out)
2693 			goto out;
2694 
2695 		/* RACE: Check return value of inet_select_addr instead. */
2696 		if (!(dev_out->flags & IFF_UP) || !__in_dev_get_rcu(dev_out)) {
2697 			rth = ERR_PTR(-ENETUNREACH);
2698 			goto out;
2699 		}
2700 		if (ipv4_is_local_multicast(fl4->daddr) ||
2701 		    ipv4_is_lbcast(fl4->daddr) ||
2702 		    fl4->flowi4_proto == IPPROTO_IGMP) {
2703 			if (!fl4->saddr)
2704 				fl4->saddr = inet_select_addr(dev_out, 0,
2705 							      RT_SCOPE_LINK);
2706 			goto make_route;
2707 		}
2708 		if (!fl4->saddr) {
2709 			if (ipv4_is_multicast(fl4->daddr))
2710 				fl4->saddr = inet_select_addr(dev_out, 0,
2711 							      fl4->flowi4_scope);
2712 			else if (!fl4->daddr)
2713 				fl4->saddr = inet_select_addr(dev_out, 0,
2714 							      RT_SCOPE_HOST);
2715 		}
2716 	}
2717 
2718 	if (!fl4->daddr) {
2719 		fl4->daddr = fl4->saddr;
2720 		if (!fl4->daddr)
2721 			fl4->daddr = fl4->saddr = htonl(INADDR_LOOPBACK);
2722 		dev_out = net->loopback_dev;
2723 		fl4->flowi4_oif = LOOPBACK_IFINDEX;
2724 		res->type = RTN_LOCAL;
2725 		flags |= RTCF_LOCAL;
2726 		goto make_route;
2727 	}
2728 
2729 	err = fib_lookup(net, fl4, res, 0);
2730 	if (err) {
2731 		res->fi = NULL;
2732 		res->table = NULL;
2733 		if (fl4->flowi4_oif &&
2734 		    (ipv4_is_multicast(fl4->daddr) ||
2735 		    !netif_index_is_l3_master(net, fl4->flowi4_oif))) {
2736 			/* Apparently, routing tables are wrong. Assume,
2737 			 * that the destination is on link.
2738 			 *
2739 			 * WHY? DW.
2740 			 * Because we are allowed to send to iface
2741 			 * even if it has NO routes and NO assigned
2742 			 * addresses. When oif is specified, routing
2743 			 * tables are looked up with only one purpose:
2744 			 * to catch if destination is gatewayed, rather than
2745 			 * direct. Moreover, if MSG_DONTROUTE is set,
2746 			 * we send packet, ignoring both routing tables
2747 			 * and ifaddr state. --ANK
2748 			 *
2749 			 *
2750 			 * We could make it even if oif is unknown,
2751 			 * likely IPv6, but we do not.
2752 			 */
2753 
2754 			if (fl4->saddr == 0)
2755 				fl4->saddr = inet_select_addr(dev_out, 0,
2756 							      RT_SCOPE_LINK);
2757 			res->type = RTN_UNICAST;
2758 			goto make_route;
2759 		}
2760 		rth = ERR_PTR(err);
2761 		goto out;
2762 	}
2763 
2764 	if (res->type == RTN_LOCAL) {
2765 		if (!fl4->saddr) {
2766 			if (res->fi->fib_prefsrc)
2767 				fl4->saddr = res->fi->fib_prefsrc;
2768 			else
2769 				fl4->saddr = fl4->daddr;
2770 		}
2771 
2772 		/* L3 master device is the loopback for that domain */
2773 		dev_out = l3mdev_master_dev_rcu(FIB_RES_DEV(*res)) ? :
2774 			net->loopback_dev;
2775 
2776 		/* make sure orig_oif points to fib result device even
2777 		 * though packet rx/tx happens over loopback or l3mdev
2778 		 */
2779 		orig_oif = FIB_RES_OIF(*res);
2780 
2781 		fl4->flowi4_oif = dev_out->ifindex;
2782 		flags |= RTCF_LOCAL;
2783 		goto make_route;
2784 	}
2785 
2786 	fib_select_path(net, res, fl4, skb);
2787 
2788 	dev_out = FIB_RES_DEV(*res);
2789 
2790 make_route:
2791 	rth = __mkroute_output(res, fl4, orig_oif, dev_out, flags);
2792 
2793 out:
2794 	return rth;
2795 }
2796 
2797 static struct dst_ops ipv4_dst_blackhole_ops = {
2798 	.family			= AF_INET,
2799 	.default_advmss		= ipv4_default_advmss,
2800 	.neigh_lookup		= ipv4_neigh_lookup,
2801 	.check			= dst_blackhole_check,
2802 	.cow_metrics		= dst_blackhole_cow_metrics,
2803 	.update_pmtu		= dst_blackhole_update_pmtu,
2804 	.redirect		= dst_blackhole_redirect,
2805 	.mtu			= dst_blackhole_mtu,
2806 };
2807 
2808 struct dst_entry *ipv4_blackhole_route(struct net *net, struct dst_entry *dst_orig)
2809 {
2810 	struct rtable *ort = (struct rtable *) dst_orig;
2811 	struct rtable *rt;
2812 
2813 	rt = dst_alloc(&ipv4_dst_blackhole_ops, NULL, 1, DST_OBSOLETE_DEAD, 0);
2814 	if (rt) {
2815 		struct dst_entry *new = &rt->dst;
2816 
2817 		new->__use = 1;
2818 		new->input = dst_discard;
2819 		new->output = dst_discard_out;
2820 
2821 		new->dev = net->loopback_dev;
2822 		dev_hold(new->dev);
2823 
2824 		rt->rt_is_input = ort->rt_is_input;
2825 		rt->rt_iif = ort->rt_iif;
2826 		rt->rt_pmtu = ort->rt_pmtu;
2827 		rt->rt_mtu_locked = ort->rt_mtu_locked;
2828 
2829 		rt->rt_genid = rt_genid_ipv4(net);
2830 		rt->rt_flags = ort->rt_flags;
2831 		rt->rt_type = ort->rt_type;
2832 		rt->rt_uses_gateway = ort->rt_uses_gateway;
2833 		rt->rt_gw_family = ort->rt_gw_family;
2834 		if (rt->rt_gw_family == AF_INET)
2835 			rt->rt_gw4 = ort->rt_gw4;
2836 		else if (rt->rt_gw_family == AF_INET6)
2837 			rt->rt_gw6 = ort->rt_gw6;
2838 
2839 		INIT_LIST_HEAD(&rt->rt_uncached);
2840 	}
2841 
2842 	dst_release(dst_orig);
2843 
2844 	return rt ? &rt->dst : ERR_PTR(-ENOMEM);
2845 }
2846 
2847 struct rtable *ip_route_output_flow(struct net *net, struct flowi4 *flp4,
2848 				    const struct sock *sk)
2849 {
2850 	struct rtable *rt = __ip_route_output_key(net, flp4);
2851 
2852 	if (IS_ERR(rt))
2853 		return rt;
2854 
2855 	if (flp4->flowi4_proto) {
2856 		flp4->flowi4_oif = rt->dst.dev->ifindex;
2857 		rt = (struct rtable *)xfrm_lookup_route(net, &rt->dst,
2858 							flowi4_to_flowi(flp4),
2859 							sk, 0);
2860 	}
2861 
2862 	return rt;
2863 }
2864 EXPORT_SYMBOL_GPL(ip_route_output_flow);
2865 
2866 struct rtable *ip_route_output_tunnel(struct sk_buff *skb,
2867 				      struct net_device *dev,
2868 				      struct net *net, __be32 *saddr,
2869 				      const struct ip_tunnel_info *info,
2870 				      u8 protocol, bool use_cache)
2871 {
2872 #ifdef CONFIG_DST_CACHE
2873 	struct dst_cache *dst_cache;
2874 #endif
2875 	struct rtable *rt = NULL;
2876 	struct flowi4 fl4;
2877 	__u8 tos;
2878 
2879 #ifdef CONFIG_DST_CACHE
2880 	dst_cache = (struct dst_cache *)&info->dst_cache;
2881 	if (use_cache) {
2882 		rt = dst_cache_get_ip4(dst_cache, saddr);
2883 		if (rt)
2884 			return rt;
2885 	}
2886 #endif
2887 	memset(&fl4, 0, sizeof(fl4));
2888 	fl4.flowi4_mark = skb->mark;
2889 	fl4.flowi4_proto = protocol;
2890 	fl4.daddr = info->key.u.ipv4.dst;
2891 	fl4.saddr = info->key.u.ipv4.src;
2892 	tos = info->key.tos;
2893 	fl4.flowi4_tos = RT_TOS(tos);
2894 
2895 	rt = ip_route_output_key(net, &fl4);
2896 	if (IS_ERR(rt)) {
2897 		netdev_dbg(dev, "no route to %pI4\n", &fl4.daddr);
2898 		return ERR_PTR(-ENETUNREACH);
2899 	}
2900 	if (rt->dst.dev == dev) { /* is this necessary? */
2901 		netdev_dbg(dev, "circular route to %pI4\n", &fl4.daddr);
2902 		ip_rt_put(rt);
2903 		return ERR_PTR(-ELOOP);
2904 	}
2905 #ifdef CONFIG_DST_CACHE
2906 	if (use_cache)
2907 		dst_cache_set_ip4(dst_cache, &rt->dst, fl4.saddr);
2908 #endif
2909 	*saddr = fl4.saddr;
2910 	return rt;
2911 }
2912 EXPORT_SYMBOL_GPL(ip_route_output_tunnel);
2913 
2914 /* called with rcu_read_lock held */
2915 static int rt_fill_info(struct net *net, __be32 dst, __be32 src,
2916 			struct rtable *rt, u32 table_id, struct flowi4 *fl4,
2917 			struct sk_buff *skb, u32 portid, u32 seq,
2918 			unsigned int flags)
2919 {
2920 	struct rtmsg *r;
2921 	struct nlmsghdr *nlh;
2922 	unsigned long expires = 0;
2923 	u32 error;
2924 	u32 metrics[RTAX_MAX];
2925 
2926 	nlh = nlmsg_put(skb, portid, seq, RTM_NEWROUTE, sizeof(*r), flags);
2927 	if (!nlh)
2928 		return -EMSGSIZE;
2929 
2930 	r = nlmsg_data(nlh);
2931 	r->rtm_family	 = AF_INET;
2932 	r->rtm_dst_len	= 32;
2933 	r->rtm_src_len	= 0;
2934 	r->rtm_tos	= fl4 ? fl4->flowi4_tos : 0;
2935 	r->rtm_table	= table_id < 256 ? table_id : RT_TABLE_COMPAT;
2936 	if (nla_put_u32(skb, RTA_TABLE, table_id))
2937 		goto nla_put_failure;
2938 	r->rtm_type	= rt->rt_type;
2939 	r->rtm_scope	= RT_SCOPE_UNIVERSE;
2940 	r->rtm_protocol = RTPROT_UNSPEC;
2941 	r->rtm_flags	= (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED;
2942 	if (rt->rt_flags & RTCF_NOTIFY)
2943 		r->rtm_flags |= RTM_F_NOTIFY;
2944 	if (IPCB(skb)->flags & IPSKB_DOREDIRECT)
2945 		r->rtm_flags |= RTCF_DOREDIRECT;
2946 
2947 	if (nla_put_in_addr(skb, RTA_DST, dst))
2948 		goto nla_put_failure;
2949 	if (src) {
2950 		r->rtm_src_len = 32;
2951 		if (nla_put_in_addr(skb, RTA_SRC, src))
2952 			goto nla_put_failure;
2953 	}
2954 	if (rt->dst.dev &&
2955 	    nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex))
2956 		goto nla_put_failure;
2957 	if (rt->dst.lwtstate &&
2958 	    lwtunnel_fill_encap(skb, rt->dst.lwtstate, RTA_ENCAP, RTA_ENCAP_TYPE) < 0)
2959 		goto nla_put_failure;
2960 #ifdef CONFIG_IP_ROUTE_CLASSID
2961 	if (rt->dst.tclassid &&
2962 	    nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid))
2963 		goto nla_put_failure;
2964 #endif
2965 	if (fl4 && !rt_is_input_route(rt) &&
2966 	    fl4->saddr != src) {
2967 		if (nla_put_in_addr(skb, RTA_PREFSRC, fl4->saddr))
2968 			goto nla_put_failure;
2969 	}
2970 	if (rt->rt_uses_gateway) {
2971 		if (rt->rt_gw_family == AF_INET &&
2972 		    nla_put_in_addr(skb, RTA_GATEWAY, rt->rt_gw4)) {
2973 			goto nla_put_failure;
2974 		} else if (rt->rt_gw_family == AF_INET6) {
2975 			int alen = sizeof(struct in6_addr);
2976 			struct nlattr *nla;
2977 			struct rtvia *via;
2978 
2979 			nla = nla_reserve(skb, RTA_VIA, alen + 2);
2980 			if (!nla)
2981 				goto nla_put_failure;
2982 
2983 			via = nla_data(nla);
2984 			via->rtvia_family = AF_INET6;
2985 			memcpy(via->rtvia_addr, &rt->rt_gw6, alen);
2986 		}
2987 	}
2988 
2989 	expires = rt->dst.expires;
2990 	if (expires) {
2991 		unsigned long now = jiffies;
2992 
2993 		if (time_before(now, expires))
2994 			expires -= now;
2995 		else
2996 			expires = 0;
2997 	}
2998 
2999 	memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics));
3000 	if (rt->rt_pmtu && expires)
3001 		metrics[RTAX_MTU - 1] = rt->rt_pmtu;
3002 	if (rt->rt_mtu_locked && expires)
3003 		metrics[RTAX_LOCK - 1] |= BIT(RTAX_MTU);
3004 	if (rtnetlink_put_metrics(skb, metrics) < 0)
3005 		goto nla_put_failure;
3006 
3007 	if (fl4) {
3008 		if (fl4->flowi4_mark &&
3009 		    nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark))
3010 			goto nla_put_failure;
3011 
3012 		if (!uid_eq(fl4->flowi4_uid, INVALID_UID) &&
3013 		    nla_put_u32(skb, RTA_UID,
3014 				from_kuid_munged(current_user_ns(),
3015 						 fl4->flowi4_uid)))
3016 			goto nla_put_failure;
3017 
3018 		if (rt_is_input_route(rt)) {
3019 #ifdef CONFIG_IP_MROUTE
3020 			if (ipv4_is_multicast(dst) &&
3021 			    !ipv4_is_local_multicast(dst) &&
3022 			    IPV4_DEVCONF_ALL(net, MC_FORWARDING)) {
3023 				int err = ipmr_get_route(net, skb,
3024 							 fl4->saddr, fl4->daddr,
3025 							 r, portid);
3026 
3027 				if (err <= 0) {
3028 					if (err == 0)
3029 						return 0;
3030 					goto nla_put_failure;
3031 				}
3032 			} else
3033 #endif
3034 				if (nla_put_u32(skb, RTA_IIF, fl4->flowi4_iif))
3035 					goto nla_put_failure;
3036 		}
3037 	}
3038 
3039 	error = rt->dst.error;
3040 
3041 	if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0)
3042 		goto nla_put_failure;
3043 
3044 	nlmsg_end(skb, nlh);
3045 	return 0;
3046 
3047 nla_put_failure:
3048 	nlmsg_cancel(skb, nlh);
3049 	return -EMSGSIZE;
3050 }
3051 
3052 static int fnhe_dump_bucket(struct net *net, struct sk_buff *skb,
3053 			    struct netlink_callback *cb, u32 table_id,
3054 			    struct fnhe_hash_bucket *bucket, int genid,
3055 			    int *fa_index, int fa_start, unsigned int flags)
3056 {
3057 	int i;
3058 
3059 	for (i = 0; i < FNHE_HASH_SIZE; i++) {
3060 		struct fib_nh_exception *fnhe;
3061 
3062 		for (fnhe = rcu_dereference(bucket[i].chain); fnhe;
3063 		     fnhe = rcu_dereference(fnhe->fnhe_next)) {
3064 			struct rtable *rt;
3065 			int err;
3066 
3067 			if (*fa_index < fa_start)
3068 				goto next;
3069 
3070 			if (fnhe->fnhe_genid != genid)
3071 				goto next;
3072 
3073 			if (fnhe->fnhe_expires &&
3074 			    time_after(jiffies, fnhe->fnhe_expires))
3075 				goto next;
3076 
3077 			rt = rcu_dereference(fnhe->fnhe_rth_input);
3078 			if (!rt)
3079 				rt = rcu_dereference(fnhe->fnhe_rth_output);
3080 			if (!rt)
3081 				goto next;
3082 
3083 			err = rt_fill_info(net, fnhe->fnhe_daddr, 0, rt,
3084 					   table_id, NULL, skb,
3085 					   NETLINK_CB(cb->skb).portid,
3086 					   cb->nlh->nlmsg_seq, flags);
3087 			if (err)
3088 				return err;
3089 next:
3090 			(*fa_index)++;
3091 		}
3092 	}
3093 
3094 	return 0;
3095 }
3096 
3097 int fib_dump_info_fnhe(struct sk_buff *skb, struct netlink_callback *cb,
3098 		       u32 table_id, struct fib_info *fi,
3099 		       int *fa_index, int fa_start, unsigned int flags)
3100 {
3101 	struct net *net = sock_net(cb->skb->sk);
3102 	int nhsel, genid = fnhe_genid(net);
3103 
3104 	for (nhsel = 0; nhsel < fib_info_num_path(fi); nhsel++) {
3105 		struct fib_nh_common *nhc = fib_info_nhc(fi, nhsel);
3106 		struct fnhe_hash_bucket *bucket;
3107 		int err;
3108 
3109 		if (nhc->nhc_flags & RTNH_F_DEAD)
3110 			continue;
3111 
3112 		rcu_read_lock();
3113 		bucket = rcu_dereference(nhc->nhc_exceptions);
3114 		err = 0;
3115 		if (bucket)
3116 			err = fnhe_dump_bucket(net, skb, cb, table_id, bucket,
3117 					       genid, fa_index, fa_start,
3118 					       flags);
3119 		rcu_read_unlock();
3120 		if (err)
3121 			return err;
3122 	}
3123 
3124 	return 0;
3125 }
3126 
3127 static struct sk_buff *inet_rtm_getroute_build_skb(__be32 src, __be32 dst,
3128 						   u8 ip_proto, __be16 sport,
3129 						   __be16 dport)
3130 {
3131 	struct sk_buff *skb;
3132 	struct iphdr *iph;
3133 
3134 	skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
3135 	if (!skb)
3136 		return NULL;
3137 
3138 	/* Reserve room for dummy headers, this skb can pass
3139 	 * through good chunk of routing engine.
3140 	 */
3141 	skb_reset_mac_header(skb);
3142 	skb_reset_network_header(skb);
3143 	skb->protocol = htons(ETH_P_IP);
3144 	iph = skb_put(skb, sizeof(struct iphdr));
3145 	iph->protocol = ip_proto;
3146 	iph->saddr = src;
3147 	iph->daddr = dst;
3148 	iph->version = 0x4;
3149 	iph->frag_off = 0;
3150 	iph->ihl = 0x5;
3151 	skb_set_transport_header(skb, skb->len);
3152 
3153 	switch (iph->protocol) {
3154 	case IPPROTO_UDP: {
3155 		struct udphdr *udph;
3156 
3157 		udph = skb_put_zero(skb, sizeof(struct udphdr));
3158 		udph->source = sport;
3159 		udph->dest = dport;
3160 		udph->len = htons(sizeof(struct udphdr));
3161 		udph->check = 0;
3162 		break;
3163 	}
3164 	case IPPROTO_TCP: {
3165 		struct tcphdr *tcph;
3166 
3167 		tcph = skb_put_zero(skb, sizeof(struct tcphdr));
3168 		tcph->source	= sport;
3169 		tcph->dest	= dport;
3170 		tcph->doff	= sizeof(struct tcphdr) / 4;
3171 		tcph->rst = 1;
3172 		tcph->check = ~tcp_v4_check(sizeof(struct tcphdr),
3173 					    src, dst, 0);
3174 		break;
3175 	}
3176 	case IPPROTO_ICMP: {
3177 		struct icmphdr *icmph;
3178 
3179 		icmph = skb_put_zero(skb, sizeof(struct icmphdr));
3180 		icmph->type = ICMP_ECHO;
3181 		icmph->code = 0;
3182 	}
3183 	}
3184 
3185 	return skb;
3186 }
3187 
3188 static int inet_rtm_valid_getroute_req(struct sk_buff *skb,
3189 				       const struct nlmsghdr *nlh,
3190 				       struct nlattr **tb,
3191 				       struct netlink_ext_ack *extack)
3192 {
3193 	struct rtmsg *rtm;
3194 	int i, err;
3195 
3196 	if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*rtm))) {
3197 		NL_SET_ERR_MSG(extack,
3198 			       "ipv4: Invalid header for route get request");
3199 		return -EINVAL;
3200 	}
3201 
3202 	if (!netlink_strict_get_check(skb))
3203 		return nlmsg_parse_deprecated(nlh, sizeof(*rtm), tb, RTA_MAX,
3204 					      rtm_ipv4_policy, extack);
3205 
3206 	rtm = nlmsg_data(nlh);
3207 	if ((rtm->rtm_src_len && rtm->rtm_src_len != 32) ||
3208 	    (rtm->rtm_dst_len && rtm->rtm_dst_len != 32) ||
3209 	    rtm->rtm_table || rtm->rtm_protocol ||
3210 	    rtm->rtm_scope || rtm->rtm_type) {
3211 		NL_SET_ERR_MSG(extack, "ipv4: Invalid values in header for route get request");
3212 		return -EINVAL;
3213 	}
3214 
3215 	if (rtm->rtm_flags & ~(RTM_F_NOTIFY |
3216 			       RTM_F_LOOKUP_TABLE |
3217 			       RTM_F_FIB_MATCH)) {
3218 		NL_SET_ERR_MSG(extack, "ipv4: Unsupported rtm_flags for route get request");
3219 		return -EINVAL;
3220 	}
3221 
3222 	err = nlmsg_parse_deprecated_strict(nlh, sizeof(*rtm), tb, RTA_MAX,
3223 					    rtm_ipv4_policy, extack);
3224 	if (err)
3225 		return err;
3226 
3227 	if ((tb[RTA_SRC] && !rtm->rtm_src_len) ||
3228 	    (tb[RTA_DST] && !rtm->rtm_dst_len)) {
3229 		NL_SET_ERR_MSG(extack, "ipv4: rtm_src_len and rtm_dst_len must be 32 for IPv4");
3230 		return -EINVAL;
3231 	}
3232 
3233 	for (i = 0; i <= RTA_MAX; i++) {
3234 		if (!tb[i])
3235 			continue;
3236 
3237 		switch (i) {
3238 		case RTA_IIF:
3239 		case RTA_OIF:
3240 		case RTA_SRC:
3241 		case RTA_DST:
3242 		case RTA_IP_PROTO:
3243 		case RTA_SPORT:
3244 		case RTA_DPORT:
3245 		case RTA_MARK:
3246 		case RTA_UID:
3247 			break;
3248 		default:
3249 			NL_SET_ERR_MSG(extack, "ipv4: Unsupported attribute in route get request");
3250 			return -EINVAL;
3251 		}
3252 	}
3253 
3254 	return 0;
3255 }
3256 
3257 static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh,
3258 			     struct netlink_ext_ack *extack)
3259 {
3260 	struct net *net = sock_net(in_skb->sk);
3261 	struct nlattr *tb[RTA_MAX+1];
3262 	u32 table_id = RT_TABLE_MAIN;
3263 	__be16 sport = 0, dport = 0;
3264 	struct fib_result res = {};
3265 	u8 ip_proto = IPPROTO_UDP;
3266 	struct rtable *rt = NULL;
3267 	struct sk_buff *skb;
3268 	struct rtmsg *rtm;
3269 	struct flowi4 fl4 = {};
3270 	__be32 dst = 0;
3271 	__be32 src = 0;
3272 	kuid_t uid;
3273 	u32 iif;
3274 	int err;
3275 	int mark;
3276 
3277 	err = inet_rtm_valid_getroute_req(in_skb, nlh, tb, extack);
3278 	if (err < 0)
3279 		return err;
3280 
3281 	rtm = nlmsg_data(nlh);
3282 	src = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0;
3283 	dst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0;
3284 	iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0;
3285 	mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0;
3286 	if (tb[RTA_UID])
3287 		uid = make_kuid(current_user_ns(), nla_get_u32(tb[RTA_UID]));
3288 	else
3289 		uid = (iif ? INVALID_UID : current_uid());
3290 
3291 	if (tb[RTA_IP_PROTO]) {
3292 		err = rtm_getroute_parse_ip_proto(tb[RTA_IP_PROTO],
3293 						  &ip_proto, AF_INET, extack);
3294 		if (err)
3295 			return err;
3296 	}
3297 
3298 	if (tb[RTA_SPORT])
3299 		sport = nla_get_be16(tb[RTA_SPORT]);
3300 
3301 	if (tb[RTA_DPORT])
3302 		dport = nla_get_be16(tb[RTA_DPORT]);
3303 
3304 	skb = inet_rtm_getroute_build_skb(src, dst, ip_proto, sport, dport);
3305 	if (!skb)
3306 		return -ENOBUFS;
3307 
3308 	fl4.daddr = dst;
3309 	fl4.saddr = src;
3310 	fl4.flowi4_tos = rtm->rtm_tos & IPTOS_RT_MASK;
3311 	fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0;
3312 	fl4.flowi4_mark = mark;
3313 	fl4.flowi4_uid = uid;
3314 	if (sport)
3315 		fl4.fl4_sport = sport;
3316 	if (dport)
3317 		fl4.fl4_dport = dport;
3318 	fl4.flowi4_proto = ip_proto;
3319 
3320 	rcu_read_lock();
3321 
3322 	if (iif) {
3323 		struct net_device *dev;
3324 
3325 		dev = dev_get_by_index_rcu(net, iif);
3326 		if (!dev) {
3327 			err = -ENODEV;
3328 			goto errout_rcu;
3329 		}
3330 
3331 		fl4.flowi4_iif = iif; /* for rt_fill_info */
3332 		skb->dev	= dev;
3333 		skb->mark	= mark;
3334 		err = ip_route_input_rcu(skb, dst, src,
3335 					 rtm->rtm_tos & IPTOS_RT_MASK, dev,
3336 					 &res);
3337 
3338 		rt = skb_rtable(skb);
3339 		if (err == 0 && rt->dst.error)
3340 			err = -rt->dst.error;
3341 	} else {
3342 		fl4.flowi4_iif = LOOPBACK_IFINDEX;
3343 		skb->dev = net->loopback_dev;
3344 		rt = ip_route_output_key_hash_rcu(net, &fl4, &res, skb);
3345 		err = 0;
3346 		if (IS_ERR(rt))
3347 			err = PTR_ERR(rt);
3348 		else
3349 			skb_dst_set(skb, &rt->dst);
3350 	}
3351 
3352 	if (err)
3353 		goto errout_rcu;
3354 
3355 	if (rtm->rtm_flags & RTM_F_NOTIFY)
3356 		rt->rt_flags |= RTCF_NOTIFY;
3357 
3358 	if (rtm->rtm_flags & RTM_F_LOOKUP_TABLE)
3359 		table_id = res.table ? res.table->tb_id : 0;
3360 
3361 	/* reset skb for netlink reply msg */
3362 	skb_trim(skb, 0);
3363 	skb_reset_network_header(skb);
3364 	skb_reset_transport_header(skb);
3365 	skb_reset_mac_header(skb);
3366 
3367 	if (rtm->rtm_flags & RTM_F_FIB_MATCH) {
3368 		struct fib_rt_info fri;
3369 
3370 		if (!res.fi) {
3371 			err = fib_props[res.type].error;
3372 			if (!err)
3373 				err = -EHOSTUNREACH;
3374 			goto errout_rcu;
3375 		}
3376 		fri.fi = res.fi;
3377 		fri.tb_id = table_id;
3378 		fri.dst = res.prefix;
3379 		fri.dst_len = res.prefixlen;
3380 		fri.tos = fl4.flowi4_tos;
3381 		fri.type = rt->rt_type;
3382 		fri.offload = 0;
3383 		fri.trap = 0;
3384 		fri.offload_failed = 0;
3385 		if (res.fa_head) {
3386 			struct fib_alias *fa;
3387 
3388 			hlist_for_each_entry_rcu(fa, res.fa_head, fa_list) {
3389 				u8 slen = 32 - fri.dst_len;
3390 
3391 				if (fa->fa_slen == slen &&
3392 				    fa->tb_id == fri.tb_id &&
3393 				    fa->fa_tos == fri.tos &&
3394 				    fa->fa_info == res.fi &&
3395 				    fa->fa_type == fri.type) {
3396 					fri.offload = fa->offload;
3397 					fri.trap = fa->trap;
3398 					break;
3399 				}
3400 			}
3401 		}
3402 		err = fib_dump_info(skb, NETLINK_CB(in_skb).portid,
3403 				    nlh->nlmsg_seq, RTM_NEWROUTE, &fri, 0);
3404 	} else {
3405 		err = rt_fill_info(net, dst, src, rt, table_id, &fl4, skb,
3406 				   NETLINK_CB(in_skb).portid,
3407 				   nlh->nlmsg_seq, 0);
3408 	}
3409 	if (err < 0)
3410 		goto errout_rcu;
3411 
3412 	rcu_read_unlock();
3413 
3414 	err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
3415 
3416 errout_free:
3417 	return err;
3418 errout_rcu:
3419 	rcu_read_unlock();
3420 	kfree_skb(skb);
3421 	goto errout_free;
3422 }
3423 
3424 void ip_rt_multicast_event(struct in_device *in_dev)
3425 {
3426 	rt_cache_flush(dev_net(in_dev->dev));
3427 }
3428 
3429 #ifdef CONFIG_SYSCTL
3430 static int ip_rt_gc_interval __read_mostly  = 60 * HZ;
3431 static int ip_rt_gc_min_interval __read_mostly	= HZ / 2;
3432 static int ip_rt_gc_elasticity __read_mostly	= 8;
3433 static int ip_min_valid_pmtu __read_mostly	= IPV4_MIN_MTU;
3434 
3435 static int ipv4_sysctl_rtcache_flush(struct ctl_table *__ctl, int write,
3436 		void *buffer, size_t *lenp, loff_t *ppos)
3437 {
3438 	struct net *net = (struct net *)__ctl->extra1;
3439 
3440 	if (write) {
3441 		rt_cache_flush(net);
3442 		fnhe_genid_bump(net);
3443 		return 0;
3444 	}
3445 
3446 	return -EINVAL;
3447 }
3448 
3449 static struct ctl_table ipv4_route_table[] = {
3450 	{
3451 		.procname	= "gc_thresh",
3452 		.data		= &ipv4_dst_ops.gc_thresh,
3453 		.maxlen		= sizeof(int),
3454 		.mode		= 0644,
3455 		.proc_handler	= proc_dointvec,
3456 	},
3457 	{
3458 		.procname	= "max_size",
3459 		.data		= &ip_rt_max_size,
3460 		.maxlen		= sizeof(int),
3461 		.mode		= 0644,
3462 		.proc_handler	= proc_dointvec,
3463 	},
3464 	{
3465 		/*  Deprecated. Use gc_min_interval_ms */
3466 
3467 		.procname	= "gc_min_interval",
3468 		.data		= &ip_rt_gc_min_interval,
3469 		.maxlen		= sizeof(int),
3470 		.mode		= 0644,
3471 		.proc_handler	= proc_dointvec_jiffies,
3472 	},
3473 	{
3474 		.procname	= "gc_min_interval_ms",
3475 		.data		= &ip_rt_gc_min_interval,
3476 		.maxlen		= sizeof(int),
3477 		.mode		= 0644,
3478 		.proc_handler	= proc_dointvec_ms_jiffies,
3479 	},
3480 	{
3481 		.procname	= "gc_timeout",
3482 		.data		= &ip_rt_gc_timeout,
3483 		.maxlen		= sizeof(int),
3484 		.mode		= 0644,
3485 		.proc_handler	= proc_dointvec_jiffies,
3486 	},
3487 	{
3488 		.procname	= "gc_interval",
3489 		.data		= &ip_rt_gc_interval,
3490 		.maxlen		= sizeof(int),
3491 		.mode		= 0644,
3492 		.proc_handler	= proc_dointvec_jiffies,
3493 	},
3494 	{
3495 		.procname	= "redirect_load",
3496 		.data		= &ip_rt_redirect_load,
3497 		.maxlen		= sizeof(int),
3498 		.mode		= 0644,
3499 		.proc_handler	= proc_dointvec,
3500 	},
3501 	{
3502 		.procname	= "redirect_number",
3503 		.data		= &ip_rt_redirect_number,
3504 		.maxlen		= sizeof(int),
3505 		.mode		= 0644,
3506 		.proc_handler	= proc_dointvec,
3507 	},
3508 	{
3509 		.procname	= "redirect_silence",
3510 		.data		= &ip_rt_redirect_silence,
3511 		.maxlen		= sizeof(int),
3512 		.mode		= 0644,
3513 		.proc_handler	= proc_dointvec,
3514 	},
3515 	{
3516 		.procname	= "error_cost",
3517 		.data		= &ip_rt_error_cost,
3518 		.maxlen		= sizeof(int),
3519 		.mode		= 0644,
3520 		.proc_handler	= proc_dointvec,
3521 	},
3522 	{
3523 		.procname	= "error_burst",
3524 		.data		= &ip_rt_error_burst,
3525 		.maxlen		= sizeof(int),
3526 		.mode		= 0644,
3527 		.proc_handler	= proc_dointvec,
3528 	},
3529 	{
3530 		.procname	= "gc_elasticity",
3531 		.data		= &ip_rt_gc_elasticity,
3532 		.maxlen		= sizeof(int),
3533 		.mode		= 0644,
3534 		.proc_handler	= proc_dointvec,
3535 	},
3536 	{
3537 		.procname	= "mtu_expires",
3538 		.data		= &ip_rt_mtu_expires,
3539 		.maxlen		= sizeof(int),
3540 		.mode		= 0644,
3541 		.proc_handler	= proc_dointvec_jiffies,
3542 	},
3543 	{
3544 		.procname	= "min_pmtu",
3545 		.data		= &ip_rt_min_pmtu,
3546 		.maxlen		= sizeof(int),
3547 		.mode		= 0644,
3548 		.proc_handler	= proc_dointvec_minmax,
3549 		.extra1		= &ip_min_valid_pmtu,
3550 	},
3551 	{
3552 		.procname	= "min_adv_mss",
3553 		.data		= &ip_rt_min_advmss,
3554 		.maxlen		= sizeof(int),
3555 		.mode		= 0644,
3556 		.proc_handler	= proc_dointvec,
3557 	},
3558 	{ }
3559 };
3560 
3561 static const char ipv4_route_flush_procname[] = "flush";
3562 
3563 static struct ctl_table ipv4_route_flush_table[] = {
3564 	{
3565 		.procname	= ipv4_route_flush_procname,
3566 		.maxlen		= sizeof(int),
3567 		.mode		= 0200,
3568 		.proc_handler	= ipv4_sysctl_rtcache_flush,
3569 	},
3570 	{ },
3571 };
3572 
3573 static __net_init int sysctl_route_net_init(struct net *net)
3574 {
3575 	struct ctl_table *tbl;
3576 
3577 	tbl = ipv4_route_flush_table;
3578 	if (!net_eq(net, &init_net)) {
3579 		tbl = kmemdup(tbl, sizeof(ipv4_route_flush_table), GFP_KERNEL);
3580 		if (!tbl)
3581 			goto err_dup;
3582 
3583 		/* Don't export non-whitelisted sysctls to unprivileged users */
3584 		if (net->user_ns != &init_user_ns) {
3585 			if (tbl[0].procname != ipv4_route_flush_procname)
3586 				tbl[0].procname = NULL;
3587 		}
3588 	}
3589 	tbl[0].extra1 = net;
3590 
3591 	net->ipv4.route_hdr = register_net_sysctl(net, "net/ipv4/route", tbl);
3592 	if (!net->ipv4.route_hdr)
3593 		goto err_reg;
3594 	return 0;
3595 
3596 err_reg:
3597 	if (tbl != ipv4_route_flush_table)
3598 		kfree(tbl);
3599 err_dup:
3600 	return -ENOMEM;
3601 }
3602 
3603 static __net_exit void sysctl_route_net_exit(struct net *net)
3604 {
3605 	struct ctl_table *tbl;
3606 
3607 	tbl = net->ipv4.route_hdr->ctl_table_arg;
3608 	unregister_net_sysctl_table(net->ipv4.route_hdr);
3609 	BUG_ON(tbl == ipv4_route_flush_table);
3610 	kfree(tbl);
3611 }
3612 
3613 static __net_initdata struct pernet_operations sysctl_route_ops = {
3614 	.init = sysctl_route_net_init,
3615 	.exit = sysctl_route_net_exit,
3616 };
3617 #endif
3618 
3619 static __net_init int rt_genid_init(struct net *net)
3620 {
3621 	atomic_set(&net->ipv4.rt_genid, 0);
3622 	atomic_set(&net->fnhe_genid, 0);
3623 	atomic_set(&net->ipv4.dev_addr_genid, get_random_int());
3624 	return 0;
3625 }
3626 
3627 static __net_initdata struct pernet_operations rt_genid_ops = {
3628 	.init = rt_genid_init,
3629 };
3630 
3631 static int __net_init ipv4_inetpeer_init(struct net *net)
3632 {
3633 	struct inet_peer_base *bp = kmalloc(sizeof(*bp), GFP_KERNEL);
3634 
3635 	if (!bp)
3636 		return -ENOMEM;
3637 	inet_peer_base_init(bp);
3638 	net->ipv4.peers = bp;
3639 	return 0;
3640 }
3641 
3642 static void __net_exit ipv4_inetpeer_exit(struct net *net)
3643 {
3644 	struct inet_peer_base *bp = net->ipv4.peers;
3645 
3646 	net->ipv4.peers = NULL;
3647 	inetpeer_invalidate_tree(bp);
3648 	kfree(bp);
3649 }
3650 
3651 static __net_initdata struct pernet_operations ipv4_inetpeer_ops = {
3652 	.init	=	ipv4_inetpeer_init,
3653 	.exit	=	ipv4_inetpeer_exit,
3654 };
3655 
3656 #ifdef CONFIG_IP_ROUTE_CLASSID
3657 struct ip_rt_acct __percpu *ip_rt_acct __read_mostly;
3658 #endif /* CONFIG_IP_ROUTE_CLASSID */
3659 
3660 int __init ip_rt_init(void)
3661 {
3662 	void *idents_hash;
3663 	int cpu;
3664 
3665 	/* For modern hosts, this will use 2 MB of memory */
3666 	idents_hash = alloc_large_system_hash("IP idents",
3667 					      sizeof(*ip_idents) + sizeof(*ip_tstamps),
3668 					      0,
3669 					      16, /* one bucket per 64 KB */
3670 					      HASH_ZERO,
3671 					      NULL,
3672 					      &ip_idents_mask,
3673 					      2048,
3674 					      256*1024);
3675 
3676 	ip_idents = idents_hash;
3677 
3678 	prandom_bytes(ip_idents, (ip_idents_mask + 1) * sizeof(*ip_idents));
3679 
3680 	ip_tstamps = idents_hash + (ip_idents_mask + 1) * sizeof(*ip_idents);
3681 
3682 	for_each_possible_cpu(cpu) {
3683 		struct uncached_list *ul = &per_cpu(rt_uncached_list, cpu);
3684 
3685 		INIT_LIST_HEAD(&ul->head);
3686 		spin_lock_init(&ul->lock);
3687 	}
3688 #ifdef CONFIG_IP_ROUTE_CLASSID
3689 	ip_rt_acct = __alloc_percpu(256 * sizeof(struct ip_rt_acct), __alignof__(struct ip_rt_acct));
3690 	if (!ip_rt_acct)
3691 		panic("IP: failed to allocate ip_rt_acct\n");
3692 #endif
3693 
3694 	ipv4_dst_ops.kmem_cachep =
3695 		kmem_cache_create("ip_dst_cache", sizeof(struct rtable), 0,
3696 				  SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
3697 
3698 	ipv4_dst_blackhole_ops.kmem_cachep = ipv4_dst_ops.kmem_cachep;
3699 
3700 	if (dst_entries_init(&ipv4_dst_ops) < 0)
3701 		panic("IP: failed to allocate ipv4_dst_ops counter\n");
3702 
3703 	if (dst_entries_init(&ipv4_dst_blackhole_ops) < 0)
3704 		panic("IP: failed to allocate ipv4_dst_blackhole_ops counter\n");
3705 
3706 	ipv4_dst_ops.gc_thresh = ~0;
3707 	ip_rt_max_size = INT_MAX;
3708 
3709 	devinet_init();
3710 	ip_fib_init();
3711 
3712 	if (ip_rt_proc_init())
3713 		pr_err("Unable to create route proc files\n");
3714 #ifdef CONFIG_XFRM
3715 	xfrm_init();
3716 	xfrm4_init();
3717 #endif
3718 	rtnl_register(PF_INET, RTM_GETROUTE, inet_rtm_getroute, NULL,
3719 		      RTNL_FLAG_DOIT_UNLOCKED);
3720 
3721 #ifdef CONFIG_SYSCTL
3722 	register_pernet_subsys(&sysctl_route_ops);
3723 #endif
3724 	register_pernet_subsys(&rt_genid_ops);
3725 	register_pernet_subsys(&ipv4_inetpeer_ops);
3726 	return 0;
3727 }
3728 
3729 #ifdef CONFIG_SYSCTL
3730 /*
3731  * We really need to sanitize the damn ipv4 init order, then all
3732  * this nonsense will go away.
3733  */
3734 void __init ip_static_sysctl_init(void)
3735 {
3736 	register_net_sysctl(&init_net, "net/ipv4/route", ipv4_route_table);
3737 }
3738 #endif
3739