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