xref: /linux/net/ipv4/udp.c (revision d77700039d09479f81f0bc8b73002af8ec95d3f7)
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  *		The User Datagram Protocol (UDP).
8  *
9  * Authors:	Ross Biro
10  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
11  *		Arnt Gulbrandsen, <agulbra@nvg.unit.no>
12  *		Alan Cox, <alan@lxorguk.ukuu.org.uk>
13  *		Hirokazu Takahashi, <taka@valinux.co.jp>
14  *
15  * Fixes:
16  *		Alan Cox	:	verify_area() calls
17  *		Alan Cox	: 	stopped close while in use off icmp
18  *					messages. Not a fix but a botch that
19  *					for udp at least is 'valid'.
20  *		Alan Cox	:	Fixed icmp handling properly
21  *		Alan Cox	: 	Correct error for oversized datagrams
22  *		Alan Cox	:	Tidied select() semantics.
23  *		Alan Cox	:	udp_err() fixed properly, also now
24  *					select and read wake correctly on errors
25  *		Alan Cox	:	udp_send verify_area moved to avoid mem leak
26  *		Alan Cox	:	UDP can count its memory
27  *		Alan Cox	:	send to an unknown connection causes
28  *					an ECONNREFUSED off the icmp, but
29  *					does NOT close.
30  *		Alan Cox	:	Switched to new sk_buff handlers. No more backlog!
31  *		Alan Cox	:	Using generic datagram code. Even smaller and the PEEK
32  *					bug no longer crashes it.
33  *		Fred Van Kempen	: 	Net2e support for sk->broadcast.
34  *		Alan Cox	:	Uses skb_free_datagram
35  *		Alan Cox	:	Added get/set sockopt support.
36  *		Alan Cox	:	Broadcasting without option set returns EACCES.
37  *		Alan Cox	:	No wakeup calls. Instead we now use the callbacks.
38  *		Alan Cox	:	Use ip_tos and ip_ttl
39  *		Alan Cox	:	SNMP Mibs
40  *		Alan Cox	:	MSG_DONTROUTE, and 0.0.0.0 support.
41  *		Matt Dillon	:	UDP length checks.
42  *		Alan Cox	:	Smarter af_inet used properly.
43  *		Alan Cox	:	Use new kernel side addressing.
44  *		Alan Cox	:	Incorrect return on truncated datagram receive.
45  *	Arnt Gulbrandsen 	:	New udp_send and stuff
46  *		Alan Cox	:	Cache last socket
47  *		Alan Cox	:	Route cache
48  *		Jon Peatfield	:	Minor efficiency fix to sendto().
49  *		Mike Shaver	:	RFC1122 checks.
50  *		Alan Cox	:	Nonblocking error fix.
51  *	Willy Konynenberg	:	Transparent proxying support.
52  *		Mike McLagan	:	Routing by source
53  *		David S. Miller	:	New socket lookup architecture.
54  *					Last socket cache retained as it
55  *					does have a high hit rate.
56  *		Olaf Kirch	:	Don't linearise iovec on sendmsg.
57  *		Andi Kleen	:	Some cleanups, cache destination entry
58  *					for connect.
59  *	Vitaly E. Lavrov	:	Transparent proxy revived after year coma.
60  *		Melvin Smith	:	Check msg_name not msg_namelen in sendto(),
61  *					return ENOTCONN for unconnected sockets (POSIX)
62  *		Janos Farkas	:	don't deliver multi/broadcasts to a different
63  *					bound-to-device socket
64  *	Hirokazu Takahashi	:	HW checksumming for outgoing UDP
65  *					datagrams.
66  *	Hirokazu Takahashi	:	sendfile() on UDP works now.
67  *		Arnaldo C. Melo :	convert /proc/net/udp to seq_file
68  *	YOSHIFUJI Hideaki @USAGI and:	Support IPV6_V6ONLY socket option, which
69  *	Alexey Kuznetsov:		allow both IPv4 and IPv6 sockets to bind
70  *					a single port at the same time.
71  *	Derek Atkins <derek@ihtfp.com>: Add Encapsulation Support
72  *	James Chapman		:	Add L2TP encapsulation type.
73  */
74 
75 #define pr_fmt(fmt) "UDP: " fmt
76 
77 #include <linux/bpf-cgroup.h>
78 #include <linux/uaccess.h>
79 #include <linux/uio.h>
80 #include <asm/ioctls.h>
81 #include <linux/memblock.h>
82 #include <linux/highmem.h>
83 #include <linux/types.h>
84 #include <linux/fcntl.h>
85 #include <linux/module.h>
86 #include <linux/socket.h>
87 #include <linux/sockios.h>
88 #include <linux/igmp.h>
89 #include <linux/inetdevice.h>
90 #include <linux/in.h>
91 #include <linux/errno.h>
92 #include <linux/timer.h>
93 #include <linux/mm.h>
94 #include <linux/inet.h>
95 #include <linux/netdevice.h>
96 #include <linux/slab.h>
97 #include <linux/sock_diag.h>
98 #include <net/tcp_states.h>
99 #include <linux/skbuff.h>
100 #include <linux/proc_fs.h>
101 #include <linux/seq_file.h>
102 #include <net/aligned_data.h>
103 #include <net/net_namespace.h>
104 #include <net/icmp.h>
105 #include <net/inet_common.h>
106 #include <net/inet_hashtables.h>
107 #include <net/ip.h>
108 #include <net/ip_tunnels.h>
109 #include <net/route.h>
110 #include <net/checksum.h>
111 #include <net/gso.h>
112 #include <net/xfrm.h>
113 #include <trace/events/udp.h>
114 #include <linux/static_key.h>
115 #include <linux/btf_ids.h>
116 #include <trace/events/skb.h>
117 #include <net/busy_poll.h>
118 #include <net/sock_reuseport.h>
119 #include <net/addrconf.h>
120 #include <net/udp_tunnel.h>
121 #include <net/gro.h>
122 #include <net/rps.h>
123 
124 struct udp_table udp_table __read_mostly;
125 
126 long sysctl_udp_mem[3] __read_mostly;
127 
128 DEFINE_PER_CPU(int, udp_memory_per_cpu_fw_alloc);
129 EXPORT_PER_CPU_SYMBOL_GPL(udp_memory_per_cpu_fw_alloc);
130 
131 #define MAX_UDP_PORTS 65536
132 #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN_PERNET)
133 
134 static bool udp_sk_reuseport_match(struct sock *sk, struct sock *sk2)
135 {
136 	return sk2->sk_family == sk->sk_family &&
137 	       ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
138 	       sk2->sk_bound_dev_if == sk->sk_bound_dev_if &&
139 	       sk2->sk_reuse == sk->sk_reuse &&
140 	       inet_rcv_saddr_equal(sk, sk2, false);
141 }
142 
143 static int udp_lib_lport_inuse(struct net *net, __u16 num,
144 			       const struct udp_hslot *hslot,
145 			       unsigned long *bitmap,
146 			       struct sock *sk, unsigned int log)
147 {
148 	kuid_t uid = sk_uid(sk);
149 	struct sock *sk2;
150 
151 	/* With @bitmap we are scanning for a free port: every port in use
152 	 * is marked, whatever reuse options the sockets have. Without it
153 	 * we are checking a specific port and honour the reuse options.
154 	 */
155 	sk_for_each(sk2, &hslot->head) {
156 		if (net_eq(sock_net(sk2), net) &&
157 		    sk2 != sk &&
158 		    (bitmap || udp_sk(sk2)->udp_port_hash == num) &&
159 		    (bitmap || !sk2->sk_reuse || !sk->sk_reuse) &&
160 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
161 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
162 		    inet_rcv_saddr_equal(sk, sk2, true)) {
163 			if (!bitmap) {
164 				if (sk2->sk_reuseport && sk->sk_reuseport &&
165 				    !rcu_access_pointer(sk->sk_reuseport_cb) &&
166 				    uid_eq(uid, sk_uid(sk2))) {
167 					if (udp_sk_reuseport_match(sk, sk2))
168 						return 0;
169 					continue;
170 				}
171 				return 1;
172 			}
173 			__set_bit(udp_sk(sk2)->udp_port_hash >> log, bitmap);
174 		}
175 	}
176 	return 0;
177 }
178 
179 /*
180  * Note: we still hold spinlock of primary hash chain, so no other writer
181  * can insert/delete a socket with local_port == num
182  */
183 static int udp_lib_lport_inuse2(struct net *net, __u16 num,
184 				struct udp_hslot *hslot2,
185 				struct sock *sk)
186 {
187 	kuid_t uid = sk_uid(sk);
188 	struct sock *sk2;
189 	int res = 0;
190 
191 	spin_lock(&hslot2->lock);
192 	udp_portaddr_for_each_entry(sk2, &hslot2->head) {
193 		if (net_eq(sock_net(sk2), net) &&
194 		    sk2 != sk &&
195 		    (udp_sk(sk2)->udp_port_hash == num) &&
196 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
197 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
198 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
199 		    inet_rcv_saddr_equal(sk, sk2, true)) {
200 			if (sk2->sk_reuseport && sk->sk_reuseport &&
201 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
202 			    uid_eq(uid, sk_uid(sk2))) {
203 				if (udp_sk_reuseport_match(sk, sk2)) {
204 					res = 0;
205 					break;
206 				}
207 				continue;
208 			}
209 			res = 1;
210 			break;
211 		}
212 	}
213 	spin_unlock(&hslot2->lock);
214 	return res;
215 }
216 
217 static int udp_reuseport_add_sock(struct sock *sk, struct udp_hslot *hslot)
218 {
219 	struct net *net = sock_net(sk);
220 	kuid_t uid = sk_uid(sk);
221 	struct sock *sk2;
222 
223 	sk_for_each(sk2, &hslot->head) {
224 		if (net_eq(sock_net(sk2), net) &&
225 		    sk2 != sk &&
226 		    sk2->sk_family == sk->sk_family &&
227 		    ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
228 		    (udp_sk(sk2)->udp_port_hash == udp_sk(sk)->udp_port_hash) &&
229 		    (sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
230 		    sk2->sk_reuseport && uid_eq(uid, sk_uid(sk2)) &&
231 		    inet_rcv_saddr_equal(sk, sk2, false)) {
232 			return reuseport_add_sock(sk, sk2,
233 						  inet_rcv_saddr_any(sk));
234 		}
235 	}
236 
237 	return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
238 }
239 
240 /**
241  *  udp_lib_get_port  -  UDP port lookup for IPv4 and IPv6
242  *
243  *  @sk:          socket struct in question
244  *  @snum:        port number to look up
245  *  @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
246  *                   with NULL address
247  */
248 int udp_lib_get_port(struct sock *sk, unsigned short snum,
249 		     unsigned int hash2_nulladdr)
250 {
251 	struct udp_hslot *hslot, *hslot2;
252 	struct net *net = sock_net(sk);
253 	struct udp_table *udptable;
254 	int error = -EADDRINUSE;
255 
256 	udptable = net->ipv4.udp_table;
257 
258 	if (!snum) {
259 		DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
260 		unsigned short first, last;
261 		int low, high, remaining;
262 		unsigned int rand;
263 
264 		inet_sk_get_local_port_range(sk, &low, &high);
265 		remaining = (high - low) + 1;
266 
267 		rand = get_random_u32();
268 		first = reciprocal_scale(rand, remaining) + low;
269 		/*
270 		 * force rand to be an odd multiple of UDP_HTABLE_SIZE
271 		 */
272 		rand = (rand | 1) * (udptable->mask + 1);
273 		last = first + udptable->mask + 1;
274 		do {
275 			hslot = udp_hashslot(udptable, net, first);
276 			bitmap_zero(bitmap, PORTS_PER_CHAIN);
277 			spin_lock_bh(&hslot->lock);
278 			udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
279 					    udptable->log);
280 
281 			snum = first;
282 			/*
283 			 * Iterate on all possible values of snum for this hash.
284 			 * Using steps of an odd multiple of UDP_HTABLE_SIZE
285 			 * give us randomization and full range coverage.
286 			 */
287 			do {
288 				if (low <= snum && snum <= high &&
289 				    !test_bit(snum >> udptable->log, bitmap) &&
290 				    !inet_is_local_reserved_port(net, snum))
291 					goto found;
292 				snum += rand;
293 			} while (snum != first);
294 			spin_unlock_bh(&hslot->lock);
295 			cond_resched();
296 		} while (++first != last);
297 		goto fail;
298 	} else {
299 		hslot = udp_hashslot(udptable, net, snum);
300 		spin_lock_bh(&hslot->lock);
301 		if (inet_use_hash2_on_bind(sk) && hslot->count > 10) {
302 			int exist;
303 			unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
304 
305 			slot2          &= udptable->mask;
306 			hash2_nulladdr &= udptable->mask;
307 
308 			hslot2 = udp_hashslot2(udptable, slot2);
309 			if (hslot->count < hslot2->count)
310 				goto scan_primary_hash;
311 
312 			exist = udp_lib_lport_inuse2(net, snum, hslot2, sk);
313 			if (!exist && (hash2_nulladdr != slot2)) {
314 				hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
315 				exist = udp_lib_lport_inuse2(net, snum, hslot2,
316 							     sk);
317 			}
318 			if (exist)
319 				goto fail_unlock;
320 			else
321 				goto found;
322 		}
323 scan_primary_hash:
324 		if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, 0))
325 			goto fail_unlock;
326 	}
327 found:
328 	inet_sk(sk)->inet_num = snum;
329 	udp_sk(sk)->udp_port_hash = snum;
330 	udp_sk(sk)->udp_portaddr_hash ^= snum;
331 	if (sk_unhashed(sk)) {
332 		if (sk->sk_reuseport &&
333 		    udp_reuseport_add_sock(sk, hslot)) {
334 			inet_sk(sk)->inet_num = 0;
335 			udp_sk(sk)->udp_port_hash = 0;
336 			udp_sk(sk)->udp_portaddr_hash ^= snum;
337 			goto fail_unlock;
338 		}
339 
340 		sock_set_flag(sk, SOCK_RCU_FREE);
341 
342 		sk_add_node_rcu(sk, &hslot->head);
343 		hslot->count++;
344 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
345 
346 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
347 		spin_lock(&hslot2->lock);
348 		if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
349 		    sk->sk_family == AF_INET6)
350 			hlist_add_tail_rcu(&udp_sk(sk)->udp_portaddr_node,
351 					   &hslot2->head);
352 		else
353 			hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
354 					   &hslot2->head);
355 		hslot2->count++;
356 		spin_unlock(&hslot2->lock);
357 	}
358 
359 	error = 0;
360 fail_unlock:
361 	spin_unlock_bh(&hslot->lock);
362 fail:
363 	return error;
364 }
365 
366 static int udp_v4_get_port(struct sock *sk, unsigned short snum)
367 {
368 	unsigned int hash2_nulladdr =
369 		ipv4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
370 	unsigned int hash2_partial =
371 		ipv4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
372 
373 	/* precompute partial secondary hash */
374 	udp_sk(sk)->udp_portaddr_hash = hash2_partial;
375 	return udp_lib_get_port(sk, snum, hash2_nulladdr);
376 }
377 
378 static __always_inline int
379 compute_score(struct sock *sk, const struct net *net,
380 	      __be32 saddr, __be16 sport, __be32 daddr,
381 	      unsigned short hnum, int dif, int sdif)
382 {
383 	int score;
384 	struct inet_sock *inet;
385 	bool dev_match;
386 
387 	if (!net_eq(sock_net(sk), net) ||
388 	    udp_sk(sk)->udp_port_hash != hnum ||
389 	    ipv6_only_sock(sk))
390 		return -1;
391 
392 	if (sk->sk_rcv_saddr != daddr)
393 		return -1;
394 
395 	score = (sk->sk_family == PF_INET) ? 2 : 1;
396 
397 	inet = inet_sk(sk);
398 	if (inet->inet_daddr) {
399 		if (inet->inet_daddr != saddr)
400 			return -1;
401 		score += 4;
402 	}
403 
404 	if (inet->inet_dport) {
405 		if (inet->inet_dport != sport)
406 			return -1;
407 		score += 4;
408 	}
409 
410 	dev_match = udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if,
411 					dif, sdif);
412 	if (!dev_match)
413 		return -1;
414 	if (sk->sk_bound_dev_if)
415 		score += 4;
416 
417 	if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
418 		score++;
419 	return score;
420 }
421 
422 u32 udp_ehashfn(const struct net *net, const __be32 laddr, const __u16 lport,
423 		const __be32 faddr, const __be16 fport)
424 {
425 	net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret));
426 
427 	return __inet_ehashfn(laddr, lport, faddr, fport,
428 			      udp_ehash_secret + net_hash_mix(net));
429 }
430 
431 /**
432  * udp4_lib_lookup1() - Simplified lookup using primary hash (destination port)
433  * @net:	Network namespace
434  * @saddr:	Source address, network order
435  * @sport:	Source port, network order
436  * @daddr:	Destination address, network order
437  * @hnum:	Destination port, host order
438  * @dif:	Destination interface index
439  * @sdif:	Destination bridge port index, if relevant
440  * @udptable:	Set of UDP hash tables
441  *
442  * Simplified lookup to be used as fallback if no sockets are found due to a
443  * potential race between (receive) address change, and lookup happening before
444  * the rehash operation. This function ignores SO_REUSEPORT groups while scoring
445  * result sockets, because if we have one, we don't need the fallback at all.
446  *
447  * Called under rcu_read_lock().
448  *
449  * Return: socket with highest matching score if any, NULL if none
450  */
451 static struct sock *udp4_lib_lookup1(const struct net *net,
452 				     __be32 saddr, __be16 sport,
453 				     __be32 daddr, unsigned int hnum,
454 				     int dif, int sdif,
455 				     const struct udp_table *udptable)
456 {
457 	unsigned int slot = udp_hashfn(net, hnum, udptable->mask);
458 	struct udp_hslot *hslot = &udptable->hash[slot];
459 	struct sock *sk, *result = NULL;
460 	int score, badness = 0;
461 
462 	sk_for_each_rcu(sk, &hslot->head) {
463 		score = compute_score(sk, net,
464 				      saddr, sport, daddr, hnum, dif, sdif);
465 		if (score > badness) {
466 			result = sk;
467 			badness = score;
468 		}
469 	}
470 
471 	return result;
472 }
473 
474 /* called with rcu_read_lock() */
475 static struct sock *udp4_lib_lookup2(const struct net *net,
476 				     __be32 saddr, __be16 sport,
477 				     __be32 daddr, unsigned int hnum,
478 				     int dif, int sdif,
479 				     struct udp_hslot *hslot2,
480 				     struct sk_buff *skb)
481 {
482 	struct sock *sk, *result;
483 	int score, badness;
484 	bool need_rescore;
485 
486 	result = NULL;
487 	badness = 0;
488 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
489 		need_rescore = false;
490 rescore:
491 		score = compute_score(need_rescore ? result : sk, net, saddr,
492 				      sport, daddr, hnum, dif, sdif);
493 		if (score > badness) {
494 			badness = score;
495 
496 			if (need_rescore)
497 				continue;
498 
499 			if (sk->sk_state == TCP_ESTABLISHED) {
500 				result = sk;
501 				continue;
502 			}
503 
504 			result = inet_lookup_reuseport(net, sk, skb, sizeof(struct udphdr),
505 						       saddr, sport, daddr, hnum, udp_ehashfn);
506 			if (!result) {
507 				result = sk;
508 				continue;
509 			}
510 
511 			/* Fall back to scoring if group has connections */
512 			if (!reuseport_has_conns(sk))
513 				return result;
514 
515 			/* Reuseport logic returned an error, keep original score. */
516 			if (IS_ERR(result))
517 				continue;
518 
519 			/* compute_score is too long of a function to be
520 			 * inlined twice here, and calling it uninlined
521 			 * here yields measurable overhead for some
522 			 * workloads. Work around it by jumping
523 			 * backwards to rescore 'result'.
524 			 */
525 			need_rescore = true;
526 			goto rescore;
527 		}
528 	}
529 	return result;
530 }
531 
532 #if IS_ENABLED(CONFIG_BASE_SMALL)
533 static struct sock *udp4_lib_lookup4(const struct net *net,
534 				     __be32 saddr, __be16 sport,
535 				     __be32 daddr, unsigned int hnum,
536 				     int dif, int sdif,
537 				     struct udp_table *udptable)
538 {
539 	return NULL;
540 }
541 
542 static void udp_rehash4(struct udp_table *udptable, struct sock *sk,
543 			u16 newhash4)
544 {
545 }
546 
547 static void udp_unhash4(struct udp_table *udptable, struct sock *sk)
548 {
549 }
550 #else /* !CONFIG_BASE_SMALL */
551 static struct sock *udp4_lib_lookup4(const struct net *net,
552 				     __be32 saddr, __be16 sport,
553 				     __be32 daddr, unsigned int hnum,
554 				     int dif, int sdif,
555 				     struct udp_table *udptable)
556 {
557 	const __portpair ports = INET_COMBINED_PORTS(sport, hnum);
558 	const struct hlist_nulls_node *node;
559 	struct udp_hslot *hslot4;
560 	unsigned int hash4, slot;
561 	struct udp_sock *up;
562 	struct sock *sk;
563 
564 	hash4 = udp_ehashfn(net, daddr, hnum, saddr, sport);
565 	slot = hash4 & udptable->mask;
566 	hslot4 = &udptable->hash4[slot];
567 	INET_ADDR_COOKIE(acookie, saddr, daddr);
568 
569 begin:
570 	/* SLAB_TYPESAFE_BY_RCU not used, so we don't need to touch sk_refcnt */
571 	udp_lrpa_for_each_entry_rcu(up, node, &hslot4->nulls_head) {
572 		sk = (struct sock *)up;
573 		if (inet_match(net, sk, acookie, ports, dif, sdif))
574 			return sk;
575 	}
576 
577 	/* if the nulls value we got at the end of this lookup is not the
578 	 * expected one, we must restart lookup. We probably met an item that
579 	 * was moved to another chain due to rehash.
580 	 */
581 	if (get_nulls_value(node) != slot)
582 		goto begin;
583 
584 	return NULL;
585 }
586 
587 /* udp_rehash4() only checks hslot4, and hash4_cnt is not processed. */
588 static void udp_rehash4(struct udp_table *udptable, struct sock *sk,
589 			u16 newhash4)
590 {
591 	struct udp_hslot *hslot4, *nhslot4;
592 
593 	hslot4 = udp_hashslot4(udptable, udp_sk(sk)->udp_lrpa_hash);
594 	nhslot4 = udp_hashslot4(udptable, newhash4);
595 	udp_sk(sk)->udp_lrpa_hash = newhash4;
596 
597 	if (hslot4 != nhslot4) {
598 		spin_lock_bh(&hslot4->lock);
599 		hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_lrpa_node);
600 		hslot4->count--;
601 		spin_unlock_bh(&hslot4->lock);
602 
603 		spin_lock_bh(&nhslot4->lock);
604 		hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_lrpa_node,
605 					 &nhslot4->nulls_head);
606 		nhslot4->count++;
607 		spin_unlock_bh(&nhslot4->lock);
608 	}
609 }
610 
611 static void udp_unhash4(struct udp_table *udptable, struct sock *sk)
612 {
613 	struct udp_hslot *hslot2, *hslot4;
614 
615 	if (udp_hashed4(sk)) {
616 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
617 		hslot4 = udp_hashslot4(udptable, udp_sk(sk)->udp_lrpa_hash);
618 
619 		spin_lock(&hslot4->lock);
620 		hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_lrpa_node);
621 		hslot4->count--;
622 		spin_unlock(&hslot4->lock);
623 
624 		spin_lock(&hslot2->lock);
625 		udp_hash4_dec(hslot2);
626 		spin_unlock(&hslot2->lock);
627 	}
628 }
629 
630 void udp_lib_hash4(struct sock *sk, u16 hash)
631 {
632 	struct udp_hslot *hslot, *hslot2, *hslot4;
633 	struct net *net = sock_net(sk);
634 	struct udp_table *udptable;
635 
636 	udptable = net->ipv4.udp_table;
637 	hslot = udp_hashslot(udptable, net, udp_sk(sk)->udp_port_hash);
638 
639 	/* A connected socket can re-connect to another address. rehash()
640 	 * relocates it, but only runs when the local address changes, so a
641 	 * socket bound to a specific address would stay filed under the
642 	 * previous peer's hash. Move it here.
643 	 */
644 	if (udp_hashed4(sk)) {
645 		if (udp_sk(sk)->udp_lrpa_hash != hash) {
646 			spin_lock_bh(&hslot->lock);
647 			udp_rehash4(udptable, sk, hash);
648 			spin_unlock_bh(&hslot->lock);
649 		}
650 		return;
651 	}
652 
653 	hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
654 	hslot4 = udp_hashslot4(udptable, hash);
655 	udp_sk(sk)->udp_lrpa_hash = hash;
656 
657 	spin_lock_bh(&hslot->lock);
658 	if (rcu_access_pointer(sk->sk_reuseport_cb))
659 		reuseport_detach_sock(sk);
660 
661 	spin_lock(&hslot4->lock);
662 	hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_lrpa_node,
663 				 &hslot4->nulls_head);
664 	hslot4->count++;
665 	spin_unlock(&hslot4->lock);
666 
667 	spin_lock(&hslot2->lock);
668 	udp_hash4_inc(hslot2);
669 	spin_unlock(&hslot2->lock);
670 
671 	spin_unlock_bh(&hslot->lock);
672 }
673 
674 /* call with sock lock */
675 void udp4_hash4(struct sock *sk)
676 {
677 	struct net *net = sock_net(sk);
678 	unsigned int hash;
679 
680 	if (sk_unhashed(sk) || sk->sk_rcv_saddr == htonl(INADDR_ANY))
681 		return;
682 
683 	hash = udp_ehashfn(net, sk->sk_rcv_saddr, sk->sk_num,
684 			   sk->sk_daddr, sk->sk_dport);
685 
686 	udp_lib_hash4(sk, hash);
687 }
688 #endif /* CONFIG_BASE_SMALL */
689 
690 /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
691  * harder than this. -DaveM
692  */
693 struct sock *__udp4_lib_lookup(const struct net *net, __be32 saddr,
694 			       __be16 sport, __be32 daddr, __be16 dport,
695 			       int dif, int sdif, struct sk_buff *skb)
696 {
697 	struct udp_table *udptable = net->ipv4.udp_table;
698 	unsigned short hnum = ntohs(dport);
699 	struct udp_hslot *hslot2;
700 	struct sock *result, *sk;
701 	unsigned int hash2;
702 
703 	hash2 = ipv4_portaddr_hash(net, daddr, hnum);
704 	hslot2 = udp_hashslot2(udptable, hash2);
705 
706 	if (udp_has_hash4(hslot2)) {
707 		result = udp4_lib_lookup4(net, saddr, sport, daddr, hnum,
708 					  dif, sdif, udptable);
709 		if (result) /* udp4_lib_lookup4 return sk or NULL */
710 			return result;
711 	}
712 
713 	/* Lookup connected or non-wildcard socket */
714 	result = udp4_lib_lookup2(net, saddr, sport,
715 				  daddr, hnum, dif, sdif,
716 				  hslot2, skb);
717 	if (!IS_ERR_OR_NULL(result) && result->sk_state == TCP_ESTABLISHED)
718 		goto done;
719 
720 	/* Lookup redirect from BPF */
721 	if (static_branch_unlikely(&bpf_sk_lookup_enabled)) {
722 		sk = inet_lookup_run_sk_lookup(net, IPPROTO_UDP, skb, sizeof(struct udphdr),
723 					       saddr, sport, daddr, hnum, dif,
724 					       udp_ehashfn);
725 		if (sk) {
726 			result = sk;
727 			goto done;
728 		}
729 	}
730 
731 	/* Got non-wildcard socket or error on first lookup */
732 	if (result)
733 		goto done;
734 
735 	/* Lookup wildcard sockets */
736 	hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
737 	hslot2 = udp_hashslot2(udptable, hash2);
738 
739 	result = udp4_lib_lookup2(net, saddr, sport,
740 				  htonl(INADDR_ANY), hnum, dif, sdif,
741 				  hslot2, skb);
742 	if (!IS_ERR_OR_NULL(result))
743 		goto done;
744 
745 	/* Primary hash (destination port) lookup as fallback for this race:
746 	 *   1. __ip4_datagram_connect() sets sk_rcv_saddr
747 	 *   2. lookup (this function): new sk_rcv_saddr, hashes not updated yet
748 	 *   3. rehash operation updating _secondary and four-tuple_ hashes
749 	 * The primary hash doesn't need an update after 1., so, thanks to this
750 	 * further step, 1. and 3. don't need to be atomic against the lookup.
751 	 */
752 	result = udp4_lib_lookup1(net, saddr, sport, daddr, hnum, dif, sdif,
753 				  udptable);
754 
755 done:
756 	if (IS_ERR(result))
757 		return NULL;
758 	return result;
759 }
760 EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
761 
762 static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
763 						 __be16 sport, __be16 dport)
764 {
765 	const struct iphdr *iph = ip_hdr(skb);
766 
767 	return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
768 				 iph->daddr, dport, inet_iif(skb),
769 				 inet_sdif(skb), skb);
770 }
771 
772 struct sock *udp4_lib_lookup_skb(const struct sk_buff *skb,
773 				 __be16 sport, __be16 dport)
774 {
775 	const u16 offset = NAPI_GRO_CB(skb)->network_offsets[skb->encapsulation];
776 	const struct iphdr *iph = (struct iphdr *)(skb->data + offset);
777 	int iif, sdif;
778 
779 	inet_get_iif_sdif(skb, &iif, &sdif);
780 
781 	return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
782 				 iph->daddr, dport, iif, sdif, NULL);
783 }
784 
785 /* Must be called under rcu_read_lock().
786  * Does increment socket refcount.
787  */
788 #if IS_ENABLED(CONFIG_NF_TPROXY_IPV4) || IS_ENABLED(CONFIG_NF_SOCKET_IPV4)
789 struct sock *udp4_lib_lookup(const struct net *net, __be32 saddr, __be16 sport,
790 			     __be32 daddr, __be16 dport, int dif)
791 {
792 	struct sock *sk;
793 
794 	sk = __udp4_lib_lookup(net, saddr, sport, daddr, dport, dif, 0, NULL);
795 	if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
796 		sk = NULL;
797 	return sk;
798 }
799 EXPORT_SYMBOL_GPL(udp4_lib_lookup);
800 #endif
801 
802 static inline bool __udp_is_mcast_sock(struct net *net, const struct sock *sk,
803 				       __be16 loc_port, __be32 loc_addr,
804 				       __be16 rmt_port, __be32 rmt_addr,
805 				       int dif, int sdif, unsigned short hnum)
806 {
807 	const struct inet_sock *inet = inet_sk(sk);
808 
809 	if (!net_eq(sock_net(sk), net) ||
810 	    udp_sk(sk)->udp_port_hash != hnum ||
811 	    (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
812 	    (inet->inet_dport != rmt_port && inet->inet_dport) ||
813 	    (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) ||
814 	    ipv6_only_sock(sk) ||
815 	    !udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif))
816 		return false;
817 	if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif, sdif))
818 		return false;
819 	return true;
820 }
821 
822 DEFINE_STATIC_KEY_FALSE(udp_encap_needed_key);
823 
824 #if IS_ENABLED(CONFIG_IPV6)
825 DEFINE_STATIC_KEY_FALSE(udpv6_encap_needed_key);
826 #endif
827 
828 void udp_encap_enable(void)
829 {
830 	static_branch_inc(&udp_encap_needed_key);
831 }
832 EXPORT_SYMBOL(udp_encap_enable);
833 
834 void udp_encap_disable(void)
835 {
836 	static_branch_dec(&udp_encap_needed_key);
837 }
838 EXPORT_SYMBOL(udp_encap_disable);
839 
840 /* Handler for tunnels with arbitrary destination ports: no socket lookup, go
841  * through error handlers in encapsulations looking for a match.
842  */
843 static int __udp4_lib_err_encap_no_sk(struct sk_buff *skb, u32 info)
844 {
845 	int i;
846 
847 	for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) {
848 		int (*handler)(struct sk_buff *skb, u32 info);
849 		const struct ip_tunnel_encap_ops *encap;
850 
851 		encap = rcu_dereference(iptun_encaps[i]);
852 		if (!encap)
853 			continue;
854 		handler = encap->err_handler;
855 		if (handler && !handler(skb, info))
856 			return 0;
857 	}
858 
859 	return -ENOENT;
860 }
861 
862 /* Try to match ICMP errors to UDP tunnels by looking up a socket without
863  * reversing source and destination port: this will match tunnels that force the
864  * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that
865  * lwtunnels might actually break this assumption by being configured with
866  * different destination ports on endpoints, in this case we won't be able to
867  * trace ICMP messages back to them.
868  *
869  * If this doesn't match any socket, probe tunnels with arbitrary destination
870  * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port
871  * we've sent packets to won't necessarily match the local destination port.
872  *
873  * Then ask the tunnel implementation to match the error against a valid
874  * association.
875  *
876  * Return an error if we can't find a match, the socket if we need further
877  * processing, zero otherwise.
878  */
879 static struct sock *__udp4_lib_err_encap(struct net *net,
880 					 const struct iphdr *iph,
881 					 struct udphdr *uh,
882 					 struct sock *sk,
883 					 struct sk_buff *skb, u32 info)
884 {
885 	int (*lookup)(struct sock *sk, struct sk_buff *skb);
886 	int network_offset, transport_offset;
887 	struct udp_sock *up;
888 
889 	network_offset = skb_network_offset(skb);
890 	transport_offset = skb_transport_offset(skb);
891 
892 	/* Network header needs to point to the outer IPv4 header inside ICMP */
893 	skb_reset_network_header(skb);
894 
895 	/* Transport header needs to point to the UDP header */
896 	skb_set_transport_header(skb, iph->ihl << 2);
897 
898 	if (sk) {
899 		up = udp_sk(sk);
900 
901 		lookup = READ_ONCE(up->encap_err_lookup);
902 		if (lookup && lookup(sk, skb))
903 			sk = NULL;
904 
905 		goto out;
906 	}
907 
908 	sk = __udp4_lib_lookup(net, iph->daddr, uh->source,
909 			       iph->saddr, uh->dest, skb->dev->ifindex, 0, NULL);
910 	if (sk) {
911 		up = udp_sk(sk);
912 
913 		lookup = READ_ONCE(up->encap_err_lookup);
914 		if (!lookup || lookup(sk, skb))
915 			sk = NULL;
916 	}
917 
918 out:
919 	if (!sk)
920 		sk = ERR_PTR(__udp4_lib_err_encap_no_sk(skb, info));
921 
922 	skb_set_transport_header(skb, transport_offset);
923 	skb_set_network_header(skb, network_offset);
924 
925 	return sk;
926 }
927 
928 static void udp_err_update_exception(struct net *net, struct sk_buff *skb,
929 				     int type, int code, u32 info)
930 {
931 	if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)
932 		ipv4_update_pmtu(skb, net, info, 0, IPPROTO_UDP);
933 	else if (type == ICMP_REDIRECT)
934 		ipv4_redirect(skb, net, 0, IPPROTO_UDP);
935 }
936 
937 /*
938  * This routine is called by the ICMP module when it gets some
939  * sort of error condition.  If err < 0 then the socket should
940  * be closed and the error returned to the user.  If err > 0
941  * it's just the icmp type << 8 | icmp code.
942  * Header points to the ip header of the error packet. We move
943  * on past this. Then (as it used to claim before adjustment)
944  * header points to the first 8 bytes of the udp header.  We need
945  * to find the appropriate port.
946  */
947 int udp_err(struct sk_buff *skb, u32 info)
948 {
949 	const struct iphdr *iph = (const struct iphdr *)skb->data;
950 	const int type = icmp_hdr(skb)->type;
951 	const int code = icmp_hdr(skb)->code;
952 	struct net *net = dev_net(skb->dev);
953 	struct inet_sock *inet;
954 	bool tunnel = false;
955 	struct udphdr *uh;
956 	struct sock *sk;
957 	int harderr;
958 	int err;
959 
960 	udp_err_update_exception(net, skb, type, code, info);
961 
962 	uh = (struct udphdr *)(skb->data + (iph->ihl << 2));
963 	sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
964 			       iph->saddr, uh->source, skb->dev->ifindex,
965 			       inet_sdif(skb), NULL);
966 
967 	if (!sk || READ_ONCE(udp_sk(sk)->encap_type)) {
968 		/* No socket for error: try tunnels before discarding */
969 		if (static_branch_unlikely(&udp_encap_needed_key)) {
970 			sk = __udp4_lib_err_encap(net, iph, uh, sk, skb, info);
971 			if (!sk)
972 				return 0;
973 		} else
974 			sk = ERR_PTR(-ENOENT);
975 
976 		if (IS_ERR(sk)) {
977 			__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
978 			return PTR_ERR(sk);
979 		}
980 
981 		tunnel = true;
982 	}
983 
984 	err = 0;
985 	harderr = 0;
986 	inet = inet_sk(sk);
987 
988 	switch (type) {
989 	default:
990 	case ICMP_TIME_EXCEEDED:
991 		err = EHOSTUNREACH;
992 		break;
993 	case ICMP_SOURCE_QUENCH:
994 		goto out;
995 	case ICMP_PARAMETERPROB:
996 		err = EPROTO;
997 		harderr = 1;
998 		break;
999 	case ICMP_DEST_UNREACH:
1000 		if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
1001 			ipv4_sk_update_pmtu(skb, sk, info);
1002 			if (READ_ONCE(inet->pmtudisc) != IP_PMTUDISC_DONT) {
1003 				err = EMSGSIZE;
1004 				harderr = 1;
1005 				break;
1006 			}
1007 			goto out;
1008 		}
1009 		err = EHOSTUNREACH;
1010 		if (code <= NR_ICMP_UNREACH) {
1011 			harderr = icmp_err_convert[code].fatal;
1012 			err = icmp_err_convert[code].errno;
1013 		}
1014 		break;
1015 	case ICMP_REDIRECT:
1016 		ipv4_sk_redirect(skb, sk);
1017 		goto out;
1018 	}
1019 
1020 	/*
1021 	 *      RFC1122: OK.  Passes ICMP errors back to application, as per
1022 	 *	4.1.3.3.
1023 	 */
1024 	if (tunnel) {
1025 		/* ...not for tunnels though: we don't have a sending socket */
1026 		if (udp_sk(sk)->encap_err_rcv)
1027 			udp_sk(sk)->encap_err_rcv(sk, skb, err, uh->dest, info,
1028 						  (u8 *)(uh+1));
1029 		goto out;
1030 	}
1031 	if (!inet_test_bit(RECVERR, sk)) {
1032 		if (!harderr || sk->sk_state != TCP_ESTABLISHED)
1033 			goto out;
1034 	} else
1035 		ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
1036 
1037 	sk->sk_err = err;
1038 	sk_error_report(sk);
1039 out:
1040 	return 0;
1041 }
1042 
1043 /*
1044  * Throw away all pending data and cancel the corking. Socket is locked.
1045  */
1046 void udp_flush_pending_frames(struct sock *sk)
1047 {
1048 	struct udp_sock *up = udp_sk(sk);
1049 
1050 	if (up->pending) {
1051 		up->len = 0;
1052 		WRITE_ONCE(up->pending, 0);
1053 		ip_flush_pending_frames(sk);
1054 	}
1055 }
1056 
1057 /**
1058  * 	udp4_hwcsum  -  handle outgoing HW checksumming
1059  * 	@skb: 	sk_buff containing the filled-in UDP header
1060  * 	        (checksum field must be zeroed out)
1061  *	@src:	source IP address
1062  *	@dst:	destination IP address
1063  */
1064 void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
1065 {
1066 	struct udphdr *uh = udp_hdr(skb);
1067 	int offset = skb_transport_offset(skb);
1068 	int len = skb->len - offset;
1069 	int hlen = len;
1070 	__wsum csum = 0;
1071 
1072 	if (!skb_has_frag_list(skb)) {
1073 		/*
1074 		 * Only one fragment on the socket.
1075 		 */
1076 		skb->csum_start = skb_transport_header(skb) - skb->head;
1077 		skb->csum_offset = offsetof(struct udphdr, check);
1078 		uh->check = ~csum_tcpudp_magic(src, dst, len,
1079 					       IPPROTO_UDP, 0);
1080 	} else {
1081 		struct sk_buff *frags;
1082 
1083 		/*
1084 		 * HW-checksum won't work as there are two or more
1085 		 * fragments on the socket so that all csums of sk_buffs
1086 		 * should be together
1087 		 */
1088 		skb_walk_frags(skb, frags) {
1089 			csum = csum_add(csum, frags->csum);
1090 			hlen -= frags->len;
1091 		}
1092 
1093 		csum = skb_checksum(skb, offset, hlen, csum);
1094 		skb->ip_summed = CHECKSUM_NONE;
1095 
1096 		uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
1097 		if (uh->check == 0)
1098 			uh->check = CSUM_MANGLED_0;
1099 	}
1100 }
1101 EXPORT_SYMBOL_GPL(udp4_hwcsum);
1102 
1103 /* Function to set UDP checksum for an IPv4 UDP packet. This is intended
1104  * for the simple case like when setting the checksum for a UDP tunnel.
1105  */
1106 void udp_set_csum(bool nocheck, struct sk_buff *skb,
1107 		  __be32 saddr, __be32 daddr, int len)
1108 {
1109 	struct udphdr *uh = udp_hdr(skb);
1110 
1111 	if (nocheck) {
1112 		uh->check = 0;
1113 	} else if (skb_is_gso(skb)) {
1114 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
1115 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) {
1116 		uh->check = 0;
1117 		uh->check = udp_v4_check(len, saddr, daddr, lco_csum(skb));
1118 		if (uh->check == 0)
1119 			uh->check = CSUM_MANGLED_0;
1120 	} else {
1121 		skb->ip_summed = CHECKSUM_PARTIAL;
1122 		skb->csum_start = skb_transport_header(skb) - skb->head;
1123 		skb->csum_offset = offsetof(struct udphdr, check);
1124 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
1125 	}
1126 }
1127 EXPORT_SYMBOL(udp_set_csum);
1128 
1129 static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4,
1130 			struct inet_cork *cork)
1131 {
1132 	struct sock *sk = skb->sk;
1133 	int offset, len, datalen;
1134 	struct udphdr *uh;
1135 	int err;
1136 
1137 	offset = skb_transport_offset(skb);
1138 	len = skb->len - offset;
1139 	datalen = len - sizeof(*uh);
1140 
1141 	/*
1142 	 * Create a UDP header
1143 	 */
1144 	uh = udp_hdr(skb);
1145 	uh->source = inet_sk(sk)->inet_sport;
1146 	uh->dest = fl4->fl4_dport;
1147 	/* Datagram length checked in udp_sendmsg. */
1148 	udp_set_len_short(uh, len);
1149 	uh->check = 0;
1150 
1151 	if (cork->gso_size) {
1152 		const int hlen = skb_network_header_len(skb) +
1153 				 sizeof(struct udphdr);
1154 
1155 		if (hlen + min(datalen, cork->gso_size) > cork->fragsize) {
1156 			kfree_skb(skb);
1157 			return -EMSGSIZE;
1158 		}
1159 		if (datalen > cork->gso_size * UDP_MAX_SEGMENTS) {
1160 			kfree_skb(skb);
1161 			return -EINVAL;
1162 		}
1163 		if (sk->sk_no_check_tx) {
1164 			kfree_skb(skb);
1165 			return -EINVAL;
1166 		}
1167 		if (dst_xfrm(skb_dst(skb))) {
1168 			kfree_skb(skb);
1169 			return -EIO;
1170 		}
1171 
1172 		if (datalen > cork->gso_size) {
1173 			skb_shinfo(skb)->gso_size = cork->gso_size;
1174 			skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4;
1175 			skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(datalen,
1176 								 cork->gso_size);
1177 
1178 			/* Don't checksum the payload, skb will get segmented */
1179 			goto csum_partial;
1180 		}
1181 	}
1182 
1183 	if (sk->sk_no_check_tx) {			 /* UDP csum off */
1184 		skb->ip_summed = CHECKSUM_NONE;
1185 		goto send;
1186 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
1187 csum_partial:
1188 		udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
1189 		goto send;
1190 	}
1191 
1192 	/* add protocol-dependent pseudo-header */
1193 	uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
1194 				      IPPROTO_UDP, udp_csum(skb));
1195 	if (uh->check == 0)
1196 		uh->check = CSUM_MANGLED_0;
1197 
1198 send:
1199 	err = ip_send_skb(sock_net(sk), skb);
1200 	if (unlikely(err)) {
1201 		if (err == -ENOBUFS &&
1202 		    !inet_test_bit(RECVERR, sk)) {
1203 			UDP_INC_STATS(sock_net(sk), UDP_MIB_SNDBUFERRORS);
1204 			err = 0;
1205 		}
1206 	} else {
1207 		UDP_INC_STATS(sock_net(sk), UDP_MIB_OUTDATAGRAMS);
1208 	}
1209 	return err;
1210 }
1211 
1212 /*
1213  * Push out all pending data as one UDP datagram. Socket is locked.
1214  */
1215 int udp_push_pending_frames(struct sock *sk)
1216 {
1217 	struct udp_sock  *up = udp_sk(sk);
1218 	struct inet_sock *inet = inet_sk(sk);
1219 	struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
1220 	struct sk_buff *skb;
1221 	int err = 0;
1222 
1223 	skb = ip_finish_skb(sk, fl4);
1224 	if (!skb)
1225 		goto out;
1226 
1227 	err = udp_send_skb(skb, fl4, &inet->cork.base);
1228 
1229 out:
1230 	up->len = 0;
1231 	WRITE_ONCE(up->pending, 0);
1232 	return err;
1233 }
1234 
1235 static int __udp_cmsg_send(struct cmsghdr *cmsg, u16 *gso_size)
1236 {
1237 	switch (cmsg->cmsg_type) {
1238 	case UDP_SEGMENT:
1239 		if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u16)))
1240 			return -EINVAL;
1241 		*gso_size = *(__u16 *)CMSG_DATA(cmsg);
1242 		return 0;
1243 	default:
1244 		return -EINVAL;
1245 	}
1246 }
1247 
1248 int udp_cmsg_send(struct sock *sk, struct msghdr *msg, u16 *gso_size)
1249 {
1250 	struct cmsghdr *cmsg;
1251 	bool need_ip = false;
1252 	int err;
1253 
1254 	for_each_cmsghdr(cmsg, msg) {
1255 		if (!CMSG_OK(msg, cmsg))
1256 			return -EINVAL;
1257 
1258 		if (cmsg->cmsg_level != SOL_UDP) {
1259 			need_ip = true;
1260 			continue;
1261 		}
1262 
1263 		err = __udp_cmsg_send(cmsg, gso_size);
1264 		if (err)
1265 			return err;
1266 	}
1267 
1268 	return need_ip;
1269 }
1270 
1271 int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1272 {
1273 	int corkreq = udp_test_bit(CORK, sk) || msg->msg_flags & MSG_MORE;
1274 	DEFINE_RAW_FLEX(struct ip_options_rcu, opt_copy, opt.__data,
1275 			IP_OPTIONS_DATA_FIXED_SIZE);
1276 	DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
1277 	int ulen = len, free = 0, connected = 0;
1278 	struct inet_sock *inet = inet_sk(sk);
1279 	struct udp_sock *up = udp_sk(sk);
1280 	__be32 daddr, faddr, saddr;
1281 	struct rtable *rt = NULL;
1282 	struct flowi4 fl4_stack;
1283 	struct ipcm_cookie ipc;
1284 	struct sk_buff *skb;
1285 	struct flowi4 *fl4;
1286 	__be16 dport;
1287 	int uc_index;
1288 	u8 scope;
1289 	int err;
1290 
1291 	if (len > 0xFFFF)
1292 		return -EMSGSIZE;
1293 
1294 	/*
1295 	 *	Check the flags.
1296 	 */
1297 
1298 	if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
1299 		return -EOPNOTSUPP;
1300 
1301 	fl4 = &inet->cork.fl.u.ip4;
1302 	if (READ_ONCE(up->pending)) {
1303 		/*
1304 		 * There are pending frames.
1305 		 * The socket lock must be held while it's corked.
1306 		 */
1307 		lock_sock(sk);
1308 		if (likely(up->pending)) {
1309 			if (unlikely(up->pending != AF_INET)) {
1310 				release_sock(sk);
1311 				return -EINVAL;
1312 			}
1313 			goto do_append_data;
1314 		}
1315 		release_sock(sk);
1316 	}
1317 	ulen += sizeof(struct udphdr);
1318 
1319 	/*
1320 	 *	Get and verify the address.
1321 	 */
1322 	if (usin) {
1323 		if (msg->msg_namelen < sizeof(*usin))
1324 			return -EINVAL;
1325 		if (usin->sin_family != AF_INET) {
1326 			if (usin->sin_family != AF_UNSPEC)
1327 				return -EAFNOSUPPORT;
1328 		}
1329 
1330 		daddr = usin->sin_addr.s_addr;
1331 		dport = usin->sin_port;
1332 		if (dport == 0)
1333 			return -EINVAL;
1334 	} else {
1335 		if (sk->sk_state != TCP_ESTABLISHED)
1336 			return -EDESTADDRREQ;
1337 		daddr = inet->inet_daddr;
1338 		dport = inet->inet_dport;
1339 		/* Open fast path for connected socket.
1340 		   Route will not be used, if at least one option is set.
1341 		 */
1342 		connected = 1;
1343 	}
1344 
1345 	ipcm_init_sk(&ipc, inet);
1346 	ipc.gso_size = READ_ONCE(up->gso_size);
1347 
1348 	if (msg->msg_controllen) {
1349 		err = udp_cmsg_send(sk, msg, &ipc.gso_size);
1350 		if (err > 0) {
1351 			err = ip_cmsg_send(sk, msg, &ipc,
1352 					   sk->sk_family == AF_INET6);
1353 			connected = 0;
1354 		}
1355 		if (unlikely(err < 0)) {
1356 			kfree(ipc.opt);
1357 			return err;
1358 		}
1359 		if (ipc.opt)
1360 			free = 1;
1361 	}
1362 	if (!ipc.opt) {
1363 		struct ip_options_rcu *inet_opt;
1364 
1365 		rcu_read_lock();
1366 		inet_opt = rcu_dereference(inet->inet_opt);
1367 		if (inet_opt) {
1368 			memcpy(opt_copy, inet_opt,
1369 			       sizeof(*inet_opt) + inet_opt->opt.optlen);
1370 			ipc.opt = opt_copy;
1371 		}
1372 		rcu_read_unlock();
1373 	}
1374 
1375 	if (cgroup_bpf_enabled(CGROUP_UDP4_SENDMSG) && !connected) {
1376 		err = BPF_CGROUP_RUN_PROG_UDP4_SENDMSG_LOCK(sk,
1377 					    (struct sockaddr *)usin,
1378 					    &msg->msg_namelen,
1379 					    &ipc.addr);
1380 		if (err)
1381 			goto out_free;
1382 		if (usin) {
1383 			if (usin->sin_port == 0) {
1384 				/* BPF program set invalid port. Reject it. */
1385 				err = -EINVAL;
1386 				goto out_free;
1387 			}
1388 			daddr = usin->sin_addr.s_addr;
1389 			dport = usin->sin_port;
1390 		}
1391 	}
1392 
1393 	saddr = ipc.addr;
1394 	ipc.addr = faddr = daddr;
1395 
1396 	if (ipc.opt && ipc.opt->opt.srr) {
1397 		if (!daddr) {
1398 			err = -EINVAL;
1399 			goto out_free;
1400 		}
1401 		faddr = ipc.opt->opt.faddr;
1402 		connected = 0;
1403 	}
1404 	scope = ip_sendmsg_scope(inet, &ipc, msg);
1405 	if (scope == RT_SCOPE_LINK)
1406 		connected = 0;
1407 
1408 	uc_index = READ_ONCE(inet->uc_index);
1409 	if (ipv4_is_multicast(daddr)) {
1410 		if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif))
1411 			ipc.oif = READ_ONCE(inet->mc_index);
1412 		if (!saddr)
1413 			saddr = READ_ONCE(inet->mc_addr);
1414 		connected = 0;
1415 	} else if (!ipc.oif) {
1416 		ipc.oif = uc_index;
1417 	} else if (ipv4_is_lbcast(daddr) && uc_index) {
1418 		/* oif is set, packet is to local broadcast and
1419 		 * uc_index is set. oif is most likely set
1420 		 * by sk_bound_dev_if. If uc_index != oif check if the
1421 		 * oif is an L3 master and uc_index is an L3 slave.
1422 		 * If so, we want to allow the send using the uc_index.
1423 		 */
1424 		if (ipc.oif != uc_index &&
1425 		    ipc.oif == l3mdev_master_ifindex_by_index(sock_net(sk),
1426 							      uc_index)) {
1427 			ipc.oif = uc_index;
1428 		}
1429 	}
1430 
1431 	if (connected)
1432 		rt = dst_rtable(sk_dst_check(sk, 0));
1433 
1434 	if (!rt) {
1435 		struct net *net = sock_net(sk);
1436 		__u8 flow_flags = inet_sk_flowi_flags(sk);
1437 
1438 		fl4 = &fl4_stack;
1439 
1440 		flowi4_init_output(fl4, ipc.oif, ipc.sockc.mark,
1441 				   ipc.tos & INET_DSCP_MASK, scope,
1442 				   IPPROTO_UDP, flow_flags, faddr, saddr,
1443 				   dport, inet->inet_sport,
1444 				   sk_uid(sk));
1445 
1446 		security_sk_classify_flow(sk, flowi4_to_flowi_common(fl4));
1447 		rt = ip_route_output_flow(net, fl4, sk);
1448 		if (IS_ERR(rt)) {
1449 			err = PTR_ERR(rt);
1450 			rt = NULL;
1451 			if (err == -ENETUNREACH)
1452 				IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
1453 			goto out;
1454 		}
1455 
1456 		err = -EACCES;
1457 		if ((rt->rt_flags & RTCF_BROADCAST) &&
1458 		    !sock_flag(sk, SOCK_BROADCAST))
1459 			goto out;
1460 		if (connected)
1461 			sk_dst_set(sk, dst_clone(&rt->dst));
1462 	}
1463 
1464 	if (msg->msg_flags&MSG_CONFIRM)
1465 		goto do_confirm;
1466 back_from_confirm:
1467 
1468 	saddr = fl4->saddr;
1469 	if (!ipc.addr)
1470 		daddr = ipc.addr = fl4->daddr;
1471 
1472 	/* Lockless fast path for the non-corking case. */
1473 	if (!corkreq) {
1474 		struct inet_cork cork;
1475 
1476 		skb = ip_make_skb(sk, fl4, ip_generic_getfrag, msg, ulen,
1477 				  sizeof(struct udphdr), &ipc, &rt,
1478 				  &cork, msg->msg_flags);
1479 		err = PTR_ERR(skb);
1480 		if (!IS_ERR_OR_NULL(skb))
1481 			err = udp_send_skb(skb, fl4, &cork);
1482 		goto out;
1483 	}
1484 
1485 	lock_sock(sk);
1486 	if (unlikely(up->pending)) {
1487 		/* The socket is already corked while preparing it. */
1488 		/* ... which is an evident application bug. --ANK */
1489 		release_sock(sk);
1490 
1491 		net_dbg_ratelimited("socket already corked\n");
1492 		err = -EINVAL;
1493 		goto out;
1494 	}
1495 	/*
1496 	 *	Now cork the socket to pend data.
1497 	 */
1498 	fl4 = &inet->cork.fl.u.ip4;
1499 	fl4->daddr = daddr;
1500 	fl4->saddr = saddr;
1501 	fl4->fl4_dport = dport;
1502 	fl4->fl4_sport = inet->inet_sport;
1503 	WRITE_ONCE(up->pending, AF_INET);
1504 
1505 do_append_data:
1506 	up->len += ulen;
1507 	err = ip_append_data(sk, fl4, ip_generic_getfrag, msg, ulen,
1508 			     sizeof(struct udphdr), &ipc, &rt,
1509 			     corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
1510 	if (err)
1511 		udp_flush_pending_frames(sk);
1512 	else if (!corkreq)
1513 		err = udp_push_pending_frames(sk);
1514 	else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
1515 		WRITE_ONCE(up->pending, 0);
1516 	release_sock(sk);
1517 
1518 out:
1519 	ip_rt_put(rt);
1520 out_free:
1521 	if (free)
1522 		kfree(ipc.opt);
1523 	if (!err)
1524 		return len;
1525 	/*
1526 	 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space.  Reporting
1527 	 * ENOBUFS might not be good (it's not tunable per se), but otherwise
1528 	 * we don't have a good statistic (IpOutDiscards but it can be too many
1529 	 * things).  We could add another new stat but at least for now that
1530 	 * seems like overkill.
1531 	 */
1532 	if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags))
1533 		UDP_INC_STATS(sock_net(sk), UDP_MIB_SNDBUFERRORS);
1534 
1535 	return err;
1536 
1537 do_confirm:
1538 	if (msg->msg_flags & MSG_PROBE)
1539 		dst_confirm_neigh(&rt->dst, &fl4->daddr);
1540 	if (!(msg->msg_flags&MSG_PROBE) || len)
1541 		goto back_from_confirm;
1542 	err = 0;
1543 	goto out;
1544 }
1545 EXPORT_SYMBOL(udp_sendmsg);
1546 
1547 void udp_splice_eof(struct socket *sock)
1548 {
1549 	struct sock *sk = sock->sk;
1550 	struct udp_sock *up = udp_sk(sk);
1551 
1552 	if (!READ_ONCE(up->pending) || udp_test_bit(CORK, sk))
1553 		return;
1554 
1555 	lock_sock(sk);
1556 	if (up->pending && !udp_test_bit(CORK, sk))
1557 		udp_push_pending_frames(sk);
1558 	release_sock(sk);
1559 }
1560 
1561 #define UDP_SKB_IS_STATELESS 0x80000000
1562 
1563 /* all head states (dst, sk, nf conntrack) except skb extensions are
1564  * cleared by udp_rcv().
1565  *
1566  * We need to preserve secpath, if present, to eventually process
1567  * IP_CMSG_PASSSEC at recvmsg() time.
1568  *
1569  * Other extensions can be cleared.
1570  */
1571 static bool udp_try_make_stateless(struct sk_buff *skb)
1572 {
1573 	if (!skb_has_extensions(skb))
1574 		return true;
1575 
1576 	if (!secpath_exists(skb)) {
1577 		skb_ext_reset(skb);
1578 		return true;
1579 	}
1580 
1581 	return false;
1582 }
1583 
1584 static void udp_set_dev_scratch(struct sk_buff *skb)
1585 {
1586 	struct udp_dev_scratch *scratch = udp_skb_scratch(skb);
1587 
1588 	BUILD_BUG_ON(sizeof(struct udp_dev_scratch) > sizeof(long));
1589 	scratch->_tsize_state = skb->truesize;
1590 #if BITS_PER_LONG == 64
1591 	scratch->len = skb->len;
1592 	scratch->csum_unnecessary = !!skb_csum_unnecessary(skb);
1593 	scratch->is_linear = !skb_is_nonlinear(skb);
1594 #endif
1595 	if (udp_try_make_stateless(skb))
1596 		scratch->_tsize_state |= UDP_SKB_IS_STATELESS;
1597 }
1598 
1599 static void udp_skb_csum_unnecessary_set(struct sk_buff *skb)
1600 {
1601 	/* We come here after udp_lib_checksum_complete() returned 0.
1602 	 * This means that __skb_checksum_complete() might have
1603 	 * set skb->csum_valid to 1.
1604 	 * On 64bit platforms, we can set csum_unnecessary
1605 	 * to true, but only if the skb is not shared.
1606 	 */
1607 #if BITS_PER_LONG == 64
1608 	if (!skb_shared(skb))
1609 		udp_skb_scratch(skb)->csum_unnecessary = true;
1610 #endif
1611 }
1612 
1613 static int udp_skb_truesize(struct sk_buff *skb)
1614 {
1615 	return udp_skb_scratch(skb)->_tsize_state & ~UDP_SKB_IS_STATELESS;
1616 }
1617 
1618 static bool udp_skb_has_head_state(struct sk_buff *skb)
1619 {
1620 	return !(udp_skb_scratch(skb)->_tsize_state & UDP_SKB_IS_STATELESS);
1621 }
1622 
1623 /* fully reclaim rmem/fwd memory allocated for skb */
1624 static void udp_rmem_release(struct sock *sk, unsigned int size,
1625 			     int partial, bool rx_queue_lock_held)
1626 {
1627 	struct udp_sock *up = udp_sk(sk);
1628 	struct sk_buff_head *sk_queue;
1629 	unsigned int amt;
1630 
1631 	if (likely(partial)) {
1632 		up->forward_deficit += size;
1633 		size = up->forward_deficit;
1634 		if (size < READ_ONCE(up->forward_threshold) &&
1635 		    !skb_queue_empty(&up->reader_queue))
1636 			return;
1637 	} else {
1638 		size += up->forward_deficit;
1639 	}
1640 	up->forward_deficit = 0;
1641 
1642 	/* acquire the sk_receive_queue for fwd allocated memory scheduling,
1643 	 * if the called don't held it already
1644 	 */
1645 	sk_queue = &sk->sk_receive_queue;
1646 	if (!rx_queue_lock_held)
1647 		spin_lock(&sk_queue->lock);
1648 
1649 	amt = (size + sk->sk_forward_alloc - partial) & ~(PAGE_SIZE - 1);
1650 	sk_forward_alloc_add(sk, size - amt);
1651 
1652 	if (amt)
1653 		__sk_mem_reduce_allocated(sk, amt >> PAGE_SHIFT);
1654 
1655 	atomic_sub(size, &sk->sk_rmem_alloc);
1656 
1657 	/* this can save us from acquiring the rx queue lock on next receive */
1658 	skb_queue_splice_tail_init(sk_queue, &up->reader_queue);
1659 
1660 	if (!rx_queue_lock_held)
1661 		spin_unlock(&sk_queue->lock);
1662 }
1663 
1664 /* Note: called with reader_queue.lock held.
1665  * Instead of using skb->truesize here, find a copy of it in skb->dev_scratch
1666  * This avoids a cache line miss while receive_queue lock is held.
1667  * Look at __udp_enqueue_schedule_skb() to find where this copy is done.
1668  */
1669 void udp_skb_destructor(struct sock *sk, struct sk_buff *skb)
1670 {
1671 	prefetch(&skb->data);
1672 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, false);
1673 }
1674 
1675 /* as above, but the caller held the rx queue lock, too */
1676 static void udp_skb_dtor_locked(struct sock *sk, struct sk_buff *skb)
1677 {
1678 	prefetch(&skb->data);
1679 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, true);
1680 }
1681 
1682 static int udp_rmem_schedule(struct sock *sk, int size)
1683 {
1684 	int delta;
1685 
1686 	delta = size - sk->sk_forward_alloc;
1687 	if (delta > 0 && !__sk_mem_schedule(sk, delta, SK_MEM_RECV))
1688 		return -ENOBUFS;
1689 
1690 	return 0;
1691 }
1692 
1693 int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb)
1694 {
1695 	struct sk_buff_head *list = &sk->sk_receive_queue;
1696 	struct udp_prod_queue *udp_prod_queue;
1697 	struct sk_buff *next, *to_drop = NULL;
1698 	struct llist_node *ll_list;
1699 	unsigned int rmem, rcvbuf;
1700 	int size, err = -ENOMEM;
1701 	int total_size = 0;
1702 	int q_size = 0;
1703 	int dropcount;
1704 	int nb = 0;
1705 
1706 	rmem = atomic_read(&sk->sk_rmem_alloc);
1707 	rcvbuf = READ_ONCE(sk->sk_rcvbuf);
1708 	size = skb->truesize;
1709 
1710 	udp_prod_queue = &udp_sk(sk)->udp_prod_queue[numa_node_id()];
1711 
1712 	rmem += atomic_read(&udp_prod_queue->rmem_alloc);
1713 
1714 	/* Immediately drop when the receive queue is full.
1715 	 * Cast to unsigned int performs the boundary check for INT_MAX.
1716 	 */
1717 	if (rmem + size > rcvbuf) {
1718 		if (rcvbuf > INT_MAX >> 1)
1719 			goto drop;
1720 
1721 		/* Accept the packet if queue is empty. */
1722 		if (rmem)
1723 			goto drop;
1724 	}
1725 
1726 	/* Under mem pressure, it might be helpful to help udp_recvmsg()
1727 	 * having linear skbs :
1728 	 * - Reduce memory overhead and thus increase receive queue capacity
1729 	 * - Less cache line misses at copyout() time
1730 	 * - Less work at consume_skb() (less alien page frag freeing)
1731 	 */
1732 	if (rmem > (rcvbuf >> 1)) {
1733 		skb_condense(skb);
1734 		size = skb->truesize;
1735 	}
1736 
1737 	udp_set_dev_scratch(skb);
1738 
1739 	atomic_add(size, &udp_prod_queue->rmem_alloc);
1740 
1741 	if (!llist_add(&skb->ll_node, &udp_prod_queue->ll_root))
1742 		return 0;
1743 
1744 	dropcount = sock_flag(sk, SOCK_RXQ_OVFL) ? sk_drops_read(sk) : 0;
1745 
1746 	spin_lock(&list->lock);
1747 
1748 	ll_list = llist_del_all(&udp_prod_queue->ll_root);
1749 
1750 	ll_list = llist_reverse_order(ll_list);
1751 
1752 	llist_for_each_entry_safe(skb, next, ll_list, ll_node) {
1753 		size = udp_skb_truesize(skb);
1754 		total_size += size;
1755 		err = udp_rmem_schedule(sk, size);
1756 		if (unlikely(err)) {
1757 			/*  Free the skbs outside of locked section. */
1758 			skb->next = to_drop;
1759 			to_drop = skb;
1760 			continue;
1761 		}
1762 
1763 		q_size += size;
1764 		sk_forward_alloc_add(sk, -size);
1765 
1766 		/* no need to setup a destructor, we will explicitly release the
1767 		 * forward allocated memory on dequeue
1768 		 */
1769 		SOCK_SKB_CB(skb)->dropcount = dropcount;
1770 		nb++;
1771 		__skb_queue_tail(list, skb);
1772 	}
1773 
1774 	atomic_add(q_size, &sk->sk_rmem_alloc);
1775 
1776 	spin_unlock(&list->lock);
1777 
1778 	if (!sock_flag(sk, SOCK_DEAD)) {
1779 		/* Multiple threads might be blocked in recvmsg(),
1780 		 * using prepare_to_wait_exclusive().
1781 		 */
1782 		while (nb) {
1783 			INDIRECT_CALL_1(READ_ONCE(sk->sk_data_ready),
1784 					sock_def_readable, sk);
1785 			nb--;
1786 		}
1787 	}
1788 
1789 	if (unlikely(to_drop)) {
1790 		int err_ipv4 = 0;
1791 		int err_ipv6 = 0;
1792 
1793 		for (nb = 0; to_drop != NULL; nb++) {
1794 			skb = to_drop;
1795 			if (skb->protocol == htons(ETH_P_IP))
1796 				err_ipv4++;
1797 			else
1798 				err_ipv6++;
1799 			to_drop = skb->next;
1800 			skb_mark_not_on_list(skb);
1801 			sk_skb_reason_drop(sk, skb, SKB_DROP_REASON_PROTO_MEM);
1802 		}
1803 		numa_drop_add(&udp_sk(sk)->drop_counters, nb);
1804 		if (err_ipv4 > 0) {
1805 			SNMP_ADD_STATS(__UDPX_MIB(sk, true), UDP_MIB_MEMERRORS,
1806 				       err_ipv4);
1807 			SNMP_ADD_STATS(__UDPX_MIB(sk, true), UDP_MIB_INERRORS,
1808 				       err_ipv4);
1809 		}
1810 		if (err_ipv6 > 0) {
1811 			SNMP_ADD_STATS(__UDPX_MIB(sk, false), UDP_MIB_MEMERRORS,
1812 				       err_ipv6);
1813 			SNMP_ADD_STATS(__UDPX_MIB(sk, false), UDP_MIB_INERRORS,
1814 				       err_ipv6);
1815 		}
1816 	}
1817 
1818 	atomic_sub(total_size, &udp_prod_queue->rmem_alloc);
1819 
1820 	return 0;
1821 
1822 drop:
1823 	udp_drops_inc(sk);
1824 	return err;
1825 }
1826 
1827 void udp_destruct_common(struct sock *sk)
1828 {
1829 	/* reclaim completely the forward allocated memory */
1830 	struct udp_sock *up = udp_sk(sk);
1831 	unsigned int total = 0;
1832 	struct sk_buff *skb;
1833 
1834 	skb_queue_splice_tail_init(&sk->sk_receive_queue, &up->reader_queue);
1835 	while ((skb = __skb_dequeue(&up->reader_queue)) != NULL) {
1836 		total += skb->truesize;
1837 		kfree_skb(skb);
1838 	}
1839 	udp_rmem_release(sk, total, 0, true);
1840 	kfree(up->udp_prod_queue);
1841 }
1842 
1843 static void udp_destruct_sock(struct sock *sk)
1844 {
1845 	udp_destruct_common(sk);
1846 	inet_sock_destruct(sk);
1847 }
1848 
1849 static int udp_init_sock(struct sock *sk)
1850 {
1851 	int res = udp_lib_init_sock(sk);
1852 
1853 	sk->sk_destruct = udp_destruct_sock;
1854 	set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
1855 	return res;
1856 }
1857 
1858 void skb_consume_udp(struct sock *sk, struct sk_buff *skb, int len)
1859 {
1860 	if (unlikely(READ_ONCE(udp_sk(sk)->peeking_with_offset)))
1861 		sk_peek_offset_bwd(sk, len);
1862 
1863 	if (!skb_shared(skb)) {
1864 		skb_orphan(skb);
1865 		skb_attempt_defer_free(skb);
1866 		return;
1867 	}
1868 
1869 	if (!skb_unref(skb))
1870 		return;
1871 
1872 	/* In the more common cases we cleared the head states previously,
1873 	 * see __udp_queue_rcv_skb().
1874 	 */
1875 	if (unlikely(udp_skb_has_head_state(skb)))
1876 		skb_release_head_state(skb);
1877 	__consume_stateless_skb(skb);
1878 }
1879 
1880 static struct sk_buff *__first_packet_length(struct sock *sk,
1881 					     struct sk_buff_head *rcvq,
1882 					     unsigned int *total)
1883 {
1884 	struct sk_buff *skb;
1885 
1886 	while ((skb = skb_peek(rcvq)) != NULL) {
1887 		if (udp_lib_checksum_complete(skb)) {
1888 			struct net *net = sock_net(sk);
1889 
1890 			__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS);
1891 			__UDP_INC_STATS(net, UDP_MIB_INERRORS);
1892 			udp_drops_inc(sk);
1893 			__skb_unlink(skb, rcvq);
1894 			*total += skb->truesize;
1895 			kfree_skb_reason(skb, SKB_DROP_REASON_UDP_CSUM);
1896 		} else {
1897 			udp_skb_csum_unnecessary_set(skb);
1898 			break;
1899 		}
1900 	}
1901 	return skb;
1902 }
1903 
1904 /**
1905  *	first_packet_length	- return length of first packet in receive queue
1906  *	@sk: socket
1907  *
1908  *	Drops all bad checksum frames, until a valid one is found.
1909  *	Returns the length of found skb, or -1 if none is found.
1910  */
1911 static int first_packet_length(struct sock *sk)
1912 {
1913 	struct sk_buff_head *rcvq = &udp_sk(sk)->reader_queue;
1914 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
1915 	unsigned int total = 0;
1916 	struct sk_buff *skb;
1917 	int res;
1918 
1919 	spin_lock_bh(&rcvq->lock);
1920 	skb = __first_packet_length(sk, rcvq, &total);
1921 	if (!skb && !skb_queue_empty_lockless(sk_queue)) {
1922 		spin_lock(&sk_queue->lock);
1923 		skb_queue_splice_tail_init(sk_queue, rcvq);
1924 		spin_unlock(&sk_queue->lock);
1925 
1926 		skb = __first_packet_length(sk, rcvq, &total);
1927 	}
1928 	res = skb ? skb->len : -1;
1929 	if (total)
1930 		udp_rmem_release(sk, total, 1, false);
1931 	spin_unlock_bh(&rcvq->lock);
1932 	return res;
1933 }
1934 
1935 /*
1936  *	IOCTL requests applicable to the UDP protocol
1937  */
1938 
1939 int udp_ioctl(struct sock *sk, int cmd, int *karg)
1940 {
1941 	switch (cmd) {
1942 	case SIOCOUTQ:
1943 	{
1944 		*karg = sk_wmem_alloc_get(sk);
1945 		return 0;
1946 	}
1947 
1948 	case SIOCINQ:
1949 	{
1950 		*karg = max_t(int, 0, first_packet_length(sk));
1951 		return 0;
1952 	}
1953 
1954 	default:
1955 		return -ENOIOCTLCMD;
1956 	}
1957 
1958 	return 0;
1959 }
1960 
1961 struct sk_buff *__skb_recv_udp(struct sock *sk, unsigned int flags,
1962 			       int *off, int *err)
1963 {
1964 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
1965 	struct sk_buff_head *queue;
1966 	struct sk_buff *last;
1967 	long timeo;
1968 	int error;
1969 
1970 	queue = &udp_sk(sk)->reader_queue;
1971 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1972 	do {
1973 		struct sk_buff *skb;
1974 
1975 		error = sock_error(sk);
1976 		if (error)
1977 			break;
1978 
1979 		error = -EAGAIN;
1980 		do {
1981 			spin_lock_bh(&queue->lock);
1982 			skb = __skb_try_recv_from_queue(queue, flags, off, err,
1983 							&last);
1984 			if (skb) {
1985 				if (!(flags & MSG_PEEK))
1986 					udp_skb_destructor(sk, skb);
1987 				spin_unlock_bh(&queue->lock);
1988 				return skb;
1989 			}
1990 
1991 			if (skb_queue_empty_lockless(sk_queue)) {
1992 				spin_unlock_bh(&queue->lock);
1993 				goto busy_check;
1994 			}
1995 
1996 			/* refill the reader queue and walk it again
1997 			 * keep both queues locked to avoid re-acquiring
1998 			 * the sk_receive_queue lock if fwd memory scheduling
1999 			 * is needed.
2000 			 */
2001 			spin_lock(&sk_queue->lock);
2002 			skb_queue_splice_tail_init(sk_queue, queue);
2003 
2004 			skb = __skb_try_recv_from_queue(queue, flags, off, err,
2005 							&last);
2006 			if (skb && !(flags & MSG_PEEK))
2007 				udp_skb_dtor_locked(sk, skb);
2008 			spin_unlock(&sk_queue->lock);
2009 			spin_unlock_bh(&queue->lock);
2010 			if (skb)
2011 				return skb;
2012 
2013 busy_check:
2014 			if (!sk_can_busy_loop(sk))
2015 				break;
2016 
2017 			sk_busy_loop(sk, flags & MSG_DONTWAIT);
2018 		} while (!skb_queue_empty_lockless(sk_queue));
2019 
2020 		/* sk_queue is empty, reader_queue may contain peeked packets */
2021 	} while (timeo &&
2022 		 !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,
2023 					      &error, &timeo,
2024 					      (struct sk_buff *)sk_queue));
2025 
2026 	*err = error;
2027 	return NULL;
2028 }
2029 EXPORT_SYMBOL(__skb_recv_udp);
2030 
2031 int udp_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
2032 {
2033 	struct sk_buff *skb;
2034 	int err;
2035 
2036 try_again:
2037 	skb = skb_recv_udp(sk, MSG_DONTWAIT, &err);
2038 	if (!skb)
2039 		return err;
2040 
2041 	if (udp_lib_checksum_complete(skb)) {
2042 		struct net *net = sock_net(sk);
2043 
2044 		__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS);
2045 		__UDP_INC_STATS(net, UDP_MIB_INERRORS);
2046 		udp_drops_inc(sk);
2047 		kfree_skb_reason(skb, SKB_DROP_REASON_UDP_CSUM);
2048 		goto try_again;
2049 	}
2050 
2051 	WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk));
2052 
2053 	/*
2054 	 * skb->dev still aliases the UDP rx dev_scratch (its charge was freed
2055 	 * on dequeue above); a sockmap verdict program may deref it via
2056 	 * bpf_sk_lookup_*(), so clear it -> bpf_skc_lookup() uses skb->sk
2057 	 */
2058 	skb->dev = NULL;
2059 
2060 	return recv_actor(sk, skb);
2061 }
2062 
2063 /*
2064  * 	This should be easy, if there is something there we
2065  * 	return it, otherwise we block.
2066  */
2067 
2068 INDIRECT_CALLABLE_SCOPE
2069 int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags)
2070 {
2071 	DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
2072 	int off, err, peeking = flags & MSG_PEEK;
2073 	struct inet_sock *inet = inet_sk(sk);
2074 	struct net *net = sock_net(sk);
2075 	bool checksum_valid = false;
2076 	unsigned int ulen, copied;
2077 	struct sk_buff *skb;
2078 
2079 	if (flags & MSG_ERRQUEUE)
2080 		return ip_recv_error(sk, msg, len);
2081 
2082 try_again:
2083 	off = sk_peek_offset(sk, flags);
2084 	skb = __skb_recv_udp(sk, flags, &off, &err);
2085 	if (!skb)
2086 		return err;
2087 
2088 	ulen = udp_skb_len(skb);
2089 	copied = len;
2090 	if (copied > ulen - off)
2091 		copied = ulen - off;
2092 	else if (copied < ulen)
2093 		msg->msg_flags |= MSG_TRUNC;
2094 
2095 	/* If checksum is needed at all, try to do it while copying the
2096 	 * data.  If the data is truncated, do it before the copy.
2097 	 */
2098 	if (copied < ulen || peeking) {
2099 		checksum_valid = udp_skb_csum_unnecessary(skb) ||
2100 				!__udp_lib_checksum_complete(skb);
2101 		if (!checksum_valid)
2102 			goto csum_copy_err;
2103 	}
2104 
2105 	if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
2106 		if (udp_skb_is_linear(skb))
2107 			err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
2108 		else
2109 			err = skb_copy_datagram_msg(skb, off, msg, copied);
2110 	} else {
2111 		err = skb_copy_and_csum_datagram_msg(skb, off, msg);
2112 
2113 		if (err == -EINVAL)
2114 			goto csum_copy_err;
2115 	}
2116 
2117 	if (unlikely(err)) {
2118 		if (!peeking) {
2119 			udp_drops_inc(sk);
2120 			UDP_INC_STATS(net, UDP_MIB_INERRORS);
2121 		}
2122 		kfree_skb(skb);
2123 		return err;
2124 	}
2125 
2126 	if (!peeking)
2127 		UDP_INC_STATS(net, UDP_MIB_INDATAGRAMS);
2128 
2129 	sock_recv_cmsgs(msg, sk, skb);
2130 
2131 	/* Copy the address. */
2132 	if (sin) {
2133 		sin->sin_family = AF_INET;
2134 		sin->sin_port = udp_hdr(skb)->source;
2135 		sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
2136 		memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
2137 		msg->msg_namelen = sizeof(*sin);
2138 
2139 		BPF_CGROUP_RUN_PROG_UDP4_RECVMSG_LOCK(sk,
2140 						      (struct sockaddr *)sin,
2141 						      &msg->msg_namelen);
2142 	}
2143 
2144 	if (udp_test_bit(GRO_ENABLED, sk))
2145 		udp_cmsg_recv(msg, sk, skb);
2146 
2147 	if (inet_cmsg_flags(inet))
2148 		ip_cmsg_recv_offset(msg, sk, skb, sizeof(struct udphdr), off);
2149 
2150 	err = copied;
2151 	if (flags & MSG_TRUNC)
2152 		err = ulen;
2153 
2154 	skb_consume_udp(sk, skb, peeking ? -err : err);
2155 	return err;
2156 
2157 csum_copy_err:
2158 	if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags,
2159 				 udp_skb_destructor)) {
2160 		UDP_INC_STATS(net, UDP_MIB_CSUMERRORS);
2161 		UDP_INC_STATS(net, UDP_MIB_INERRORS);
2162 	}
2163 	kfree_skb_reason(skb, SKB_DROP_REASON_UDP_CSUM);
2164 
2165 	/* starting over for a new packet, but check if we need to yield */
2166 	cond_resched();
2167 	msg->msg_flags &= ~MSG_TRUNC;
2168 	goto try_again;
2169 }
2170 
2171 int udp_pre_connect(struct sock *sk, struct sockaddr_unsized *uaddr,
2172 		    int addr_len)
2173 {
2174 	/* This check is replicated from __ip4_datagram_connect() and
2175 	 * intended to prevent BPF program called below from accessing bytes
2176 	 * that are out of the bound specified by user in addr_len.
2177 	 */
2178 	if (addr_len < sizeof(struct sockaddr_in))
2179 		return -EINVAL;
2180 
2181 	return BPF_CGROUP_RUN_PROG_INET4_CONNECT_LOCK(sk, uaddr, &addr_len);
2182 }
2183 
2184 static int udp_connect(struct sock *sk, struct sockaddr_unsized *uaddr,
2185 		       int addr_len)
2186 {
2187 	int res;
2188 
2189 	lock_sock(sk);
2190 	res = __ip4_datagram_connect(sk, uaddr, addr_len);
2191 	if (!res)
2192 		udp4_hash4(sk);
2193 	release_sock(sk);
2194 	return res;
2195 }
2196 
2197 int __udp_disconnect(struct sock *sk, int flags)
2198 {
2199 	struct inet_sock *inet = inet_sk(sk);
2200 	/*
2201 	 *	1003.1g - break association.
2202 	 */
2203 
2204 	sk->sk_state = TCP_CLOSE;
2205 	WRITE_ONCE(inet->inet_daddr, 0);
2206 	inet->inet_dport = 0;
2207 	sock_rps_reset_rxhash(sk);
2208 	WRITE_ONCE(sk->sk_bound_dev_if, 0);
2209 	if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) {
2210 		inet_reset_saddr(sk);
2211 		if (sk->sk_prot->rehash &&
2212 		    (sk->sk_userlocks & SOCK_BINDPORT_LOCK))
2213 			sk->sk_prot->rehash(sk);
2214 	}
2215 
2216 	if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
2217 		sk->sk_prot->unhash(sk);
2218 		inet->inet_sport = 0;
2219 	}
2220 	sk_dst_reset(sk);
2221 	return 0;
2222 }
2223 EXPORT_SYMBOL(__udp_disconnect);
2224 
2225 /* __udp_disconnect() takes a socket out of the 4-tuple hash table only via
2226  * ->rehash() or ->unhash(), and neither runs for a socket bound to a
2227  * specific address and port. Remove it here, before its peer is cleared.
2228  */
2229 static void udp_unhash4_on_disconnect(struct sock *sk)
2230 {
2231 	struct net *net = sock_net(sk);
2232 	struct udp_table *udptable;
2233 	struct udp_hslot *hslot;
2234 
2235 	if (!udp_hashed4(sk))
2236 		return;
2237 
2238 	udptable = net->ipv4.udp_table;
2239 	hslot = udp_hashslot(udptable, net, udp_sk(sk)->udp_port_hash);
2240 
2241 	spin_lock_bh(&hslot->lock);
2242 	udp_unhash4(udptable, sk);
2243 	spin_unlock_bh(&hslot->lock);
2244 }
2245 
2246 int udp_disconnect(struct sock *sk, int flags)
2247 {
2248 	lock_sock(sk);
2249 	udp_unhash4_on_disconnect(sk);
2250 	__udp_disconnect(sk, flags);
2251 	release_sock(sk);
2252 	return 0;
2253 }
2254 
2255 void udp_lib_unhash(struct sock *sk)
2256 {
2257 	if (sk_hashed(sk)) {
2258 		struct udp_hslot *hslot, *hslot2;
2259 		struct net *net = sock_net(sk);
2260 		struct udp_table *udptable;
2261 
2262 		sock_rps_delete_flow(sk);
2263 		udptable = net->ipv4.udp_table;
2264 		hslot  = udp_hashslot(udptable, net, udp_sk(sk)->udp_port_hash);
2265 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
2266 
2267 		spin_lock_bh(&hslot->lock);
2268 		if (rcu_access_pointer(sk->sk_reuseport_cb))
2269 			reuseport_detach_sock(sk);
2270 		if (sk_del_node_init_rcu(sk)) {
2271 			hslot->count--;
2272 			inet_sk(sk)->inet_num = 0;
2273 			sock_prot_inuse_add(net, sk->sk_prot, -1);
2274 
2275 			spin_lock(&hslot2->lock);
2276 			hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
2277 			hslot2->count--;
2278 			spin_unlock(&hslot2->lock);
2279 
2280 			udp_unhash4(udptable, sk);
2281 		}
2282 		spin_unlock_bh(&hslot->lock);
2283 	}
2284 }
2285 
2286 /*
2287  * inet_rcv_saddr was changed, we must rehash secondary hash
2288  */
2289 void udp_lib_rehash(struct sock *sk, u16 newhash, u16 newhash4)
2290 {
2291 	if (sk_hashed(sk)) {
2292 		struct udp_hslot *hslot, *hslot2, *nhslot2;
2293 		struct net *net = sock_net(sk);
2294 		struct udp_table *udptable;
2295 
2296 		udptable = net->ipv4.udp_table;
2297 		hslot = udp_hashslot(udptable, net, udp_sk(sk)->udp_port_hash);
2298 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
2299 		nhslot2 = udp_hashslot2(udptable, newhash);
2300 
2301 		if (hslot2 != nhslot2 ||
2302 		    rcu_access_pointer(sk->sk_reuseport_cb)) {
2303 			/* we must lock primary chain too */
2304 			spin_lock_bh(&hslot->lock);
2305 			if (rcu_access_pointer(sk->sk_reuseport_cb))
2306 				reuseport_detach_sock(sk);
2307 
2308 			if (hslot2 != nhslot2) {
2309 				spin_lock(&hslot2->lock);
2310 				hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
2311 				hslot2->count--;
2312 				spin_unlock(&hslot2->lock);
2313 
2314 				spin_lock(&nhslot2->lock);
2315 				hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
2316 							 &nhslot2->head);
2317 				nhslot2->count++;
2318 				spin_unlock(&nhslot2->lock);
2319 			}
2320 
2321 			spin_unlock_bh(&hslot->lock);
2322 		}
2323 
2324 		/* Now process hash4 if necessary:
2325 		 * (1) update hslot4;
2326 		 * (2) update hslot2->hash4_cnt.
2327 		 * Note that hslot2/hslot4 should be checked separately, as
2328 		 * either of them may change with the other unchanged.
2329 		 */
2330 		if (udp_hashed4(sk)) {
2331 			spin_lock_bh(&hslot->lock);
2332 
2333 			if (inet_rcv_saddr_any(sk)) {
2334 				udp_unhash4(udptable, sk);
2335 			} else {
2336 				udp_rehash4(udptable, sk, newhash4);
2337 				if (hslot2 != nhslot2) {
2338 					spin_lock(&hslot2->lock);
2339 					udp_hash4_dec(hslot2);
2340 					spin_unlock(&hslot2->lock);
2341 
2342 					spin_lock(&nhslot2->lock);
2343 					udp_hash4_inc(nhslot2);
2344 					spin_unlock(&nhslot2->lock);
2345 				}
2346 			}
2347 
2348 			spin_unlock_bh(&hslot->lock);
2349 		}
2350 
2351 		udp_sk(sk)->udp_portaddr_hash = newhash;
2352 	}
2353 }
2354 
2355 static void udp_v4_rehash(struct sock *sk)
2356 {
2357 	u16 new_hash = ipv4_portaddr_hash(sock_net(sk),
2358 					  inet_sk(sk)->inet_rcv_saddr,
2359 					  inet_sk(sk)->inet_num);
2360 	u16 new_hash4 = udp_ehashfn(sock_net(sk),
2361 				    sk->sk_rcv_saddr, sk->sk_num,
2362 				    sk->sk_daddr, sk->sk_dport);
2363 
2364 	udp_lib_rehash(sk, new_hash, new_hash4);
2365 }
2366 
2367 static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2368 {
2369 	int rc;
2370 
2371 	if (inet_sk(sk)->inet_daddr) {
2372 		sock_rps_save_rxhash(sk, skb);
2373 		sk_mark_napi_id(sk, skb);
2374 		sk_incoming_cpu_update(sk);
2375 	} else {
2376 		sk_mark_napi_id_once(sk, skb);
2377 	}
2378 
2379 	rc = __udp_enqueue_schedule_skb(sk, skb);
2380 	if (rc < 0) {
2381 		struct net *net = sock_net(sk);
2382 		int drop_reason;
2383 
2384 		/* Note that an ENOMEM error is charged twice */
2385 		if (rc == -ENOMEM) {
2386 			UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS);
2387 			drop_reason = SKB_DROP_REASON_SOCKET_RCVBUFF;
2388 		} else {
2389 			UDP_INC_STATS(net, UDP_MIB_MEMERRORS);
2390 			drop_reason = SKB_DROP_REASON_PROTO_MEM;
2391 		}
2392 		UDP_INC_STATS(net, UDP_MIB_INERRORS);
2393 		trace_udp_fail_queue_rcv_skb(rc, sk, skb);
2394 		sk_skb_reason_drop(sk, skb, drop_reason);
2395 		return -1;
2396 	}
2397 
2398 	return 0;
2399 }
2400 
2401 /* returns:
2402  *  -1: error
2403  *   0: success
2404  *  >0: "udp encap" protocol resubmission
2405  *
2406  * Note that in the success and error cases, the skb is assumed to
2407  * have either been requeued or freed.
2408  */
2409 static int udp_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
2410 {
2411 	enum skb_drop_reason drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2412 	struct udp_sock *up = udp_sk(sk);
2413 	struct net *net = sock_net(sk);
2414 
2415 	/*
2416 	 *	Charge it to the socket, dropping if the queue is full.
2417 	 */
2418 	if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
2419 		drop_reason = SKB_DROP_REASON_XFRM_POLICY;
2420 		goto drop;
2421 	}
2422 	nf_reset_ct(skb);
2423 
2424 	if (static_branch_unlikely(&udp_encap_needed_key) &&
2425 	    READ_ONCE(up->encap_type)) {
2426 		int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
2427 
2428 		/*
2429 		 * This is an encapsulation socket so pass the skb to
2430 		 * the socket's udp_encap_rcv() hook. Otherwise, just
2431 		 * fall through and pass this up the UDP socket.
2432 		 * up->encap_rcv() returns the following value:
2433 		 * =0 if skb was successfully passed to the encap
2434 		 *    handler or was discarded by it.
2435 		 * >0 if skb should be passed on to UDP.
2436 		 * <0 if skb should be resubmitted as proto -N
2437 		 */
2438 
2439 		/* if we're overly short, let UDP handle it */
2440 		encap_rcv = READ_ONCE(up->encap_rcv);
2441 		if (encap_rcv) {
2442 			int ret;
2443 
2444 			/* Verify checksum before giving to encap */
2445 			if (udp_lib_checksum_complete(skb))
2446 				goto csum_error;
2447 
2448 			ret = encap_rcv(sk, skb);
2449 			if (ret <= 0) {
2450 				__UDP_INC_STATS(net, UDP_MIB_INDATAGRAMS);
2451 				return -ret;
2452 			}
2453 		}
2454 
2455 		/* FALLTHROUGH -- it's a UDP Packet */
2456 	}
2457 
2458 	prefetch(&sk->sk_rmem_alloc);
2459 	if (rcu_access_pointer(sk->sk_filter) &&
2460 	    udp_lib_checksum_complete(skb))
2461 			goto csum_error;
2462 
2463 	drop_reason = sk_filter_trim_cap(sk, skb, sizeof(struct udphdr));
2464 	if (drop_reason)
2465 		goto drop;
2466 
2467 	udp_csum_pull_header(skb);
2468 
2469 	ipv4_pktinfo_prepare(sk, skb, true);
2470 	return __udp_queue_rcv_skb(sk, skb);
2471 
2472 csum_error:
2473 	drop_reason = SKB_DROP_REASON_UDP_CSUM;
2474 	__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS);
2475 drop:
2476 	__UDP_INC_STATS(net, UDP_MIB_INERRORS);
2477 	udp_drops_inc(sk);
2478 	sk_skb_reason_drop(sk, skb, drop_reason);
2479 	return -1;
2480 }
2481 
2482 static int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2483 {
2484 	struct sk_buff *next, *segs;
2485 	int ret;
2486 
2487 	if (likely(!udp_unexpected_gso(sk, skb)))
2488 		return udp_queue_rcv_one_skb(sk, skb);
2489 
2490 	BUILD_BUG_ON(sizeof(struct udp_skb_cb) > SKB_GSO_CB_OFFSET);
2491 	__skb_push(skb, -skb_mac_offset(skb));
2492 	segs = udp_rcv_segment(sk, skb, true);
2493 	skb_list_walk_safe(segs, skb, next) {
2494 		__skb_pull(skb, skb_transport_offset(skb));
2495 
2496 		udp_post_segment_fix_csum(skb);
2497 		ret = udp_queue_rcv_one_skb(sk, skb);
2498 		if (ret > 0)
2499 			ip_protocol_deliver_rcu(dev_net(skb->dev), skb, ret);
2500 	}
2501 	return 0;
2502 }
2503 
2504 /* For TCP sockets, sk_rx_dst is protected by socket lock
2505  * For UDP, we use xchg() to guard against concurrent changes.
2506  */
2507 bool udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
2508 {
2509 	struct dst_entry *old;
2510 
2511 	if (dst_hold_safe(dst)) {
2512 		old = unrcu_pointer(xchg(&sk->sk_rx_dst, RCU_INITIALIZER(dst)));
2513 		dst_release(old);
2514 		return old != dst;
2515 	}
2516 	return false;
2517 }
2518 
2519 /*
2520  *	Multicasts and broadcasts go to each listener.
2521  *
2522  *	Note: called only from the BH handler context.
2523  */
2524 static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
2525 				    struct udphdr  *uh,
2526 				    __be32 saddr, __be32 daddr)
2527 {
2528 	struct udp_table *udptable = net->ipv4.udp_table;
2529 	unsigned int hash2, hash2_any, offset;
2530 	unsigned short hnum = ntohs(uh->dest);
2531 	struct sock *sk, *first = NULL;
2532 	int dif = skb->dev->ifindex;
2533 	int sdif = inet_sdif(skb);
2534 	struct hlist_node *node;
2535 	struct udp_hslot *hslot;
2536 	struct sk_buff *nskb;
2537 	bool use_hash2;
2538 	int ret;
2539 
2540 	hash2_any = 0;
2541 	hash2 = 0;
2542 	hslot = udp_hashslot(udptable, net, hnum);
2543 	use_hash2 = hslot->count > 10;
2544 	offset = offsetof(typeof(*sk), sk_node);
2545 
2546 	if (use_hash2) {
2547 		hash2_any = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum) &
2548 			    udptable->mask;
2549 		hash2 = ipv4_portaddr_hash(net, daddr, hnum) & udptable->mask;
2550 start_lookup:
2551 		hslot = &udptable->hash2[hash2].hslot;
2552 		offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
2553 	}
2554 
2555 	sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
2556 		if (!__udp_is_mcast_sock(net, sk, uh->dest, daddr,
2557 					 uh->source, saddr, dif, sdif, hnum))
2558 			continue;
2559 
2560 		if (!first) {
2561 			first = sk;
2562 			continue;
2563 		}
2564 		nskb = skb_clone(skb, GFP_ATOMIC);
2565 
2566 		if (unlikely(!nskb)) {
2567 			udp_drops_inc(sk);
2568 			__UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS);
2569 			__UDP_INC_STATS(net, UDP_MIB_INERRORS);
2570 			continue;
2571 		}
2572 		if (udp_queue_rcv_skb(sk, nskb) > 0)
2573 			consume_skb(nskb);
2574 	}
2575 
2576 	/* Also lookup *:port if we are using hash2 and haven't done so yet. */
2577 	if (use_hash2 && hash2 != hash2_any) {
2578 		hash2 = hash2_any;
2579 		goto start_lookup;
2580 	}
2581 
2582 	if (first) {
2583 		ret = udp_queue_rcv_skb(first, skb);
2584 		if (ret > 0)
2585 			return -ret;
2586 	} else {
2587 		kfree_skb(skb);
2588 		__UDP_INC_STATS(net, UDP_MIB_IGNOREDMULTI);
2589 	}
2590 	return 0;
2591 }
2592 
2593 /* Initialize UDP checksum. If exited with zero value (success),
2594  * CHECKSUM_UNNECESSARY means, that no more checks are required.
2595  * Otherwise, csum completion requires checksumming packet body,
2596  * including udp header and folding it to skb->csum.
2597  */
2598 static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh)
2599 {
2600 	int err;
2601 
2602 	/* Note, we are only interested in != 0 or == 0, thus the
2603 	 * force to int.
2604 	 */
2605 	err = (__force int)skb_checksum_init_zero_check(skb, IPPROTO_UDP, uh->check,
2606 							inet_compute_pseudo);
2607 	if (err)
2608 		return err;
2609 
2610 	if (skb->ip_summed == CHECKSUM_COMPLETE && !skb->csum_valid) {
2611 		/* If SW calculated the value, we know it's bad */
2612 		if (skb->csum_complete_sw)
2613 			return 1;
2614 
2615 		/* HW says the value is bad. Let's validate that.
2616 		 * skb->csum is no longer the full packet checksum,
2617 		 * so don't treat it as such.
2618 		 */
2619 		skb_checksum_complete_unset(skb);
2620 	}
2621 
2622 	return 0;
2623 }
2624 
2625 /* wrapper for udp_queue_rcv_skb taking care of csum conversion and
2626  * return code conversion for ip layer consumption
2627  */
2628 static int udp_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb,
2629 			       struct udphdr *uh)
2630 {
2631 	int ret;
2632 
2633 	if (inet_get_convert_csum(sk) && uh->check)
2634 		skb_checksum_try_convert(skb, IPPROTO_UDP, inet_compute_pseudo);
2635 
2636 	ret = udp_queue_rcv_skb(sk, skb);
2637 
2638 	/* a return value > 0 means to resubmit the input, but
2639 	 * it wants the return to be -protocol, or 0
2640 	 */
2641 	if (ret > 0)
2642 		return -ret;
2643 	return 0;
2644 }
2645 
2646 /*
2647  *	All we need to do is get the socket, and then do a checksum.
2648  */
2649 
2650 int udp_rcv(struct sk_buff *skb)
2651 {
2652 	struct rtable *rt = skb_rtable(skb);
2653 	struct net *net = dev_net(skb->dev);
2654 	struct sock *sk = NULL;
2655 	__be32 saddr, daddr;
2656 	unsigned int ulen;
2657 	struct udphdr *uh;
2658 	bool refcounted;
2659 	int drop_reason;
2660 
2661 	drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2662 
2663 	/*
2664 	 *  Validate the packet.
2665 	 */
2666 	if (!pskb_may_pull(skb, sizeof(struct udphdr)))
2667 		goto drop;		/* No space for header. */
2668 
2669 	uh   = udp_hdr(skb);
2670 	ulen = udp_get_len(skb, uh, 0);
2671 	saddr = ip_hdr(skb)->saddr;
2672 	daddr = ip_hdr(skb)->daddr;
2673 
2674 	if (ulen > skb->len)
2675 		goto short_packet;
2676 
2677 	if (ulen < sizeof(*uh))
2678 		goto short_packet;
2679 
2680 	if (ulen < skb->len) {
2681 		if (pskb_trim_rcsum(skb, ulen))
2682 			goto short_packet;
2683 
2684 		uh = udp_hdr(skb);
2685 	}
2686 
2687 	if (udp4_csum_init(skb, uh))
2688 		goto csum_error;
2689 
2690 	sk = inet_steal_sock(net, skb, sizeof(struct udphdr), saddr, uh->source, daddr, uh->dest,
2691 			     &refcounted, udp_ehashfn);
2692 	if (IS_ERR(sk))
2693 		goto no_sk;
2694 
2695 	if (sk) {
2696 		struct dst_entry *dst = skb_dst(skb);
2697 		int ret;
2698 
2699 		if (unlikely(rcu_dereference(sk->sk_rx_dst) != dst))
2700 			udp_sk_rx_dst_set(sk, dst);
2701 
2702 		ret = udp_unicast_rcv_skb(sk, skb, uh);
2703 		if (refcounted)
2704 			sock_put(sk);
2705 		return ret;
2706 	}
2707 
2708 	if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
2709 		return __udp4_lib_mcast_deliver(net, skb, uh, saddr, daddr);
2710 
2711 	sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest);
2712 	if (sk)
2713 		return udp_unicast_rcv_skb(sk, skb, uh);
2714 no_sk:
2715 	if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
2716 		goto drop;
2717 	nf_reset_ct(skb);
2718 
2719 	/* No socket. Drop packet silently, if checksum is wrong */
2720 	if (udp_lib_checksum_complete(skb))
2721 		goto csum_error;
2722 
2723 	drop_reason = SKB_DROP_REASON_NO_SOCKET;
2724 	__UDP_INC_STATS(net, UDP_MIB_NOPORTS);
2725 	icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
2726 
2727 	/*
2728 	 * Hmm.  We got an UDP packet to a port to which we
2729 	 * don't wanna listen.  Ignore it.
2730 	 */
2731 	sk_skb_reason_drop(sk, skb, drop_reason);
2732 	return 0;
2733 
2734 short_packet:
2735 	drop_reason = SKB_DROP_REASON_PKT_TOO_SMALL;
2736 	net_dbg_ratelimited("UDP: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
2737 			    &saddr, ntohs(uh->source),
2738 			    ulen, skb->len,
2739 			    &daddr, ntohs(uh->dest));
2740 	goto drop;
2741 
2742 csum_error:
2743 	/*
2744 	 * RFC1122: OK.  Discards the bad packet silently (as far as
2745 	 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
2746 	 */
2747 	drop_reason = SKB_DROP_REASON_UDP_CSUM;
2748 	net_dbg_ratelimited("UDP: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
2749 			    &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
2750 			    ulen);
2751 	__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS);
2752 drop:
2753 	__UDP_INC_STATS(net, UDP_MIB_INERRORS);
2754 	sk_skb_reason_drop(sk, skb, drop_reason);
2755 	return 0;
2756 }
2757 
2758 /* We can only early demux multicast if there is a single matching socket.
2759  * If more than one socket found returns NULL
2760  */
2761 static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net,
2762 						  __be16 loc_port, __be32 loc_addr,
2763 						  __be16 rmt_port, __be32 rmt_addr,
2764 						  int dif, int sdif)
2765 {
2766 	struct udp_table *udptable = net->ipv4.udp_table;
2767 	unsigned short hnum = ntohs(loc_port);
2768 	struct sock *sk, *result;
2769 	struct udp_hslot *hslot;
2770 	unsigned int slot;
2771 
2772 	slot = udp_hashfn(net, hnum, udptable->mask);
2773 	hslot = &udptable->hash[slot];
2774 
2775 	/* Do not bother scanning a too big list */
2776 	if (hslot->count > 10)
2777 		return NULL;
2778 
2779 	result = NULL;
2780 	sk_for_each_rcu(sk, &hslot->head) {
2781 		if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr,
2782 					rmt_port, rmt_addr, dif, sdif, hnum)) {
2783 			if (result)
2784 				return NULL;
2785 			result = sk;
2786 		}
2787 	}
2788 
2789 	return result;
2790 }
2791 
2792 /* For unicast we should only early demux connected sockets or we can
2793  * break forwarding setups.  The chains here can be long so only check
2794  * if the first socket is an exact match and if not move on.
2795  */
2796 static struct sock *__udp4_lib_demux_lookup(struct net *net,
2797 					    __be16 loc_port, __be32 loc_addr,
2798 					    __be16 rmt_port, __be32 rmt_addr,
2799 					    int dif, int sdif)
2800 {
2801 	struct udp_table *udptable = net->ipv4.udp_table;
2802 	INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr);
2803 	unsigned short hnum = ntohs(loc_port);
2804 	struct udp_hslot *hslot2;
2805 	unsigned int hash2;
2806 	__portpair ports;
2807 	struct sock *sk;
2808 
2809 	hash2 = ipv4_portaddr_hash(net, loc_addr, hnum);
2810 	hslot2 = udp_hashslot2(udptable, hash2);
2811 	ports = INET_COMBINED_PORTS(rmt_port, hnum);
2812 
2813 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
2814 		if (inet_match(net, sk, acookie, ports, dif, sdif))
2815 			return sk;
2816 		/* Only check first socket in chain */
2817 		break;
2818 	}
2819 	return NULL;
2820 }
2821 
2822 enum skb_drop_reason udp_v4_early_demux(struct sk_buff *skb)
2823 {
2824 	struct net *net = dev_net(skb->dev);
2825 	struct in_device *in_dev = NULL;
2826 	const struct iphdr *iph;
2827 	const struct udphdr *uh;
2828 	struct sock *sk = NULL;
2829 	struct dst_entry *dst;
2830 	int dif = skb->dev->ifindex;
2831 	int sdif = inet_sdif(skb);
2832 	int ours;
2833 
2834 	/* validate the packet */
2835 	if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)))
2836 		return SKB_NOT_DROPPED_YET;
2837 
2838 	iph = ip_hdr(skb);
2839 	uh = udp_hdr(skb);
2840 
2841 	if (skb->pkt_type == PACKET_MULTICAST) {
2842 		in_dev = __in_dev_get_rcu(skb->dev);
2843 
2844 		if (!in_dev)
2845 			return SKB_NOT_DROPPED_YET;
2846 
2847 		ours = ip_check_mc_rcu(in_dev, iph->daddr, iph->saddr,
2848 				       iph->protocol);
2849 		if (!ours)
2850 			return SKB_NOT_DROPPED_YET;
2851 
2852 		sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr,
2853 						   uh->source, iph->saddr,
2854 						   dif, sdif);
2855 	} else if (skb->pkt_type == PACKET_HOST) {
2856 		sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr,
2857 					     uh->source, iph->saddr, dif, sdif);
2858 	}
2859 
2860 	if (!sk)
2861 		return SKB_NOT_DROPPED_YET;
2862 
2863 	skb->sk = sk;
2864 	DEBUG_NET_WARN_ON_ONCE(sk_is_refcounted(sk));
2865 	skb->destructor = sock_pfree;
2866 	dst = rcu_dereference(sk->sk_rx_dst);
2867 
2868 	/* A dual-stack socket can cache an IPv6 dst. */
2869 	if (dst && dst->ops->family == AF_INET)
2870 		dst = dst_check(dst, 0);
2871 	else
2872 		dst = NULL;
2873 	if (dst) {
2874 		u32 itag = 0;
2875 
2876 		/* set noref for now.
2877 		 * any place which wants to hold dst has to call
2878 		 * dst_hold_safe()
2879 		 */
2880 		skb_dst_set_noref(skb, dst);
2881 
2882 		/* for unconnected multicast sockets we need to validate
2883 		 * the source on each packet
2884 		 */
2885 		if (!inet_sk(sk)->inet_daddr && in_dev)
2886 			return ip_mc_validate_source(skb, iph->daddr,
2887 						     iph->saddr,
2888 						     ip4h_dscp(iph),
2889 						     skb->dev, in_dev, &itag);
2890 	}
2891 	return SKB_NOT_DROPPED_YET;
2892 }
2893 
2894 static void udp_destroy_sock(struct sock *sk)
2895 {
2896 	struct udp_sock *up = udp_sk(sk);
2897 	bool slow = lock_sock_fast(sk);
2898 
2899 	/* protects from races with udp_abort() */
2900 	sock_set_flag(sk, SOCK_DEAD);
2901 	udp_flush_pending_frames(sk);
2902 	unlock_sock_fast(sk, slow);
2903 	if (static_branch_unlikely(&udp_encap_needed_key)) {
2904 		if (up->encap_type) {
2905 			void (*encap_destroy)(struct sock *sk);
2906 			encap_destroy = READ_ONCE(up->encap_destroy);
2907 			if (encap_destroy)
2908 				encap_destroy(sk);
2909 		}
2910 		if (udp_test_bit(ENCAP_ENABLED, sk)) {
2911 			static_branch_dec(&udp_encap_needed_key);
2912 			udp_tunnel_cleanup_gro(sk);
2913 		}
2914 	}
2915 }
2916 
2917 typedef struct sk_buff *(*udp_gro_receive_t)(struct sock *sk,
2918 					     struct list_head *head,
2919 					     struct sk_buff *skb);
2920 
2921 static void set_xfrm_gro_udp_encap_rcv(__u16 encap_type, unsigned short family,
2922 				       struct sock *sk)
2923 {
2924 #ifdef CONFIG_XFRM
2925 	udp_gro_receive_t new_gro_receive;
2926 
2927 	if (udp_test_bit(GRO_ENABLED, sk) && encap_type == UDP_ENCAP_ESPINUDP) {
2928 		if (IS_ENABLED(CONFIG_IPV6) && family == AF_INET6)
2929 			new_gro_receive = xfrm6_gro_udp_encap_rcv;
2930 		else
2931 			new_gro_receive = xfrm4_gro_udp_encap_rcv;
2932 
2933 		if (udp_sk(sk)->gro_receive != new_gro_receive) {
2934 			/*
2935 			 * With IPV6_ADDRFORM the gro callback could change
2936 			 * after being set, unregister the old one, if valid.
2937 			 */
2938 			if (udp_sk(sk)->gro_receive)
2939 				udp_tunnel_update_gro_rcv(sk, false);
2940 
2941 			WRITE_ONCE(udp_sk(sk)->gro_receive, new_gro_receive);
2942 			udp_tunnel_update_gro_rcv(sk, true);
2943 		}
2944 	}
2945 #endif
2946 }
2947 
2948 /*
2949  *	Socket option code for UDP
2950  */
2951 int udp_lib_setsockopt(struct sock *sk, int level, int optname,
2952 		       sockptr_t optval, unsigned int optlen,
2953 		       int (*push_pending_frames)(struct sock *))
2954 {
2955 	struct udp_sock *up = udp_sk(sk);
2956 	int val, valbool;
2957 	int err = 0;
2958 
2959 	if (level == SOL_SOCKET) {
2960 		err = sk_setsockopt(sk, level, optname, optval, optlen);
2961 
2962 		if (optname == SO_RCVBUF || optname == SO_RCVBUFFORCE) {
2963 			sockopt_lock_sock(sk);
2964 			/* paired with READ_ONCE in udp_rmem_release() */
2965 			WRITE_ONCE(up->forward_threshold, sk->sk_rcvbuf >> 2);
2966 			sockopt_release_sock(sk);
2967 		}
2968 		return err;
2969 	}
2970 
2971 	if (optlen < sizeof(int))
2972 		return -EINVAL;
2973 
2974 	if (copy_from_sockptr(&val, optval, sizeof(val)))
2975 		return -EFAULT;
2976 
2977 	valbool = val ? 1 : 0;
2978 
2979 	switch (optname) {
2980 	case UDP_CORK:
2981 		if (val != 0) {
2982 			udp_set_bit(CORK, sk);
2983 		} else {
2984 			udp_clear_bit(CORK, sk);
2985 			lock_sock(sk);
2986 			push_pending_frames(sk);
2987 			release_sock(sk);
2988 		}
2989 		break;
2990 
2991 	case UDP_ENCAP:
2992 		sockopt_lock_sock(sk);
2993 		switch (val) {
2994 		case 0:
2995 #ifdef CONFIG_XFRM
2996 		case UDP_ENCAP_ESPINUDP:
2997 			set_xfrm_gro_udp_encap_rcv(val, sk->sk_family, sk);
2998 #if IS_ENABLED(CONFIG_IPV6)
2999 			if (sk->sk_family == AF_INET6)
3000 				WRITE_ONCE(up->encap_rcv,
3001 					   xfrm6_udp_encap_rcv);
3002 			else
3003 #endif
3004 				WRITE_ONCE(up->encap_rcv,
3005 					   xfrm4_udp_encap_rcv);
3006 #endif
3007 			fallthrough;
3008 		case UDP_ENCAP_L2TPINUDP:
3009 			WRITE_ONCE(up->encap_type, val);
3010 			udp_tunnel_encap_enable(sk);
3011 			break;
3012 		default:
3013 			err = -ENOPROTOOPT;
3014 			break;
3015 		}
3016 		sockopt_release_sock(sk);
3017 		break;
3018 
3019 	case UDP_NO_CHECK6_TX:
3020 		udp_set_no_check6_tx(sk, valbool);
3021 		break;
3022 
3023 	case UDP_NO_CHECK6_RX:
3024 		udp_set_no_check6_rx(sk, valbool);
3025 		break;
3026 
3027 	case UDP_SEGMENT:
3028 		if (val < 0 || val > USHRT_MAX)
3029 			return -EINVAL;
3030 		WRITE_ONCE(up->gso_size, val);
3031 		break;
3032 
3033 	case UDP_GRO:
3034 		sockopt_lock_sock(sk);
3035 		/* when enabling GRO, accept the related GSO packet type */
3036 		if (valbool)
3037 			udp_tunnel_encap_enable(sk);
3038 		udp_assign_bit(GRO_ENABLED, sk, valbool);
3039 		udp_assign_bit(ACCEPT_L4, sk, valbool);
3040 		set_xfrm_gro_udp_encap_rcv(up->encap_type, sk->sk_family, sk);
3041 		sockopt_release_sock(sk);
3042 		break;
3043 
3044 	default:
3045 		err = -ENOPROTOOPT;
3046 		break;
3047 	}
3048 
3049 	return err;
3050 }
3051 
3052 static int udp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
3053 			  unsigned int optlen)
3054 {
3055 	if (level == SOL_UDP || level == SOL_SOCKET)
3056 		return udp_lib_setsockopt(sk, level, optname,
3057 					  optval, optlen,
3058 					  udp_push_pending_frames);
3059 	return ip_setsockopt(sk, level, optname, optval, optlen);
3060 }
3061 
3062 int udp_lib_getsockopt(struct sock *sk, int level, int optname,
3063 		       sockopt_t *opt)
3064 {
3065 	struct udp_sock *up = udp_sk(sk);
3066 	int val, len;
3067 
3068 	len = opt->optlen;
3069 	/* keep the check so direct sockopt_t callers stay covered. */
3070 	if (len < 0)
3071 		return -EINVAL;
3072 
3073 	len = min_t(unsigned int, len, sizeof(int));
3074 
3075 	switch (optname) {
3076 	case UDP_CORK:
3077 		val = udp_test_bit(CORK, sk);
3078 		break;
3079 
3080 	case UDP_ENCAP:
3081 		val = READ_ONCE(up->encap_type);
3082 		break;
3083 
3084 	case UDP_NO_CHECK6_TX:
3085 		val = udp_get_no_check6_tx(sk);
3086 		break;
3087 
3088 	case UDP_NO_CHECK6_RX:
3089 		val = udp_get_no_check6_rx(sk);
3090 		break;
3091 
3092 	case UDP_SEGMENT:
3093 		val = READ_ONCE(up->gso_size);
3094 		break;
3095 
3096 	case UDP_GRO:
3097 		val = udp_test_bit(GRO_ENABLED, sk);
3098 		break;
3099 
3100 	default:
3101 		return -ENOPROTOOPT;
3102 	}
3103 
3104 	opt->optlen = len;
3105 	if (copy_to_iter(&val, len, &opt->iter_out) != len)
3106 		return -EFAULT;
3107 	return 0;
3108 }
3109 
3110 static int udp_getsockopt(struct sock *sk, int level, int optname,
3111 			  char __user *optval, int __user *optlen)
3112 {
3113 	sockopt_t opt;
3114 	int err;
3115 
3116 	/*
3117 	 * keep the old __user pointers, until ip_getsockopt() moves
3118 	 * to sockopt_t
3119 	 */
3120 	if (level != SOL_UDP)
3121 		return ip_getsockopt(sk, level, optname, optval, optlen);
3122 
3123 	err = sockopt_init_user(&opt, optval, optlen);
3124 	if (err)
3125 		return err;
3126 
3127 	err = udp_lib_getsockopt(sk, level, optname, &opt);
3128 	if (err)
3129 		return err;
3130 
3131 	/* optval was written by copy_to_iter() in udp_lib_getsockopt() */
3132 	if (put_user(opt.optlen, optlen))
3133 		return -EFAULT;
3134 
3135 	return 0;
3136 }
3137 
3138 /**
3139  * 	udp_poll - wait for a UDP event.
3140  *	@file: - file struct
3141  *	@sock: - socket
3142  *	@wait: - poll table
3143  *
3144  *	This is same as datagram poll, except for the special case of
3145  *	blocking sockets. If application is using a blocking fd
3146  *	and a packet with checksum error is in the queue;
3147  *	then it could get return from select indicating data available
3148  *	but then block when reading it. Add special case code
3149  *	to work around these arguably broken applications.
3150  */
3151 __poll_t udp_poll(struct file *file, struct socket *sock, poll_table *wait)
3152 {
3153 	__poll_t mask = datagram_poll(file, sock, wait);
3154 	struct sock *sk = sock->sk;
3155 
3156 	if (!skb_queue_empty_lockless(&udp_sk(sk)->reader_queue))
3157 		mask |= EPOLLIN | EPOLLRDNORM;
3158 
3159 	/* Check for false positives due to checksum errors */
3160 	if ((mask & EPOLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
3161 	    !(sk->sk_shutdown & RCV_SHUTDOWN) && first_packet_length(sk) == -1)
3162 		mask &= ~(EPOLLIN | EPOLLRDNORM);
3163 
3164 	/* psock ingress_msg queue should not contain any bad checksum frames */
3165 	if (sk_is_readable(sk))
3166 		mask |= EPOLLIN | EPOLLRDNORM;
3167 	return mask;
3168 
3169 }
3170 
3171 int udp_abort(struct sock *sk, int err)
3172 {
3173 	if (!has_current_bpf_ctx())
3174 		lock_sock(sk);
3175 
3176 	/* udp{v6}_destroy_sock() sets it under the sk lock, avoid racing
3177 	 * with close()
3178 	 */
3179 	if (sock_flag(sk, SOCK_DEAD))
3180 		goto out;
3181 
3182 	sk->sk_err = err;
3183 	sk_error_report(sk);
3184 	udp_unhash4_on_disconnect(sk);
3185 	__udp_disconnect(sk, 0);
3186 
3187 out:
3188 	if (!has_current_bpf_ctx())
3189 		release_sock(sk);
3190 
3191 	return 0;
3192 }
3193 
3194 struct proto udp_prot = {
3195 	.name			= "UDP",
3196 	.owner			= THIS_MODULE,
3197 	.close			= udp_lib_close,
3198 	.pre_connect		= udp_pre_connect,
3199 	.connect		= udp_connect,
3200 	.disconnect		= udp_disconnect,
3201 	.ioctl			= udp_ioctl,
3202 	.init			= udp_init_sock,
3203 	.destroy		= udp_destroy_sock,
3204 	.setsockopt		= udp_setsockopt,
3205 	.getsockopt		= udp_getsockopt,
3206 	.sendmsg		= udp_sendmsg,
3207 	.recvmsg		= udp_recvmsg,
3208 	.splice_eof		= udp_splice_eof,
3209 	.release_cb		= ip4_datagram_release_cb,
3210 	.hash			= udp_lib_hash,
3211 	.unhash			= udp_lib_unhash,
3212 	.rehash			= udp_v4_rehash,
3213 	.get_port		= udp_v4_get_port,
3214 	.put_port		= udp_lib_unhash,
3215 #ifdef CONFIG_BPF_SYSCALL
3216 	.psock_update_sk_prot	= udp_bpf_update_proto,
3217 #endif
3218 	.memory_allocated	= &net_aligned_data.udp_memory_allocated,
3219 	.per_cpu_fw_alloc	= &udp_memory_per_cpu_fw_alloc,
3220 
3221 	.sysctl_mem		= sysctl_udp_mem,
3222 	.sysctl_wmem_offset	= offsetof(struct net, ipv4.sysctl_udp_wmem_min),
3223 	.sysctl_rmem_offset	= offsetof(struct net, ipv4.sysctl_udp_rmem_min),
3224 	.obj_size		= sizeof(struct udp_sock),
3225 	.diag_destroy		= udp_abort,
3226 };
3227 EXPORT_SYMBOL(udp_prot);
3228 
3229 /* ------------------------------------------------------------------------ */
3230 #ifdef CONFIG_PROC_FS
3231 
3232 static unsigned short seq_file_family(const struct seq_file *seq);
3233 static bool seq_sk_match(struct seq_file *seq, const struct sock *sk)
3234 {
3235 	unsigned short family = seq_file_family(seq);
3236 
3237 	/* AF_UNSPEC is used as a match all */
3238 	return ((family == AF_UNSPEC || family == sk->sk_family) &&
3239 		net_eq(sock_net(sk), seq_file_net(seq)));
3240 }
3241 
3242 #ifdef CONFIG_BPF_SYSCALL
3243 static const struct seq_operations bpf_iter_udp_seq_ops;
3244 #endif
3245 
3246 static struct sock *udp_get_first(struct seq_file *seq, int start)
3247 {
3248 	struct udp_iter_state *state = seq->private;
3249 	struct net *net = seq_file_net(seq);
3250 	struct udp_table *udptable;
3251 	struct sock *sk;
3252 
3253 	udptable = net->ipv4.udp_table;
3254 
3255 	for (state->bucket = start; state->bucket <= udptable->mask;
3256 	     ++state->bucket) {
3257 		struct udp_hslot *hslot = &udptable->hash[state->bucket];
3258 
3259 		if (hlist_empty(&hslot->head))
3260 			continue;
3261 
3262 		spin_lock_bh(&hslot->lock);
3263 		sk_for_each(sk, &hslot->head) {
3264 			if (seq_sk_match(seq, sk))
3265 				goto found;
3266 		}
3267 		spin_unlock_bh(&hslot->lock);
3268 	}
3269 	sk = NULL;
3270 found:
3271 	return sk;
3272 }
3273 
3274 static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
3275 {
3276 	struct udp_iter_state *state = seq->private;
3277 	struct net *net = seq_file_net(seq);
3278 	struct udp_table *udptable;
3279 
3280 	do {
3281 		sk = sk_next(sk);
3282 	} while (sk && !seq_sk_match(seq, sk));
3283 
3284 	if (!sk) {
3285 		udptable = net->ipv4.udp_table;
3286 
3287 		if (state->bucket <= udptable->mask)
3288 			spin_unlock_bh(&udptable->hash[state->bucket].lock);
3289 
3290 		return udp_get_first(seq, state->bucket + 1);
3291 	}
3292 	return sk;
3293 }
3294 
3295 static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
3296 {
3297 	struct sock *sk = udp_get_first(seq, 0);
3298 
3299 	if (sk)
3300 		while (pos && (sk = udp_get_next(seq, sk)) != NULL)
3301 			--pos;
3302 	return pos ? NULL : sk;
3303 }
3304 
3305 void *udp_seq_start(struct seq_file *seq, loff_t *pos)
3306 {
3307 	struct udp_iter_state *state = seq->private;
3308 	state->bucket = MAX_UDP_PORTS;
3309 
3310 	return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
3311 }
3312 
3313 void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3314 {
3315 	struct sock *sk;
3316 
3317 	if (v == SEQ_START_TOKEN)
3318 		sk = udp_get_idx(seq, 0);
3319 	else
3320 		sk = udp_get_next(seq, v);
3321 
3322 	++*pos;
3323 	return sk;
3324 }
3325 
3326 void udp_seq_stop(struct seq_file *seq, void *v)
3327 {
3328 	struct udp_iter_state *state = seq->private;
3329 	struct udp_table *udptable;
3330 
3331 	udptable = seq_file_net(seq)->ipv4.udp_table;
3332 
3333 	if (state->bucket <= udptable->mask)
3334 		spin_unlock_bh(&udptable->hash[state->bucket].lock);
3335 }
3336 
3337 /* ------------------------------------------------------------------------ */
3338 static void udp4_format_sock(struct sock *sp, struct seq_file *f,
3339 		int bucket)
3340 {
3341 	struct inet_sock *inet = inet_sk(sp);
3342 	__be32 dest = inet->inet_daddr;
3343 	__be32 src  = inet->inet_rcv_saddr;
3344 	__u16 destp	  = ntohs(inet->inet_dport);
3345 	__u16 srcp	  = ntohs(inet->inet_sport);
3346 
3347 	seq_printf(f, "%5d: %08X:%04X %08X:%04X"
3348 		" %02X %08X:%08X %02X:%08lX %08X %5u %8d %llu %d 0 %u",
3349 		bucket, src, srcp, dest, destp, sp->sk_state,
3350 		sk_wmem_alloc_get(sp),
3351 		udp_rqueue_get(sp),
3352 		0, 0L, 0,
3353 		from_kuid_munged(seq_user_ns(f), sk_uid(sp)),
3354 		0, sock_i_ino(sp),
3355 		refcount_read(&sp->sk_refcnt), sk_drops_read(sp));
3356 }
3357 
3358 static int udp4_seq_show(struct seq_file *seq, void *v)
3359 {
3360 	seq_setwidth(seq, 127);
3361 	if (v == SEQ_START_TOKEN)
3362 		seq_puts(seq, "   sl  local_address rem_address   st tx_queue "
3363 			   "rx_queue tr tm->when retrnsmt   uid  timeout "
3364 			   "inode ref pointer drops");
3365 	else {
3366 		struct udp_iter_state *state = seq->private;
3367 
3368 		udp4_format_sock(v, seq, state->bucket);
3369 	}
3370 	seq_pad(seq, '\n');
3371 	return 0;
3372 }
3373 
3374 #ifdef CONFIG_BPF_SYSCALL
3375 struct bpf_iter__udp {
3376 	__bpf_md_ptr(struct bpf_iter_meta *, meta);
3377 	__bpf_md_ptr(struct udp_sock *, udp_sk);
3378 	uid_t uid __aligned(8);
3379 	int bucket __aligned(8);
3380 };
3381 
3382 union bpf_udp_iter_batch_item {
3383 	struct sock *sk;
3384 	__u64 cookie;
3385 };
3386 
3387 struct bpf_udp_iter_state {
3388 	struct udp_iter_state state;
3389 	unsigned int cur_sk;
3390 	unsigned int end_sk;
3391 	unsigned int max_sk;
3392 	union bpf_udp_iter_batch_item *batch;
3393 };
3394 
3395 static int bpf_iter_udp_realloc_batch(struct bpf_udp_iter_state *iter,
3396 				      unsigned int new_batch_sz, gfp_t flags);
3397 static struct sock *bpf_iter_udp_resume(struct sock *first_sk,
3398 					union bpf_udp_iter_batch_item *cookies,
3399 					int n_cookies)
3400 {
3401 	struct sock *sk = NULL;
3402 	int i;
3403 
3404 	for (i = 0; i < n_cookies; i++) {
3405 		sk = first_sk;
3406 		udp_portaddr_for_each_entry_from(sk)
3407 			if (cookies[i].cookie == atomic64_read(&sk->sk_cookie))
3408 				goto done;
3409 	}
3410 done:
3411 	return sk;
3412 }
3413 
3414 static struct sock *bpf_iter_udp_batch(struct seq_file *seq)
3415 {
3416 	struct bpf_udp_iter_state *iter = seq->private;
3417 	struct udp_iter_state *state = &iter->state;
3418 	unsigned int find_cookie, end_cookie;
3419 	struct net *net = seq_file_net(seq);
3420 	struct udp_table *udptable;
3421 	unsigned int batch_sks = 0;
3422 	int resume_bucket;
3423 	int resizes = 0;
3424 	struct sock *sk;
3425 	int err = 0;
3426 
3427 	resume_bucket = state->bucket;
3428 
3429 	/* The current batch is done, so advance the bucket. */
3430 	if (iter->cur_sk == iter->end_sk)
3431 		state->bucket++;
3432 
3433 	udptable = net->ipv4.udp_table;
3434 
3435 again:
3436 	/* New batch for the next bucket.
3437 	 * Iterate over the hash table to find a bucket with sockets matching
3438 	 * the iterator attributes, and return the first matching socket from
3439 	 * the bucket. The remaining matched sockets from the bucket are batched
3440 	 * before releasing the bucket lock. This allows BPF programs that are
3441 	 * called in seq_show to acquire the bucket lock if needed.
3442 	 */
3443 	find_cookie = iter->cur_sk;
3444 	end_cookie = iter->end_sk;
3445 	iter->cur_sk = 0;
3446 	iter->end_sk = 0;
3447 	batch_sks = 0;
3448 
3449 	for (; state->bucket <= udptable->mask; state->bucket++) {
3450 		struct udp_hslot *hslot2 = &udptable->hash2[state->bucket].hslot;
3451 
3452 		if (hlist_empty(&hslot2->head))
3453 			goto next_bucket;
3454 
3455 		spin_lock_bh(&hslot2->lock);
3456 		sk = hlist_entry_safe(hslot2->head.first, struct sock,
3457 				      __sk_common.skc_portaddr_node);
3458 		/* Resume from the first (in iteration order) unseen socket from
3459 		 * the last batch that still exists in resume_bucket. Most of
3460 		 * the time this will just be where the last iteration left off
3461 		 * in resume_bucket unless that socket disappeared between
3462 		 * reads.
3463 		 */
3464 		if (state->bucket == resume_bucket)
3465 			sk = bpf_iter_udp_resume(sk, &iter->batch[find_cookie],
3466 						 end_cookie - find_cookie);
3467 fill_batch:
3468 		udp_portaddr_for_each_entry_from(sk) {
3469 			if (seq_sk_match(seq, sk)) {
3470 				if (iter->end_sk < iter->max_sk) {
3471 					sock_hold(sk);
3472 					iter->batch[iter->end_sk++].sk = sk;
3473 				}
3474 				batch_sks++;
3475 			}
3476 		}
3477 
3478 		/* Allocate a larger batch and try again. */
3479 		if (unlikely(resizes <= 1 && iter->end_sk &&
3480 			     iter->end_sk != batch_sks)) {
3481 			resizes++;
3482 
3483 			/* First, try with GFP_USER to maximize the chances of
3484 			 * grabbing more memory.
3485 			 */
3486 			if (resizes == 1) {
3487 				spin_unlock_bh(&hslot2->lock);
3488 				err = bpf_iter_udp_realloc_batch(iter,
3489 								 batch_sks * 3 / 2,
3490 								 GFP_USER);
3491 				if (err)
3492 					return ERR_PTR(err);
3493 				/* Start over. */
3494 				goto again;
3495 			}
3496 
3497 			/* Next, hold onto the lock, so the bucket doesn't
3498 			 * change while we get the rest of the sockets.
3499 			 */
3500 			err = bpf_iter_udp_realloc_batch(iter, batch_sks,
3501 							 GFP_NOWAIT);
3502 			if (err) {
3503 				spin_unlock_bh(&hslot2->lock);
3504 				return ERR_PTR(err);
3505 			}
3506 
3507 			/* Pick up where we left off. */
3508 			sk = iter->batch[iter->end_sk - 1].sk;
3509 			sk = hlist_entry_safe(sk->__sk_common.skc_portaddr_node.next,
3510 					      struct sock,
3511 					      __sk_common.skc_portaddr_node);
3512 			batch_sks = iter->end_sk;
3513 			goto fill_batch;
3514 		}
3515 
3516 		spin_unlock_bh(&hslot2->lock);
3517 
3518 		if (iter->end_sk)
3519 			break;
3520 next_bucket:
3521 		resizes = 0;
3522 	}
3523 
3524 	WARN_ON_ONCE(iter->end_sk != batch_sks);
3525 	return iter->end_sk ? iter->batch[0].sk : NULL;
3526 }
3527 
3528 static void *bpf_iter_udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3529 {
3530 	struct bpf_udp_iter_state *iter = seq->private;
3531 	struct sock *sk;
3532 
3533 	/* Whenever seq_next() is called, the iter->cur_sk is
3534 	 * done with seq_show(), so unref the iter->cur_sk.
3535 	 */
3536 	if (iter->cur_sk < iter->end_sk)
3537 		sock_put(iter->batch[iter->cur_sk++].sk);
3538 
3539 	/* After updating iter->cur_sk, check if there are more sockets
3540 	 * available in the current bucket batch.
3541 	 */
3542 	if (iter->cur_sk < iter->end_sk)
3543 		sk = iter->batch[iter->cur_sk].sk;
3544 	else
3545 		/* Prepare a new batch. */
3546 		sk = bpf_iter_udp_batch(seq);
3547 
3548 	++*pos;
3549 	return sk;
3550 }
3551 
3552 static void *bpf_iter_udp_seq_start(struct seq_file *seq, loff_t *pos)
3553 {
3554 	/* bpf iter does not support lseek, so it always
3555 	 * continue from where it was stop()-ped.
3556 	 */
3557 	if (*pos)
3558 		return bpf_iter_udp_batch(seq);
3559 
3560 	return SEQ_START_TOKEN;
3561 }
3562 
3563 static int udp_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
3564 			     struct udp_sock *udp_sk, uid_t uid, int bucket)
3565 {
3566 	struct bpf_iter__udp ctx;
3567 
3568 	meta->seq_num--;  /* skip SEQ_START_TOKEN */
3569 	ctx.meta = meta;
3570 	ctx.udp_sk = udp_sk;
3571 	ctx.uid = uid;
3572 	ctx.bucket = bucket;
3573 	return bpf_iter_run_prog(prog, &ctx);
3574 }
3575 
3576 static int bpf_iter_udp_seq_show(struct seq_file *seq, void *v)
3577 {
3578 	struct udp_iter_state *state = seq->private;
3579 	struct bpf_iter_meta meta;
3580 	struct bpf_prog *prog;
3581 	struct sock *sk = v;
3582 	uid_t uid;
3583 	int ret;
3584 
3585 	if (v == SEQ_START_TOKEN)
3586 		return 0;
3587 
3588 	lock_sock(sk);
3589 
3590 	if (unlikely(sk_unhashed(sk))) {
3591 		ret = SEQ_SKIP;
3592 		goto unlock;
3593 	}
3594 
3595 	uid = from_kuid_munged(seq_user_ns(seq), sk_uid(sk));
3596 	meta.seq = seq;
3597 	prog = bpf_iter_get_info(&meta, false);
3598 	ret = udp_prog_seq_show(prog, &meta, v, uid, state->bucket);
3599 
3600 unlock:
3601 	release_sock(sk);
3602 	return ret;
3603 }
3604 
3605 static void bpf_iter_udp_put_batch(struct bpf_udp_iter_state *iter)
3606 {
3607 	union bpf_udp_iter_batch_item *item;
3608 	unsigned int cur_sk = iter->cur_sk;
3609 	__u64 cookie;
3610 
3611 	/* Remember the cookies of the sockets we haven't seen yet, so we can
3612 	 * pick up where we left off next time around.
3613 	 */
3614 	while (cur_sk < iter->end_sk) {
3615 		item = &iter->batch[cur_sk++];
3616 		cookie = sock_gen_cookie(item->sk);
3617 		sock_put(item->sk);
3618 		item->cookie = cookie;
3619 	}
3620 }
3621 
3622 static void bpf_iter_udp_seq_stop(struct seq_file *seq, void *v)
3623 {
3624 	struct bpf_udp_iter_state *iter = seq->private;
3625 	struct bpf_iter_meta meta;
3626 	struct bpf_prog *prog;
3627 
3628 	if (!v) {
3629 		meta.seq = seq;
3630 		prog = bpf_iter_get_info(&meta, true);
3631 		if (prog)
3632 			(void)udp_prog_seq_show(prog, &meta, v, 0, 0);
3633 	}
3634 
3635 	if (iter->cur_sk < iter->end_sk)
3636 		bpf_iter_udp_put_batch(iter);
3637 }
3638 
3639 static const struct seq_operations bpf_iter_udp_seq_ops = {
3640 	.start		= bpf_iter_udp_seq_start,
3641 	.next		= bpf_iter_udp_seq_next,
3642 	.stop		= bpf_iter_udp_seq_stop,
3643 	.show		= bpf_iter_udp_seq_show,
3644 };
3645 #endif
3646 
3647 static unsigned short seq_file_family(const struct seq_file *seq)
3648 {
3649 	const struct udp_seq_afinfo *afinfo;
3650 
3651 #ifdef CONFIG_BPF_SYSCALL
3652 	/* BPF iterator: bpf programs to filter sockets. */
3653 	if (seq->op == &bpf_iter_udp_seq_ops)
3654 		return AF_UNSPEC;
3655 #endif
3656 
3657 	/* Proc fs iterator */
3658 	afinfo = pde_data(file_inode(seq->file));
3659 	return afinfo->family;
3660 }
3661 
3662 static const struct seq_operations udp_seq_ops = {
3663 	.start		= udp_seq_start,
3664 	.next		= udp_seq_next,
3665 	.stop		= udp_seq_stop,
3666 	.show		= udp4_seq_show,
3667 };
3668 
3669 static struct udp_seq_afinfo udp4_seq_afinfo = {
3670 	.family		= AF_INET,
3671 };
3672 
3673 static int __net_init udp4_proc_init_net(struct net *net)
3674 {
3675 	if (!proc_create_net_data("udp", 0444, net->proc_net, &udp_seq_ops,
3676 			sizeof(struct udp_iter_state), &udp4_seq_afinfo))
3677 		return -ENOMEM;
3678 	return 0;
3679 }
3680 
3681 static void __net_exit udp4_proc_exit_net(struct net *net)
3682 {
3683 	remove_proc_entry("udp", net->proc_net);
3684 }
3685 
3686 static struct pernet_operations udp4_net_ops = {
3687 	.init = udp4_proc_init_net,
3688 	.exit = udp4_proc_exit_net,
3689 };
3690 
3691 int __init udp4_proc_init(void)
3692 {
3693 	return register_pernet_subsys(&udp4_net_ops);
3694 }
3695 
3696 void udp4_proc_exit(void)
3697 {
3698 	unregister_pernet_subsys(&udp4_net_ops);
3699 }
3700 #endif /* CONFIG_PROC_FS */
3701 
3702 static __initdata unsigned long uhash_entries;
3703 static int __init set_uhash_entries(char *str)
3704 {
3705 	ssize_t ret;
3706 
3707 	if (!str)
3708 		return 0;
3709 
3710 	ret = kstrtoul(str, 0, &uhash_entries);
3711 	if (ret)
3712 		return 0;
3713 
3714 	if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
3715 		uhash_entries = UDP_HTABLE_SIZE_MIN;
3716 	return 1;
3717 }
3718 __setup("uhash_entries=", set_uhash_entries);
3719 
3720 static void __init udp_table_init(struct udp_table *table, const char *name)
3721 {
3722 	unsigned int i, slot_size;
3723 
3724 	slot_size = sizeof(struct udp_hslot) + sizeof(struct udp_hslot_main) +
3725 		    udp_hash4_slot_size();
3726 	table->hash = alloc_large_system_hash(name,
3727 					      slot_size,
3728 					      uhash_entries,
3729 					      21, /* one slot per 2 MB */
3730 					      0,
3731 					      &table->log,
3732 					      &table->mask,
3733 					      UDP_HTABLE_SIZE_MIN,
3734 					      UDP_HTABLE_SIZE_MAX);
3735 
3736 	table->hash2 = (void *)(table->hash + (table->mask + 1));
3737 	for (i = 0; i <= table->mask; i++) {
3738 		INIT_HLIST_HEAD(&table->hash[i].head);
3739 		table->hash[i].count = 0;
3740 		spin_lock_init(&table->hash[i].lock);
3741 	}
3742 	for (i = 0; i <= table->mask; i++) {
3743 		INIT_HLIST_HEAD(&table->hash2[i].hslot.head);
3744 		table->hash2[i].hslot.count = 0;
3745 		spin_lock_init(&table->hash2[i].hslot.lock);
3746 	}
3747 	udp_table_hash4_init(table);
3748 }
3749 
3750 u32 udp_flow_hashrnd(void)
3751 {
3752 	static u32 hashrnd __read_mostly;
3753 
3754 	net_get_random_once(&hashrnd, sizeof(hashrnd));
3755 
3756 	return hashrnd;
3757 }
3758 EXPORT_SYMBOL(udp_flow_hashrnd);
3759 
3760 static void __net_init udp_sysctl_init(struct net *net)
3761 {
3762 	net->ipv4.sysctl_udp_rmem_min = PAGE_SIZE;
3763 	net->ipv4.sysctl_udp_wmem_min = PAGE_SIZE;
3764 
3765 #ifdef CONFIG_NET_L3_MASTER_DEV
3766 	net->ipv4.sysctl_udp_l3mdev_accept = 0;
3767 #endif
3768 }
3769 
3770 static struct udp_table __net_init *udp_pernet_table_alloc(unsigned int hash_entries)
3771 {
3772 	struct udp_table *udptable;
3773 	unsigned int slot_size;
3774 	int i;
3775 
3776 	udptable = kmalloc_obj(*udptable);
3777 	if (!udptable)
3778 		goto out;
3779 
3780 	slot_size = sizeof(struct udp_hslot) + sizeof(struct udp_hslot_main) +
3781 		    udp_hash4_slot_size();
3782 	udptable->hash = vmalloc_huge(hash_entries * slot_size,
3783 				      GFP_KERNEL_ACCOUNT);
3784 	if (!udptable->hash)
3785 		goto free_table;
3786 
3787 	udptable->hash2 = (void *)(udptable->hash + hash_entries);
3788 	udptable->mask = hash_entries - 1;
3789 	udptable->log = ilog2(hash_entries);
3790 
3791 	for (i = 0; i < hash_entries; i++) {
3792 		INIT_HLIST_HEAD(&udptable->hash[i].head);
3793 		udptable->hash[i].count = 0;
3794 		spin_lock_init(&udptable->hash[i].lock);
3795 
3796 		INIT_HLIST_HEAD(&udptable->hash2[i].hslot.head);
3797 		udptable->hash2[i].hslot.count = 0;
3798 		spin_lock_init(&udptable->hash2[i].hslot.lock);
3799 	}
3800 	udp_table_hash4_init(udptable);
3801 
3802 	return udptable;
3803 
3804 free_table:
3805 	kfree(udptable);
3806 out:
3807 	return NULL;
3808 }
3809 
3810 static void __net_exit udp_pernet_table_free(struct net *net)
3811 {
3812 	struct udp_table *udptable = net->ipv4.udp_table;
3813 
3814 	if (udptable == &udp_table)
3815 		return;
3816 
3817 	kvfree(udptable->hash);
3818 	kfree(udptable);
3819 }
3820 
3821 static void __net_init udp_set_table(struct net *net)
3822 {
3823 	struct udp_table *udptable;
3824 	unsigned int hash_entries;
3825 	struct net *old_net;
3826 
3827 	if (net_eq(net, &init_net))
3828 		goto fallback;
3829 
3830 	old_net = current->nsproxy->net_ns;
3831 	hash_entries = READ_ONCE(old_net->ipv4.sysctl_udp_child_hash_entries);
3832 	if (!hash_entries)
3833 		goto fallback;
3834 
3835 	/* Set min to keep the bitmap on stack in udp_lib_get_port() */
3836 	if (hash_entries < UDP_HTABLE_SIZE_MIN_PERNET)
3837 		hash_entries = UDP_HTABLE_SIZE_MIN_PERNET;
3838 	else
3839 		hash_entries = roundup_pow_of_two(hash_entries);
3840 
3841 	udptable = udp_pernet_table_alloc(hash_entries);
3842 	if (udptable) {
3843 		net->ipv4.udp_table = udptable;
3844 	} else {
3845 		pr_warn("Failed to allocate UDP hash table (entries: %u) "
3846 			"for a netns, fallback to the global one\n",
3847 			hash_entries);
3848 fallback:
3849 		net->ipv4.udp_table = &udp_table;
3850 	}
3851 }
3852 
3853 static int __net_init udp_pernet_init(struct net *net)
3854 {
3855 #if IS_ENABLED(CONFIG_NET_UDP_TUNNEL)
3856 	int i;
3857 
3858 	/* No tunnel is configured */
3859 	for (i = 0; i < ARRAY_SIZE(net->ipv4.udp_tunnel_gro); ++i) {
3860 		INIT_HLIST_HEAD(&net->ipv4.udp_tunnel_gro[i].list);
3861 		RCU_INIT_POINTER(net->ipv4.udp_tunnel_gro[i].sk, NULL);
3862 	}
3863 #endif
3864 	udp_sysctl_init(net);
3865 	udp_set_table(net);
3866 
3867 	return 0;
3868 }
3869 
3870 static void __net_exit udp_pernet_exit(struct net *net)
3871 {
3872 	udp_pernet_table_free(net);
3873 }
3874 
3875 static struct pernet_operations __net_initdata udp_sysctl_ops = {
3876 	.init	= udp_pernet_init,
3877 	.exit	= udp_pernet_exit,
3878 };
3879 
3880 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
3881 DEFINE_BPF_ITER_FUNC(udp, struct bpf_iter_meta *meta,
3882 		     struct udp_sock *udp_sk, uid_t uid, int bucket)
3883 
3884 static int bpf_iter_udp_realloc_batch(struct bpf_udp_iter_state *iter,
3885 				      unsigned int new_batch_sz, gfp_t flags)
3886 {
3887 	union bpf_udp_iter_batch_item *new_batch;
3888 
3889 	new_batch = kvmalloc_objs(*new_batch, new_batch_sz,
3890 				  flags | __GFP_NOWARN);
3891 	if (!new_batch)
3892 		return -ENOMEM;
3893 
3894 	if (flags != GFP_NOWAIT)
3895 		bpf_iter_udp_put_batch(iter);
3896 
3897 	memcpy(new_batch, iter->batch, sizeof(*iter->batch) * iter->end_sk);
3898 	kvfree(iter->batch);
3899 	iter->batch = new_batch;
3900 	iter->max_sk = new_batch_sz;
3901 
3902 	return 0;
3903 }
3904 
3905 #define INIT_BATCH_SZ 16
3906 
3907 static int bpf_iter_init_udp(void *priv_data, struct bpf_iter_aux_info *aux)
3908 {
3909 	struct bpf_udp_iter_state *iter = priv_data;
3910 	int ret;
3911 
3912 	ret = bpf_iter_init_seq_net(priv_data, aux);
3913 	if (ret)
3914 		return ret;
3915 
3916 	ret = bpf_iter_udp_realloc_batch(iter, INIT_BATCH_SZ, GFP_USER);
3917 	if (ret)
3918 		bpf_iter_fini_seq_net(priv_data);
3919 
3920 	iter->state.bucket = -1;
3921 
3922 	return ret;
3923 }
3924 
3925 static void bpf_iter_fini_udp(void *priv_data)
3926 {
3927 	struct bpf_udp_iter_state *iter = priv_data;
3928 
3929 	bpf_iter_fini_seq_net(priv_data);
3930 	kvfree(iter->batch);
3931 }
3932 
3933 static const struct bpf_iter_seq_info udp_seq_info = {
3934 	.seq_ops		= &bpf_iter_udp_seq_ops,
3935 	.init_seq_private	= bpf_iter_init_udp,
3936 	.fini_seq_private	= bpf_iter_fini_udp,
3937 	.seq_priv_size		= sizeof(struct bpf_udp_iter_state),
3938 };
3939 
3940 static struct bpf_iter_reg udp_reg_info = {
3941 	.target			= "udp",
3942 	.ctx_arg_info_size	= 1,
3943 	.ctx_arg_info		= {
3944 		{ offsetof(struct bpf_iter__udp, udp_sk),
3945 		  PTR_TO_BTF_ID_OR_NULL | PTR_TRUSTED },
3946 	},
3947 	.seq_info		= &udp_seq_info,
3948 };
3949 
3950 static void __init bpf_iter_register(void)
3951 {
3952 	udp_reg_info.ctx_arg_info[0].btf_id = btf_sock_ids[BTF_SOCK_TYPE_UDP];
3953 	if (bpf_iter_reg_target(&udp_reg_info))
3954 		pr_warn("Warning: could not register bpf iterator udp\n");
3955 }
3956 #endif
3957 
3958 void __init udp_init(void)
3959 {
3960 	unsigned long limit;
3961 
3962 	udp_table_init(&udp_table, "UDP");
3963 	limit = nr_free_buffer_pages() / 8;
3964 	limit = max(limit, 128UL);
3965 	sysctl_udp_mem[0] = limit / 4 * 3;
3966 	sysctl_udp_mem[1] = limit;
3967 	sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
3968 
3969 	if (register_pernet_subsys(&udp_sysctl_ops))
3970 		panic("UDP: failed to init sysctl parameters.\n");
3971 
3972 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
3973 	bpf_iter_register();
3974 #endif
3975 }
3976