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