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