xref: /linux/net/ipv4/udp.c (revision 882af43a0fc37e26d85fb0df0c9edd3bed928de4)
12874c5fdSThomas Gleixner // SPDX-License-Identifier: GPL-2.0-or-later
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  * INET		An implementation of the TCP/IP protocol suite for the LINUX
41da177e4SLinus Torvalds  *		operating system.  INET is implemented using the  BSD Socket
51da177e4SLinus Torvalds  *		interface as the means of communication with the user level.
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  *		The User Datagram Protocol (UDP).
81da177e4SLinus Torvalds  *
902c30a84SJesper Juhl  * Authors:	Ross Biro
101da177e4SLinus Torvalds  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
111da177e4SLinus Torvalds  *		Arnt Gulbrandsen, <agulbra@nvg.unit.no>
12113aa838SAlan Cox  *		Alan Cox, <alan@lxorguk.ukuu.org.uk>
131da177e4SLinus Torvalds  *		Hirokazu Takahashi, <taka@valinux.co.jp>
141da177e4SLinus Torvalds  *
151da177e4SLinus Torvalds  * Fixes:
161da177e4SLinus Torvalds  *		Alan Cox	:	verify_area() calls
171da177e4SLinus Torvalds  *		Alan Cox	: 	stopped close while in use off icmp
181da177e4SLinus Torvalds  *					messages. Not a fix but a botch that
191da177e4SLinus Torvalds  *					for udp at least is 'valid'.
201da177e4SLinus Torvalds  *		Alan Cox	:	Fixed icmp handling properly
211da177e4SLinus Torvalds  *		Alan Cox	: 	Correct error for oversized datagrams
221da177e4SLinus Torvalds  *		Alan Cox	:	Tidied select() semantics.
231da177e4SLinus Torvalds  *		Alan Cox	:	udp_err() fixed properly, also now
241da177e4SLinus Torvalds  *					select and read wake correctly on errors
251da177e4SLinus Torvalds  *		Alan Cox	:	udp_send verify_area moved to avoid mem leak
261da177e4SLinus Torvalds  *		Alan Cox	:	UDP can count its memory
271da177e4SLinus Torvalds  *		Alan Cox	:	send to an unknown connection causes
281da177e4SLinus Torvalds  *					an ECONNREFUSED off the icmp, but
291da177e4SLinus Torvalds  *					does NOT close.
301da177e4SLinus Torvalds  *		Alan Cox	:	Switched to new sk_buff handlers. No more backlog!
311da177e4SLinus Torvalds  *		Alan Cox	:	Using generic datagram code. Even smaller and the PEEK
321da177e4SLinus Torvalds  *					bug no longer crashes it.
331da177e4SLinus Torvalds  *		Fred Van Kempen	: 	Net2e support for sk->broadcast.
341da177e4SLinus Torvalds  *		Alan Cox	:	Uses skb_free_datagram
351da177e4SLinus Torvalds  *		Alan Cox	:	Added get/set sockopt support.
361da177e4SLinus Torvalds  *		Alan Cox	:	Broadcasting without option set returns EACCES.
371da177e4SLinus Torvalds  *		Alan Cox	:	No wakeup calls. Instead we now use the callbacks.
381da177e4SLinus Torvalds  *		Alan Cox	:	Use ip_tos and ip_ttl
391da177e4SLinus Torvalds  *		Alan Cox	:	SNMP Mibs
401da177e4SLinus Torvalds  *		Alan Cox	:	MSG_DONTROUTE, and 0.0.0.0 support.
411da177e4SLinus Torvalds  *		Matt Dillon	:	UDP length checks.
421da177e4SLinus Torvalds  *		Alan Cox	:	Smarter af_inet used properly.
431da177e4SLinus Torvalds  *		Alan Cox	:	Use new kernel side addressing.
441da177e4SLinus Torvalds  *		Alan Cox	:	Incorrect return on truncated datagram receive.
451da177e4SLinus Torvalds  *	Arnt Gulbrandsen 	:	New udp_send and stuff
461da177e4SLinus Torvalds  *		Alan Cox	:	Cache last socket
471da177e4SLinus Torvalds  *		Alan Cox	:	Route cache
481da177e4SLinus Torvalds  *		Jon Peatfield	:	Minor efficiency fix to sendto().
491da177e4SLinus Torvalds  *		Mike Shaver	:	RFC1122 checks.
501da177e4SLinus Torvalds  *		Alan Cox	:	Nonblocking error fix.
511da177e4SLinus Torvalds  *	Willy Konynenberg	:	Transparent proxying support.
521da177e4SLinus Torvalds  *		Mike McLagan	:	Routing by source
531da177e4SLinus Torvalds  *		David S. Miller	:	New socket lookup architecture.
541da177e4SLinus Torvalds  *					Last socket cache retained as it
551da177e4SLinus Torvalds  *					does have a high hit rate.
561da177e4SLinus Torvalds  *		Olaf Kirch	:	Don't linearise iovec on sendmsg.
571da177e4SLinus Torvalds  *		Andi Kleen	:	Some cleanups, cache destination entry
581da177e4SLinus Torvalds  *					for connect.
591da177e4SLinus Torvalds  *	Vitaly E. Lavrov	:	Transparent proxy revived after year coma.
601da177e4SLinus Torvalds  *		Melvin Smith	:	Check msg_name not msg_namelen in sendto(),
611da177e4SLinus Torvalds  *					return ENOTCONN for unconnected sockets (POSIX)
621da177e4SLinus Torvalds  *		Janos Farkas	:	don't deliver multi/broadcasts to a different
631da177e4SLinus Torvalds  *					bound-to-device socket
641da177e4SLinus Torvalds  *	Hirokazu Takahashi	:	HW checksumming for outgoing UDP
651da177e4SLinus Torvalds  *					datagrams.
661da177e4SLinus Torvalds  *	Hirokazu Takahashi	:	sendfile() on UDP works now.
671da177e4SLinus Torvalds  *		Arnaldo C. Melo :	convert /proc/net/udp to seq_file
681da177e4SLinus Torvalds  *	YOSHIFUJI Hideaki @USAGI and:	Support IPV6_V6ONLY socket option, which
691da177e4SLinus Torvalds  *	Alexey Kuznetsov:		allow both IPv4 and IPv6 sockets to bind
701da177e4SLinus Torvalds  *					a single port at the same time.
711da177e4SLinus Torvalds  *	Derek Atkins <derek@ihtfp.com>: Add Encapulation Support
72342f0234SJames Chapman  *	James Chapman		:	Add L2TP encapsulation type.
731da177e4SLinus Torvalds  */
741da177e4SLinus Torvalds 
75afd46503SJoe Perches #define pr_fmt(fmt) "UDP: " fmt
76afd46503SJoe Perches 
77aef2fedaSJakub Kicinski #include <linux/bpf-cgroup.h>
787c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
791da177e4SLinus Torvalds #include <asm/ioctls.h>
8057c8a661SMike Rapoport #include <linux/memblock.h>
818203efb3SEric Dumazet #include <linux/highmem.h>
821da177e4SLinus Torvalds #include <linux/types.h>
831da177e4SLinus Torvalds #include <linux/fcntl.h>
841da177e4SLinus Torvalds #include <linux/module.h>
851da177e4SLinus Torvalds #include <linux/socket.h>
861da177e4SLinus Torvalds #include <linux/sockios.h>
8714c85021SArnaldo Carvalho de Melo #include <linux/igmp.h>
886e540309SShawn Bohrer #include <linux/inetdevice.h>
891da177e4SLinus Torvalds #include <linux/in.h>
901da177e4SLinus Torvalds #include <linux/errno.h>
911da177e4SLinus Torvalds #include <linux/timer.h>
921da177e4SLinus Torvalds #include <linux/mm.h>
931da177e4SLinus Torvalds #include <linux/inet.h>
941da177e4SLinus Torvalds #include <linux/netdevice.h>
955a0e3ad6STejun Heo #include <linux/slab.h>
96c752f073SArnaldo Carvalho de Melo #include <net/tcp_states.h>
971da177e4SLinus Torvalds #include <linux/skbuff.h>
981da177e4SLinus Torvalds #include <linux/proc_fs.h>
991da177e4SLinus Torvalds #include <linux/seq_file.h>
100457c4cbcSEric W. Biederman #include <net/net_namespace.h>
1011da177e4SLinus Torvalds #include <net/icmp.h>
102421b3885SShawn Bohrer #include <net/inet_hashtables.h>
103e7cc0824SStefano Brivio #include <net/ip_tunnels.h>
1041da177e4SLinus Torvalds #include <net/route.h>
1051da177e4SLinus Torvalds #include <net/checksum.h>
106d457a0e3SEric Dumazet #include <net/gso.h>
1071da177e4SLinus Torvalds #include <net/xfrm.h>
108296f7ea7SSatoru Moriya #include <trace/events/udp.h>
109447167bfSEric Dumazet #include <linux/static_key.h>
110951cf368SYonghong Song #include <linux/btf_ids.h>
11122911fc5SEric Dumazet #include <trace/events/skb.h>
112076bb0c8SEliezer Tamir #include <net/busy_poll.h>
113ba4e58ecSGerrit Renker #include "udp_impl.h"
114e32ea7e7SCraig Gallek #include <net/sock_reuseport.h>
115217375a0SEric Dumazet #include <net/addrconf.h>
11660fb9567SPaolo Abeni #include <net/udp_tunnel.h>
1177938cd15SRichard Gobert #include <net/gro.h>
1180146dca7SSabrina Dubroca #if IS_ENABLED(CONFIG_IPV6)
1190146dca7SSabrina Dubroca #include <net/ipv6_stubs.h>
1200146dca7SSabrina Dubroca #endif
1211da177e4SLinus Torvalds 
122f86dcc5aSEric Dumazet struct udp_table udp_table __read_mostly;
123645ca708SEric Dumazet EXPORT_SYMBOL(udp_table);
1241da177e4SLinus Torvalds 
1258d987e5cSEric Dumazet long sysctl_udp_mem[3] __read_mostly;
12695766fffSHideo Aoki EXPORT_SYMBOL(sysctl_udp_mem);
127c482c568SEric Dumazet 
12891b6d325SEric Dumazet atomic_long_t udp_memory_allocated ____cacheline_aligned_in_smp;
12995766fffSHideo Aoki EXPORT_SYMBOL(udp_memory_allocated);
1300defbb0aSEric Dumazet DEFINE_PER_CPU(int, udp_memory_per_cpu_fw_alloc);
1310defbb0aSEric Dumazet EXPORT_PER_CPU_SYMBOL_GPL(udp_memory_per_cpu_fw_alloc);
13295766fffSHideo Aoki 
133f86dcc5aSEric Dumazet #define MAX_UDP_PORTS 65536
1349804985bSKuniyuki Iwashima #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN_PERNET)
13598322f22SEric Dumazet 
13667fb4330SKuniyuki Iwashima static struct udp_table *udp_get_table_prot(struct sock *sk)
13767fb4330SKuniyuki Iwashima {
13867fb4330SKuniyuki Iwashima 	return sk->sk_prot->h.udp_table ? : sock_net(sk)->ipv4.udp_table;
13967fb4330SKuniyuki Iwashima }
14067fb4330SKuniyuki Iwashima 
141f24d43c0SEric Dumazet static int udp_lib_lport_inuse(struct net *net, __u16 num,
142645ca708SEric Dumazet 			       const struct udp_hslot *hslot,
14398322f22SEric Dumazet 			       unsigned long *bitmap,
144fe38d2a1SJosef Bacik 			       struct sock *sk, unsigned int log)
14525030a7fSGerrit Renker {
146f24d43c0SEric Dumazet 	struct sock *sk2;
147ba418fa3STom Herbert 	kuid_t uid = sock_i_uid(sk);
14825030a7fSGerrit Renker 
149ca065d0cSEric Dumazet 	sk_for_each(sk2, &hslot->head) {
150f24d43c0SEric Dumazet 		if (net_eq(sock_net(sk2), net) &&
151f24d43c0SEric Dumazet 		    sk2 != sk &&
152d4cada4aSEric Dumazet 		    (bitmap || udp_sk(sk2)->udp_port_hash == num) &&
153f24d43c0SEric Dumazet 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
1549d4fb27dSJoe Perches 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
1559d4fb27dSJoe Perches 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
156fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, true)) {
157df560056SEric Garver 			if (sk2->sk_reuseport && sk->sk_reuseport &&
158df560056SEric Garver 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
159df560056SEric Garver 			    uid_eq(uid, sock_i_uid(sk2))) {
160df560056SEric Garver 				if (!bitmap)
161df560056SEric Garver 					return 0;
162df560056SEric Garver 			} else {
1634243cdc2SJoe Perches 				if (!bitmap)
164fc038410SDavid S. Miller 					return 1;
165df560056SEric Garver 				__set_bit(udp_sk(sk2)->udp_port_hash >> log,
166df560056SEric Garver 					  bitmap);
167df560056SEric Garver 			}
1684243cdc2SJoe Perches 		}
16998322f22SEric Dumazet 	}
17025030a7fSGerrit Renker 	return 0;
17125030a7fSGerrit Renker }
17225030a7fSGerrit Renker 
17330fff923SEric Dumazet /*
17430fff923SEric Dumazet  * Note: we still hold spinlock of primary hash chain, so no other writer
17530fff923SEric Dumazet  * can insert/delete a socket with local_port == num
17630fff923SEric Dumazet  */
17730fff923SEric Dumazet static int udp_lib_lport_inuse2(struct net *net, __u16 num,
17830fff923SEric Dumazet 				struct udp_hslot *hslot2,
179fe38d2a1SJosef Bacik 				struct sock *sk)
18030fff923SEric Dumazet {
18130fff923SEric Dumazet 	struct sock *sk2;
182ba418fa3STom Herbert 	kuid_t uid = sock_i_uid(sk);
18330fff923SEric Dumazet 	int res = 0;
18430fff923SEric Dumazet 
18530fff923SEric Dumazet 	spin_lock(&hslot2->lock);
186ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry(sk2, &hslot2->head) {
18730fff923SEric Dumazet 		if (net_eq(sock_net(sk2), net) &&
18830fff923SEric Dumazet 		    sk2 != sk &&
18930fff923SEric Dumazet 		    (udp_sk(sk2)->udp_port_hash == num) &&
19030fff923SEric Dumazet 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
1919d4fb27dSJoe Perches 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
1929d4fb27dSJoe Perches 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
193fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, true)) {
194df560056SEric Garver 			if (sk2->sk_reuseport && sk->sk_reuseport &&
195df560056SEric Garver 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
196df560056SEric Garver 			    uid_eq(uid, sock_i_uid(sk2))) {
197df560056SEric Garver 				res = 0;
198df560056SEric Garver 			} else {
19930fff923SEric Dumazet 				res = 1;
200df560056SEric Garver 			}
20130fff923SEric Dumazet 			break;
20230fff923SEric Dumazet 		}
2034243cdc2SJoe Perches 	}
20430fff923SEric Dumazet 	spin_unlock(&hslot2->lock);
20530fff923SEric Dumazet 	return res;
20630fff923SEric Dumazet }
20730fff923SEric Dumazet 
208fe38d2a1SJosef Bacik static int udp_reuseport_add_sock(struct sock *sk, struct udp_hslot *hslot)
209e32ea7e7SCraig Gallek {
210e32ea7e7SCraig Gallek 	struct net *net = sock_net(sk);
211e32ea7e7SCraig Gallek 	kuid_t uid = sock_i_uid(sk);
212e32ea7e7SCraig Gallek 	struct sock *sk2;
213e32ea7e7SCraig Gallek 
214ca065d0cSEric Dumazet 	sk_for_each(sk2, &hslot->head) {
215e32ea7e7SCraig Gallek 		if (net_eq(sock_net(sk2), net) &&
216e32ea7e7SCraig Gallek 		    sk2 != sk &&
217e32ea7e7SCraig Gallek 		    sk2->sk_family == sk->sk_family &&
218e32ea7e7SCraig Gallek 		    ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
219e32ea7e7SCraig Gallek 		    (udp_sk(sk2)->udp_port_hash == udp_sk(sk)->udp_port_hash) &&
220e32ea7e7SCraig Gallek 		    (sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
221e32ea7e7SCraig Gallek 		    sk2->sk_reuseport && uid_eq(uid, sock_i_uid(sk2)) &&
222fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, false)) {
2232dbb9b9eSMartin KaFai Lau 			return reuseport_add_sock(sk, sk2,
2242dbb9b9eSMartin KaFai Lau 						  inet_rcv_saddr_any(sk));
225e32ea7e7SCraig Gallek 		}
226e32ea7e7SCraig Gallek 	}
227e32ea7e7SCraig Gallek 
2282dbb9b9eSMartin KaFai Lau 	return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
229e32ea7e7SCraig Gallek }
230e32ea7e7SCraig Gallek 
23125030a7fSGerrit Renker /**
2326ba5a3c5SPavel Emelyanov  *  udp_lib_get_port  -  UDP/-Lite port lookup for IPv4 and IPv6
23325030a7fSGerrit Renker  *
23425030a7fSGerrit Renker  *  @sk:          socket struct in question
23525030a7fSGerrit Renker  *  @snum:        port number to look up
23625985edcSLucas De Marchi  *  @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
23730fff923SEric Dumazet  *                   with NULL address
23825030a7fSGerrit Renker  */
2396ba5a3c5SPavel Emelyanov int udp_lib_get_port(struct sock *sk, unsigned short snum,
24030fff923SEric Dumazet 		     unsigned int hash2_nulladdr)
2411da177e4SLinus Torvalds {
24267fb4330SKuniyuki Iwashima 	struct udp_table *udptable = udp_get_table_prot(sk);
243919dfa0bSKuniyuki Iwashima 	struct udp_hslot *hslot, *hslot2;
2443b1e0a65SYOSHIFUJI Hideaki 	struct net *net = sock_net(sk);
2457a7160edSKuniyuki Iwashima 	int error = -EADDRINUSE;
2461da177e4SLinus Torvalds 
24732c1da70SStephen Hemminger 	if (!snum) {
248919dfa0bSKuniyuki Iwashima 		DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
249919dfa0bSKuniyuki Iwashima 		unsigned short first, last;
2509088c560SEric Dumazet 		int low, high, remaining;
25195c96174SEric Dumazet 		unsigned int rand;
2521da177e4SLinus Torvalds 
25391d0b78cSJakub Sitnicki 		inet_sk_get_local_port_range(sk, &low, &high);
254a25de534SAnton Arapov 		remaining = (high - low) + 1;
255227b60f5SStephen Hemminger 
256a251c17aSJason A. Donenfeld 		rand = get_random_u32();
2578fc54f68SDaniel Borkmann 		first = reciprocal_scale(rand, remaining) + low;
25898322f22SEric Dumazet 		/*
25998322f22SEric Dumazet 		 * force rand to be an odd multiple of UDP_HTABLE_SIZE
26098322f22SEric Dumazet 		 */
261f86dcc5aSEric Dumazet 		rand = (rand | 1) * (udptable->mask + 1);
2625781b235SEric Dumazet 		last = first + udptable->mask + 1;
2635781b235SEric Dumazet 		do {
264f86dcc5aSEric Dumazet 			hslot = udp_hashslot(udptable, net, first);
26598322f22SEric Dumazet 			bitmap_zero(bitmap, PORTS_PER_CHAIN);
266645ca708SEric Dumazet 			spin_lock_bh(&hslot->lock);
26798322f22SEric Dumazet 			udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
268fe38d2a1SJosef Bacik 					    udptable->log);
26998322f22SEric Dumazet 
27098322f22SEric Dumazet 			snum = first;
27198322f22SEric Dumazet 			/*
27298322f22SEric Dumazet 			 * Iterate on all possible values of snum for this hash.
27398322f22SEric Dumazet 			 * Using steps of an odd multiple of UDP_HTABLE_SIZE
27498322f22SEric Dumazet 			 * give us randomization and full range coverage.
27598322f22SEric Dumazet 			 */
2769088c560SEric Dumazet 			do {
27798322f22SEric Dumazet 				if (low <= snum && snum <= high &&
278e3826f1eSAmerigo Wang 				    !test_bit(snum >> udptable->log, bitmap) &&
279122ff243SWANG Cong 				    !inet_is_local_reserved_port(net, snum))
28098322f22SEric Dumazet 					goto found;
28198322f22SEric Dumazet 				snum += rand;
28298322f22SEric Dumazet 			} while (snum != first);
28398322f22SEric Dumazet 			spin_unlock_bh(&hslot->lock);
284df560056SEric Garver 			cond_resched();
2855781b235SEric Dumazet 		} while (++first != last);
28698322f22SEric Dumazet 		goto fail;
287645ca708SEric Dumazet 	} else {
288f86dcc5aSEric Dumazet 		hslot = udp_hashslot(udptable, net, snum);
289645ca708SEric Dumazet 		spin_lock_bh(&hslot->lock);
29030fff923SEric Dumazet 		if (hslot->count > 10) {
29130fff923SEric Dumazet 			int exist;
29230fff923SEric Dumazet 			unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
29330fff923SEric Dumazet 
29430fff923SEric Dumazet 			slot2          &= udptable->mask;
29530fff923SEric Dumazet 			hash2_nulladdr &= udptable->mask;
29630fff923SEric Dumazet 
29730fff923SEric Dumazet 			hslot2 = udp_hashslot2(udptable, slot2);
29830fff923SEric Dumazet 			if (hslot->count < hslot2->count)
29930fff923SEric Dumazet 				goto scan_primary_hash;
30030fff923SEric Dumazet 
301fe38d2a1SJosef Bacik 			exist = udp_lib_lport_inuse2(net, snum, hslot2, sk);
30230fff923SEric Dumazet 			if (!exist && (hash2_nulladdr != slot2)) {
30330fff923SEric Dumazet 				hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
30430fff923SEric Dumazet 				exist = udp_lib_lport_inuse2(net, snum, hslot2,
305fe38d2a1SJosef Bacik 							     sk);
30630fff923SEric Dumazet 			}
30730fff923SEric Dumazet 			if (exist)
30830fff923SEric Dumazet 				goto fail_unlock;
30930fff923SEric Dumazet 			else
31030fff923SEric Dumazet 				goto found;
31130fff923SEric Dumazet 		}
31230fff923SEric Dumazet scan_primary_hash:
313fe38d2a1SJosef Bacik 		if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, 0))
314645ca708SEric Dumazet 			goto fail_unlock;
315645ca708SEric Dumazet 	}
31698322f22SEric Dumazet found:
317c720c7e8SEric Dumazet 	inet_sk(sk)->inet_num = snum;
318d4cada4aSEric Dumazet 	udp_sk(sk)->udp_port_hash = snum;
319d4cada4aSEric Dumazet 	udp_sk(sk)->udp_portaddr_hash ^= snum;
3201da177e4SLinus Torvalds 	if (sk_unhashed(sk)) {
321e32ea7e7SCraig Gallek 		if (sk->sk_reuseport &&
322fe38d2a1SJosef Bacik 		    udp_reuseport_add_sock(sk, hslot)) {
323e32ea7e7SCraig Gallek 			inet_sk(sk)->inet_num = 0;
324e32ea7e7SCraig Gallek 			udp_sk(sk)->udp_port_hash = 0;
325e32ea7e7SCraig Gallek 			udp_sk(sk)->udp_portaddr_hash ^= snum;
326e32ea7e7SCraig Gallek 			goto fail_unlock;
327e32ea7e7SCraig Gallek 		}
328e32ea7e7SCraig Gallek 
329ca065d0cSEric Dumazet 		sk_add_node_rcu(sk, &hslot->head);
330fdcc8aa9SEric Dumazet 		hslot->count++;
331c29a0bc4SPavel Emelyanov 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
332512615b6SEric Dumazet 
333512615b6SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
334512615b6SEric Dumazet 		spin_lock(&hslot2->lock);
335d894ba18SCraig Gallek 		if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
336d894ba18SCraig Gallek 		    sk->sk_family == AF_INET6)
3371602f49bSDavid S. Miller 			hlist_add_tail_rcu(&udp_sk(sk)->udp_portaddr_node,
338d894ba18SCraig Gallek 					   &hslot2->head);
339d894ba18SCraig Gallek 		else
340ca065d0cSEric Dumazet 			hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
341512615b6SEric Dumazet 					   &hslot2->head);
342512615b6SEric Dumazet 		hslot2->count++;
343512615b6SEric Dumazet 		spin_unlock(&hslot2->lock);
3441da177e4SLinus Torvalds 	}
345ca065d0cSEric Dumazet 	sock_set_flag(sk, SOCK_RCU_FREE);
34625030a7fSGerrit Renker 	error = 0;
347645ca708SEric Dumazet fail_unlock:
348645ca708SEric Dumazet 	spin_unlock_bh(&hslot->lock);
3491da177e4SLinus Torvalds fail:
35025030a7fSGerrit Renker 	return error;
3511da177e4SLinus Torvalds }
352c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_get_port);
3531da177e4SLinus Torvalds 
3546ba5a3c5SPavel Emelyanov int udp_v4_get_port(struct sock *sk, unsigned short snum)
355db8dac20SDavid S. Miller {
35630fff923SEric Dumazet 	unsigned int hash2_nulladdr =
357f0b1e64cSMartin KaFai Lau 		ipv4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
35830fff923SEric Dumazet 	unsigned int hash2_partial =
359f0b1e64cSMartin KaFai Lau 		ipv4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
36030fff923SEric Dumazet 
361d4cada4aSEric Dumazet 	/* precompute partial secondary hash */
36230fff923SEric Dumazet 	udp_sk(sk)->udp_portaddr_hash = hash2_partial;
363fe38d2a1SJosef Bacik 	return udp_lib_get_port(sk, snum, hash2_nulladdr);
364db8dac20SDavid S. Miller }
365db8dac20SDavid S. Miller 
366d1e37288SSu, Xuemin static int compute_score(struct sock *sk, struct net *net,
367d1e37288SSu, Xuemin 			 __be32 saddr, __be16 sport,
368fb74c277SDavid Ahern 			 __be32 daddr, unsigned short hnum,
36973545373STim Beale 			 int dif, int sdif)
370645ca708SEric Dumazet {
37160c04aecSJoe Perches 	int score;
37260c04aecSJoe Perches 	struct inet_sock *inet;
3736da5b0f0SMike Manning 	bool dev_match;
374645ca708SEric Dumazet 
37560c04aecSJoe Perches 	if (!net_eq(sock_net(sk), net) ||
37660c04aecSJoe Perches 	    udp_sk(sk)->udp_port_hash != hnum ||
37760c04aecSJoe Perches 	    ipv6_only_sock(sk))
37860c04aecSJoe Perches 		return -1;
379645ca708SEric Dumazet 
3804cdeeee9SPeter Oskolkov 	if (sk->sk_rcv_saddr != daddr)
381645ca708SEric Dumazet 		return -1;
38260c04aecSJoe Perches 
3834cdeeee9SPeter Oskolkov 	score = (sk->sk_family == PF_INET) ? 2 : 1;
3844cdeeee9SPeter Oskolkov 
3854cdeeee9SPeter Oskolkov 	inet = inet_sk(sk);
386c720c7e8SEric Dumazet 	if (inet->inet_daddr) {
387c720c7e8SEric Dumazet 		if (inet->inet_daddr != saddr)
388645ca708SEric Dumazet 			return -1;
389ba418fa3STom Herbert 		score += 4;
390645ca708SEric Dumazet 	}
39160c04aecSJoe Perches 
392c720c7e8SEric Dumazet 	if (inet->inet_dport) {
393c720c7e8SEric Dumazet 		if (inet->inet_dport != sport)
394645ca708SEric Dumazet 			return -1;
395ba418fa3STom Herbert 		score += 4;
396645ca708SEric Dumazet 	}
39760c04aecSJoe Perches 
3986da5b0f0SMike Manning 	dev_match = udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if,
3996da5b0f0SMike Manning 					dif, sdif);
40069678bcdSPaolo Abeni 	if (!dev_match)
401645ca708SEric Dumazet 		return -1;
4028d6c414cSMike Manning 	if (sk->sk_bound_dev_if)
403ba418fa3STom Herbert 		score += 4;
404fb74c277SDavid Ahern 
4057170a977SEric Dumazet 	if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
40670da268bSEric Dumazet 		score++;
407645ca708SEric Dumazet 	return score;
408645ca708SEric Dumazet }
409645ca708SEric Dumazet 
4100f495f76SLorenz Bauer INDIRECT_CALLABLE_SCOPE
4110f495f76SLorenz Bauer u32 udp_ehashfn(const struct net *net, const __be32 laddr, const __u16 lport,
4120f495f76SLorenz Bauer 		const __be32 faddr, const __be16 fport)
41365cd8033SHannes Frederic Sowa {
4141bbdceefSHannes Frederic Sowa 	static u32 udp_ehash_secret __read_mostly;
4151bbdceefSHannes Frederic Sowa 
4161bbdceefSHannes Frederic Sowa 	net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret));
4171bbdceefSHannes Frederic Sowa 
41865cd8033SHannes Frederic Sowa 	return __inet_ehashfn(laddr, lport, faddr, fport,
4191bbdceefSHannes Frederic Sowa 			      udp_ehash_secret + net_hash_mix(net));
42065cd8033SHannes Frederic Sowa }
42165cd8033SHannes Frederic Sowa 
422d1e37288SSu, Xuemin /* called with rcu_read_lock() */
4235051ebd2SEric Dumazet static struct sock *udp4_lib_lookup2(struct net *net,
4245051ebd2SEric Dumazet 				     __be32 saddr, __be16 sport,
425fb74c277SDavid Ahern 				     __be32 daddr, unsigned int hnum,
42673545373STim Beale 				     int dif, int sdif,
427d1e37288SSu, Xuemin 				     struct udp_hslot *hslot2,
4281134158bSCraig Gallek 				     struct sk_buff *skb)
4295051ebd2SEric Dumazet {
4305051ebd2SEric Dumazet 	struct sock *sk, *result;
431e94a62f5SPaolo Abeni 	int score, badness;
4325051ebd2SEric Dumazet 
4335051ebd2SEric Dumazet 	result = NULL;
434ba418fa3STom Herbert 	badness = 0;
435ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
436d1e37288SSu, Xuemin 		score = compute_score(sk, net, saddr, sport,
43773545373STim Beale 				      daddr, hnum, dif, sdif);
4385051ebd2SEric Dumazet 		if (score > badness) {
439ca065d0cSEric Dumazet 			badness = score;
4400f495f76SLorenz Bauer 
4410f495f76SLorenz Bauer 			if (sk->sk_state == TCP_ESTABLISHED) {
4420f495f76SLorenz Bauer 				result = sk;
4430f495f76SLorenz Bauer 				continue;
4440f495f76SLorenz Bauer 			}
4450f495f76SLorenz Bauer 
4460f495f76SLorenz Bauer 			result = inet_lookup_reuseport(net, sk, skb, sizeof(struct udphdr),
4470f495f76SLorenz Bauer 						       saddr, sport, daddr, hnum, udp_ehashfn);
448f0ea27e7SLorenz Bauer 			if (!result) {
449f0ea27e7SLorenz Bauer 				result = sk;
450f0ea27e7SLorenz Bauer 				continue;
451f0ea27e7SLorenz Bauer 			}
452f0ea27e7SLorenz Bauer 
453e32ea7e7SCraig Gallek 			/* Fall back to scoring if group has connections */
454f0ea27e7SLorenz Bauer 			if (!reuseport_has_conns(sk))
455ba418fa3STom Herbert 				return result;
456ba418fa3STom Herbert 
457f0ea27e7SLorenz Bauer 			/* Reuseport logic returned an error, keep original score. */
458f0ea27e7SLorenz Bauer 			if (IS_ERR(result))
459f0ea27e7SLorenz Bauer 				continue;
460f0ea27e7SLorenz Bauer 
461f0ea27e7SLorenz Bauer 			badness = compute_score(result, net, saddr, sport,
462f0ea27e7SLorenz Bauer 						daddr, hnum, dif, sdif);
463f0ea27e7SLorenz Bauer 
4645051ebd2SEric Dumazet 		}
4655051ebd2SEric Dumazet 	}
4665051ebd2SEric Dumazet 	return result;
4675051ebd2SEric Dumazet }
4685051ebd2SEric Dumazet 
469db8dac20SDavid S. Miller /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
470db8dac20SDavid S. Miller  * harder than this. -DaveM
471db8dac20SDavid S. Miller  */
472fce82338SPavel Emelyanov struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
473fb74c277SDavid Ahern 		__be16 sport, __be32 daddr, __be16 dport, int dif,
474fb74c277SDavid Ahern 		int sdif, struct udp_table *udptable, struct sk_buff *skb)
475db8dac20SDavid S. Miller {
476db8dac20SDavid S. Miller 	unsigned short hnum = ntohs(dport);
4774cdeeee9SPeter Oskolkov 	unsigned int hash2, slot2;
4784cdeeee9SPeter Oskolkov 	struct udp_hslot *hslot2;
47972f7e944SJakub Sitnicki 	struct sock *result, *sk;
480db8dac20SDavid S. Miller 
481f0b1e64cSMartin KaFai Lau 	hash2 = ipv4_portaddr_hash(net, daddr, hnum);
4825051ebd2SEric Dumazet 	slot2 = hash2 & udptable->mask;
4835051ebd2SEric Dumazet 	hslot2 = &udptable->hash2[slot2];
4845051ebd2SEric Dumazet 
48572f7e944SJakub Sitnicki 	/* Lookup connected or non-wildcard socket */
4865051ebd2SEric Dumazet 	result = udp4_lib_lookup2(net, saddr, sport,
487fb74c277SDavid Ahern 				  daddr, hnum, dif, sdif,
48873545373STim Beale 				  hslot2, skb);
48972f7e944SJakub Sitnicki 	if (!IS_ERR_OR_NULL(result) && result->sk_state == TCP_ESTABLISHED)
49072f7e944SJakub Sitnicki 		goto done;
49172f7e944SJakub Sitnicki 
49272f7e944SJakub Sitnicki 	/* Lookup redirect from BPF */
4936c886db2SLorenz Bauer 	if (static_branch_unlikely(&bpf_sk_lookup_enabled) &&
4946c886db2SLorenz Bauer 	    udptable == net->ipv4.udp_table) {
4956c886db2SLorenz Bauer 		sk = inet_lookup_run_sk_lookup(net, IPPROTO_UDP, skb, sizeof(struct udphdr),
4966c886db2SLorenz Bauer 					       saddr, sport, daddr, hnum, dif,
4976c886db2SLorenz Bauer 					       udp_ehashfn);
49872f7e944SJakub Sitnicki 		if (sk) {
49972f7e944SJakub Sitnicki 			result = sk;
50072f7e944SJakub Sitnicki 			goto done;
50172f7e944SJakub Sitnicki 		}
50272f7e944SJakub Sitnicki 	}
50372f7e944SJakub Sitnicki 
50472f7e944SJakub Sitnicki 	/* Got non-wildcard socket or error on first lookup */
50572f7e944SJakub Sitnicki 	if (result)
50672f7e944SJakub Sitnicki 		goto done;
50772f7e944SJakub Sitnicki 
50872f7e944SJakub Sitnicki 	/* Lookup wildcard sockets */
509f0b1e64cSMartin KaFai Lau 	hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
5105051ebd2SEric Dumazet 	slot2 = hash2 & udptable->mask;
5115051ebd2SEric Dumazet 	hslot2 = &udptable->hash2[slot2];
5125051ebd2SEric Dumazet 
5131223c67cSJorge Boncompte [DTI2] 	result = udp4_lib_lookup2(net, saddr, sport,
5144cdeeee9SPeter Oskolkov 				  htonl(INADDR_ANY), hnum, dif, sdif,
51573545373STim Beale 				  hslot2, skb);
51672f7e944SJakub Sitnicki done:
51788e235b8SEnrico Weigelt 	if (IS_ERR(result))
5188217ca65SMartin KaFai Lau 		return NULL;
5195051ebd2SEric Dumazet 	return result;
5205051ebd2SEric Dumazet }
521fce82338SPavel Emelyanov EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
522db8dac20SDavid S. Miller 
523607c4aafSKOVACS Krisztian static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
524607c4aafSKOVACS Krisztian 						 __be16 sport, __be16 dport,
525645ca708SEric Dumazet 						 struct udp_table *udptable)
526607c4aafSKOVACS Krisztian {
527607c4aafSKOVACS Krisztian 	const struct iphdr *iph = ip_hdr(skb);
528607c4aafSKOVACS Krisztian 
529ed7cbbceSAlexander Duyck 	return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
530607c4aafSKOVACS Krisztian 				 iph->daddr, dport, inet_iif(skb),
531fb74c277SDavid Ahern 				 inet_sdif(skb), udptable, skb);
532607c4aafSKOVACS Krisztian }
533607c4aafSKOVACS Krisztian 
5347b58e63eSEric Dumazet struct sock *udp4_lib_lookup_skb(const struct sk_buff *skb,
53563058308STom Herbert 				 __be16 sport, __be16 dport)
53663058308STom Herbert {
537257a525fSMartin KaFai Lau 	const struct iphdr *iph = ip_hdr(skb);
538ba6aac15SKuniyuki Iwashima 	struct net *net = dev_net(skb->dev);
5397938cd15SRichard Gobert 	int iif, sdif;
5407938cd15SRichard Gobert 
5417938cd15SRichard Gobert 	inet_get_iif_sdif(skb, &iif, &sdif);
542257a525fSMartin KaFai Lau 
543ba6aac15SKuniyuki Iwashima 	return __udp4_lib_lookup(net, iph->saddr, sport,
5447938cd15SRichard Gobert 				 iph->daddr, dport, iif,
5457938cd15SRichard Gobert 				 sdif, net->ipv4.udp_table, NULL);
54663058308STom Herbert }
54763058308STom Herbert 
548ca065d0cSEric Dumazet /* Must be called under rcu_read_lock().
549ca065d0cSEric Dumazet  * Does increment socket refcount.
550ca065d0cSEric Dumazet  */
5516e86000cSArnd Bergmann #if IS_ENABLED(CONFIG_NF_TPROXY_IPV4) || IS_ENABLED(CONFIG_NF_SOCKET_IPV4)
552bcd41303SKOVACS Krisztian struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
553bcd41303SKOVACS Krisztian 			     __be32 daddr, __be16 dport, int dif)
554bcd41303SKOVACS Krisztian {
555ca065d0cSEric Dumazet 	struct sock *sk;
556ca065d0cSEric Dumazet 
557ca065d0cSEric Dumazet 	sk = __udp4_lib_lookup(net, saddr, sport, daddr, dport,
558ba6aac15SKuniyuki Iwashima 			       dif, 0, net->ipv4.udp_table, NULL);
55941c6d650SReshetova, Elena 	if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
560ca065d0cSEric Dumazet 		sk = NULL;
561ca065d0cSEric Dumazet 	return sk;
562bcd41303SKOVACS Krisztian }
563bcd41303SKOVACS Krisztian EXPORT_SYMBOL_GPL(udp4_lib_lookup);
564ca065d0cSEric Dumazet #endif
565bcd41303SKOVACS Krisztian 
566a0a989d3SEric Dumazet static inline bool __udp_is_mcast_sock(struct net *net, const struct sock *sk,
567421b3885SShawn Bohrer 				       __be16 loc_port, __be32 loc_addr,
568421b3885SShawn Bohrer 				       __be16 rmt_port, __be32 rmt_addr,
569fb74c277SDavid Ahern 				       int dif, int sdif, unsigned short hnum)
570421b3885SShawn Bohrer {
571a0a989d3SEric Dumazet 	const struct inet_sock *inet = inet_sk(sk);
572421b3885SShawn Bohrer 
573421b3885SShawn Bohrer 	if (!net_eq(sock_net(sk), net) ||
574421b3885SShawn Bohrer 	    udp_sk(sk)->udp_port_hash != hnum ||
575421b3885SShawn Bohrer 	    (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
576421b3885SShawn Bohrer 	    (inet->inet_dport != rmt_port && inet->inet_dport) ||
577421b3885SShawn Bohrer 	    (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) ||
578421b3885SShawn Bohrer 	    ipv6_only_sock(sk) ||
57982ba25c6STim Beale 	    !udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif))
580421b3885SShawn Bohrer 		return false;
58160d9b031SDavid Ahern 	if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif, sdif))
582421b3885SShawn Bohrer 		return false;
583421b3885SShawn Bohrer 	return true;
584421b3885SShawn Bohrer }
585421b3885SShawn Bohrer 
586a36e185eSStefano Brivio DEFINE_STATIC_KEY_FALSE(udp_encap_needed_key);
587a36e185eSStefano Brivio void udp_encap_enable(void)
588a36e185eSStefano Brivio {
5899c480601SPaolo Abeni 	static_branch_inc(&udp_encap_needed_key);
590a36e185eSStefano Brivio }
591a36e185eSStefano Brivio EXPORT_SYMBOL(udp_encap_enable);
592a36e185eSStefano Brivio 
593a4a600ddSXin Long void udp_encap_disable(void)
594a4a600ddSXin Long {
595a4a600ddSXin Long 	static_branch_dec(&udp_encap_needed_key);
596a4a600ddSXin Long }
597a4a600ddSXin Long EXPORT_SYMBOL(udp_encap_disable);
598a4a600ddSXin Long 
599e7cc0824SStefano Brivio /* Handler for tunnels with arbitrary destination ports: no socket lookup, go
600e7cc0824SStefano Brivio  * through error handlers in encapsulations looking for a match.
601e7cc0824SStefano Brivio  */
602e7cc0824SStefano Brivio static int __udp4_lib_err_encap_no_sk(struct sk_buff *skb, u32 info)
603e7cc0824SStefano Brivio {
604e7cc0824SStefano Brivio 	int i;
605e7cc0824SStefano Brivio 
606e7cc0824SStefano Brivio 	for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) {
607e7cc0824SStefano Brivio 		int (*handler)(struct sk_buff *skb, u32 info);
60892b95364SPaolo Abeni 		const struct ip_tunnel_encap_ops *encap;
609e7cc0824SStefano Brivio 
61092b95364SPaolo Abeni 		encap = rcu_dereference(iptun_encaps[i]);
61192b95364SPaolo Abeni 		if (!encap)
612e7cc0824SStefano Brivio 			continue;
61392b95364SPaolo Abeni 		handler = encap->err_handler;
614e7cc0824SStefano Brivio 		if (handler && !handler(skb, info))
615e7cc0824SStefano Brivio 			return 0;
616e7cc0824SStefano Brivio 	}
617e7cc0824SStefano Brivio 
618e7cc0824SStefano Brivio 	return -ENOENT;
619e7cc0824SStefano Brivio }
620e7cc0824SStefano Brivio 
621a36e185eSStefano Brivio /* Try to match ICMP errors to UDP tunnels by looking up a socket without
622a36e185eSStefano Brivio  * reversing source and destination port: this will match tunnels that force the
623a36e185eSStefano Brivio  * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that
624a36e185eSStefano Brivio  * lwtunnels might actually break this assumption by being configured with
625a36e185eSStefano Brivio  * different destination ports on endpoints, in this case we won't be able to
626a36e185eSStefano Brivio  * trace ICMP messages back to them.
627a36e185eSStefano Brivio  *
628e7cc0824SStefano Brivio  * If this doesn't match any socket, probe tunnels with arbitrary destination
629e7cc0824SStefano Brivio  * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port
630e7cc0824SStefano Brivio  * we've sent packets to won't necessarily match the local destination port.
631e7cc0824SStefano Brivio  *
632a36e185eSStefano Brivio  * Then ask the tunnel implementation to match the error against a valid
633a36e185eSStefano Brivio  * association.
634a36e185eSStefano Brivio  *
635e7cc0824SStefano Brivio  * Return an error if we can't find a match, the socket if we need further
636e7cc0824SStefano Brivio  * processing, zero otherwise.
637a36e185eSStefano Brivio  */
638a36e185eSStefano Brivio static struct sock *__udp4_lib_err_encap(struct net *net,
639a36e185eSStefano Brivio 					 const struct iphdr *iph,
640a36e185eSStefano Brivio 					 struct udphdr *uh,
641a36e185eSStefano Brivio 					 struct udp_table *udptable,
6429bfce73cSVadim Fedorenko 					 struct sock *sk,
643e7cc0824SStefano Brivio 					 struct sk_buff *skb, u32 info)
644a36e185eSStefano Brivio {
6459bfce73cSVadim Fedorenko 	int (*lookup)(struct sock *sk, struct sk_buff *skb);
646a36e185eSStefano Brivio 	int network_offset, transport_offset;
6479bfce73cSVadim Fedorenko 	struct udp_sock *up;
648a36e185eSStefano Brivio 
649a36e185eSStefano Brivio 	network_offset = skb_network_offset(skb);
650a36e185eSStefano Brivio 	transport_offset = skb_transport_offset(skb);
651a36e185eSStefano Brivio 
652a36e185eSStefano Brivio 	/* Network header needs to point to the outer IPv4 header inside ICMP */
653a36e185eSStefano Brivio 	skb_reset_network_header(skb);
654a36e185eSStefano Brivio 
655a36e185eSStefano Brivio 	/* Transport header needs to point to the UDP header */
656a36e185eSStefano Brivio 	skb_set_transport_header(skb, iph->ihl << 2);
657a36e185eSStefano Brivio 
6589bfce73cSVadim Fedorenko 	if (sk) {
6599bfce73cSVadim Fedorenko 		up = udp_sk(sk);
6609bfce73cSVadim Fedorenko 
6619bfce73cSVadim Fedorenko 		lookup = READ_ONCE(up->encap_err_lookup);
6629bfce73cSVadim Fedorenko 		if (lookup && lookup(sk, skb))
6639bfce73cSVadim Fedorenko 			sk = NULL;
6649bfce73cSVadim Fedorenko 
6659bfce73cSVadim Fedorenko 		goto out;
6669bfce73cSVadim Fedorenko 	}
6679bfce73cSVadim Fedorenko 
668e7cc0824SStefano Brivio 	sk = __udp4_lib_lookup(net, iph->daddr, uh->source,
669e7cc0824SStefano Brivio 			       iph->saddr, uh->dest, skb->dev->ifindex, 0,
670e7cc0824SStefano Brivio 			       udptable, NULL);
671e7cc0824SStefano Brivio 	if (sk) {
6729bfce73cSVadim Fedorenko 		up = udp_sk(sk);
673e7cc0824SStefano Brivio 
674a36e185eSStefano Brivio 		lookup = READ_ONCE(up->encap_err_lookup);
675a36e185eSStefano Brivio 		if (!lookup || lookup(sk, skb))
676a36e185eSStefano Brivio 			sk = NULL;
677e7cc0824SStefano Brivio 	}
678e7cc0824SStefano Brivio 
6799bfce73cSVadim Fedorenko out:
680e7cc0824SStefano Brivio 	if (!sk)
681e7cc0824SStefano Brivio 		sk = ERR_PTR(__udp4_lib_err_encap_no_sk(skb, info));
682a36e185eSStefano Brivio 
683a36e185eSStefano Brivio 	skb_set_transport_header(skb, transport_offset);
684a36e185eSStefano Brivio 	skb_set_network_header(skb, network_offset);
685a36e185eSStefano Brivio 
686a36e185eSStefano Brivio 	return sk;
687a36e185eSStefano Brivio }
688a36e185eSStefano Brivio 
689db8dac20SDavid S. Miller /*
690db8dac20SDavid S. Miller  * This routine is called by the ICMP module when it gets some
691db8dac20SDavid S. Miller  * sort of error condition.  If err < 0 then the socket should
692db8dac20SDavid S. Miller  * be closed and the error returned to the user.  If err > 0
693db8dac20SDavid S. Miller  * it's just the icmp type << 8 | icmp code.
694db8dac20SDavid S. Miller  * Header points to the ip header of the error packet. We move
695db8dac20SDavid S. Miller  * on past this. Then (as it used to claim before adjustment)
696db8dac20SDavid S. Miller  * header points to the first 8 bytes of the udp header.  We need
697db8dac20SDavid S. Miller  * to find the appropriate port.
698db8dac20SDavid S. Miller  */
699db8dac20SDavid S. Miller 
70032bbd879SStefano Brivio int __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
701db8dac20SDavid S. Miller {
702db8dac20SDavid S. Miller 	struct inet_sock *inet;
703b71d1d42SEric Dumazet 	const struct iphdr *iph = (const struct iphdr *)skb->data;
704db8dac20SDavid S. Miller 	struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
705db8dac20SDavid S. Miller 	const int type = icmp_hdr(skb)->type;
706db8dac20SDavid S. Miller 	const int code = icmp_hdr(skb)->code;
707a36e185eSStefano Brivio 	bool tunnel = false;
708db8dac20SDavid S. Miller 	struct sock *sk;
709db8dac20SDavid S. Miller 	int harderr;
710db8dac20SDavid S. Miller 	int err;
711fd54d716SPavel Emelyanov 	struct net *net = dev_net(skb->dev);
712db8dac20SDavid S. Miller 
713fd54d716SPavel Emelyanov 	sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
714f64bf6b8SMike Manning 			       iph->saddr, uh->source, skb->dev->ifindex,
715f64bf6b8SMike Manning 			       inet_sdif(skb), udptable, NULL);
7169bfce73cSVadim Fedorenko 
71770a36f57SEric Dumazet 	if (!sk || READ_ONCE(udp_sk(sk)->encap_type)) {
718a36e185eSStefano Brivio 		/* No socket for error: try tunnels before discarding */
719e7cc0824SStefano Brivio 		if (static_branch_unlikely(&udp_encap_needed_key)) {
7209bfce73cSVadim Fedorenko 			sk = __udp4_lib_err_encap(net, iph, uh, udptable, sk, skb,
721e7cc0824SStefano Brivio 						  info);
722e7cc0824SStefano Brivio 			if (!sk)
723e7cc0824SStefano Brivio 				return 0;
7249bfce73cSVadim Fedorenko 		} else
7259bfce73cSVadim Fedorenko 			sk = ERR_PTR(-ENOENT);
726e7cc0824SStefano Brivio 
727e7cc0824SStefano Brivio 		if (IS_ERR(sk)) {
728e7cc0824SStefano Brivio 			__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
729e7cc0824SStefano Brivio 			return PTR_ERR(sk);
730e7cc0824SStefano Brivio 		}
731e7cc0824SStefano Brivio 
732a36e185eSStefano Brivio 		tunnel = true;
733db8dac20SDavid S. Miller 	}
734db8dac20SDavid S. Miller 
735db8dac20SDavid S. Miller 	err = 0;
736db8dac20SDavid S. Miller 	harderr = 0;
737db8dac20SDavid S. Miller 	inet = inet_sk(sk);
738db8dac20SDavid S. Miller 
739db8dac20SDavid S. Miller 	switch (type) {
740db8dac20SDavid S. Miller 	default:
741db8dac20SDavid S. Miller 	case ICMP_TIME_EXCEEDED:
742db8dac20SDavid S. Miller 		err = EHOSTUNREACH;
743db8dac20SDavid S. Miller 		break;
744db8dac20SDavid S. Miller 	case ICMP_SOURCE_QUENCH:
745db8dac20SDavid S. Miller 		goto out;
746db8dac20SDavid S. Miller 	case ICMP_PARAMETERPROB:
747db8dac20SDavid S. Miller 		err = EPROTO;
748db8dac20SDavid S. Miller 		harderr = 1;
749db8dac20SDavid S. Miller 		break;
750db8dac20SDavid S. Miller 	case ICMP_DEST_UNREACH:
751db8dac20SDavid S. Miller 		if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
75236393395SDavid S. Miller 			ipv4_sk_update_pmtu(skb, sk, info);
753db8dac20SDavid S. Miller 			if (inet->pmtudisc != IP_PMTUDISC_DONT) {
754db8dac20SDavid S. Miller 				err = EMSGSIZE;
755db8dac20SDavid S. Miller 				harderr = 1;
756db8dac20SDavid S. Miller 				break;
757db8dac20SDavid S. Miller 			}
758db8dac20SDavid S. Miller 			goto out;
759db8dac20SDavid S. Miller 		}
760db8dac20SDavid S. Miller 		err = EHOSTUNREACH;
761db8dac20SDavid S. Miller 		if (code <= NR_ICMP_UNREACH) {
762db8dac20SDavid S. Miller 			harderr = icmp_err_convert[code].fatal;
763db8dac20SDavid S. Miller 			err = icmp_err_convert[code].errno;
764db8dac20SDavid S. Miller 		}
765db8dac20SDavid S. Miller 		break;
76655be7a9cSDavid S. Miller 	case ICMP_REDIRECT:
76755be7a9cSDavid S. Miller 		ipv4_sk_redirect(skb, sk);
7681a462d18SDuan Jiong 		goto out;
769db8dac20SDavid S. Miller 	}
770db8dac20SDavid S. Miller 
771db8dac20SDavid S. Miller 	/*
772db8dac20SDavid S. Miller 	 *      RFC1122: OK.  Passes ICMP errors back to application, as per
773db8dac20SDavid S. Miller 	 *	4.1.3.3.
774db8dac20SDavid S. Miller 	 */
775a36e185eSStefano Brivio 	if (tunnel) {
776a36e185eSStefano Brivio 		/* ...not for tunnels though: we don't have a sending socket */
777ac56a0b4SDavid Howells 		if (udp_sk(sk)->encap_err_rcv)
77842fb06b3SDavid Howells 			udp_sk(sk)->encap_err_rcv(sk, skb, err, uh->dest, info,
77942fb06b3SDavid Howells 						  (u8 *)(uh+1));
780a36e185eSStefano Brivio 		goto out;
781a36e185eSStefano Brivio 	}
7826b5f43eaSEric Dumazet 	if (!inet_test_bit(RECVERR, sk)) {
783db8dac20SDavid S. Miller 		if (!harderr || sk->sk_state != TCP_ESTABLISHED)
784db8dac20SDavid S. Miller 			goto out;
785b1faf566SEric Dumazet 	} else
786db8dac20SDavid S. Miller 		ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
787b1faf566SEric Dumazet 
788db8dac20SDavid S. Miller 	sk->sk_err = err;
789e3ae2365SAlexander Aring 	sk_error_report(sk);
790db8dac20SDavid S. Miller out:
79132bbd879SStefano Brivio 	return 0;
792db8dac20SDavid S. Miller }
793db8dac20SDavid S. Miller 
79432bbd879SStefano Brivio int udp_err(struct sk_buff *skb, u32 info)
795db8dac20SDavid S. Miller {
796ba6aac15SKuniyuki Iwashima 	return __udp4_lib_err(skb, info, dev_net(skb->dev)->ipv4.udp_table);
797db8dac20SDavid S. Miller }
798db8dac20SDavid S. Miller 
799db8dac20SDavid S. Miller /*
800db8dac20SDavid S. Miller  * Throw away all pending data and cancel the corking. Socket is locked.
801db8dac20SDavid S. Miller  */
80236d926b9SDenis V. Lunev void udp_flush_pending_frames(struct sock *sk)
803db8dac20SDavid S. Miller {
804db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
805db8dac20SDavid S. Miller 
806db8dac20SDavid S. Miller 	if (up->pending) {
807db8dac20SDavid S. Miller 		up->len = 0;
808db8dac20SDavid S. Miller 		up->pending = 0;
809db8dac20SDavid S. Miller 		ip_flush_pending_frames(sk);
810db8dac20SDavid S. Miller 	}
811db8dac20SDavid S. Miller }
81236d926b9SDenis V. Lunev EXPORT_SYMBOL(udp_flush_pending_frames);
813db8dac20SDavid S. Miller 
814db8dac20SDavid S. Miller /**
815f6b9664fSHerbert Xu  * 	udp4_hwcsum  -  handle outgoing HW checksumming
816db8dac20SDavid S. Miller  * 	@skb: 	sk_buff containing the filled-in UDP header
817db8dac20SDavid S. Miller  * 	        (checksum field must be zeroed out)
818f6b9664fSHerbert Xu  *	@src:	source IP address
819f6b9664fSHerbert Xu  *	@dst:	destination IP address
820db8dac20SDavid S. Miller  */
821c26bf4a5SThomas Graf void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
822db8dac20SDavid S. Miller {
823db8dac20SDavid S. Miller 	struct udphdr *uh = udp_hdr(skb);
824f6b9664fSHerbert Xu 	int offset = skb_transport_offset(skb);
825f6b9664fSHerbert Xu 	int len = skb->len - offset;
826f6b9664fSHerbert Xu 	int hlen = len;
827db8dac20SDavid S. Miller 	__wsum csum = 0;
828db8dac20SDavid S. Miller 
829ebbe495fSWANG Cong 	if (!skb_has_frag_list(skb)) {
830db8dac20SDavid S. Miller 		/*
831db8dac20SDavid S. Miller 		 * Only one fragment on the socket.
832db8dac20SDavid S. Miller 		 */
833db8dac20SDavid S. Miller 		skb->csum_start = skb_transport_header(skb) - skb->head;
834db8dac20SDavid S. Miller 		skb->csum_offset = offsetof(struct udphdr, check);
835f6b9664fSHerbert Xu 		uh->check = ~csum_tcpudp_magic(src, dst, len,
836f6b9664fSHerbert Xu 					       IPPROTO_UDP, 0);
837db8dac20SDavid S. Miller 	} else {
838ebbe495fSWANG Cong 		struct sk_buff *frags;
839ebbe495fSWANG Cong 
840db8dac20SDavid S. Miller 		/*
841db8dac20SDavid S. Miller 		 * HW-checksum won't work as there are two or more
842db8dac20SDavid S. Miller 		 * fragments on the socket so that all csums of sk_buffs
843db8dac20SDavid S. Miller 		 * should be together
844db8dac20SDavid S. Miller 		 */
845ebbe495fSWANG Cong 		skb_walk_frags(skb, frags) {
846f6b9664fSHerbert Xu 			csum = csum_add(csum, frags->csum);
847f6b9664fSHerbert Xu 			hlen -= frags->len;
848ebbe495fSWANG Cong 		}
849db8dac20SDavid S. Miller 
850f6b9664fSHerbert Xu 		csum = skb_checksum(skb, offset, hlen, csum);
851db8dac20SDavid S. Miller 		skb->ip_summed = CHECKSUM_NONE;
852db8dac20SDavid S. Miller 
853db8dac20SDavid S. Miller 		uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
854db8dac20SDavid S. Miller 		if (uh->check == 0)
855db8dac20SDavid S. Miller 			uh->check = CSUM_MANGLED_0;
856db8dac20SDavid S. Miller 	}
857db8dac20SDavid S. Miller }
858c26bf4a5SThomas Graf EXPORT_SYMBOL_GPL(udp4_hwcsum);
859db8dac20SDavid S. Miller 
860af5fcba7STom Herbert /* Function to set UDP checksum for an IPv4 UDP packet. This is intended
861af5fcba7STom Herbert  * for the simple case like when setting the checksum for a UDP tunnel.
862af5fcba7STom Herbert  */
863af5fcba7STom Herbert void udp_set_csum(bool nocheck, struct sk_buff *skb,
864af5fcba7STom Herbert 		  __be32 saddr, __be32 daddr, int len)
865af5fcba7STom Herbert {
866af5fcba7STom Herbert 	struct udphdr *uh = udp_hdr(skb);
867af5fcba7STom Herbert 
868179bc67fSEdward Cree 	if (nocheck) {
869af5fcba7STom Herbert 		uh->check = 0;
870179bc67fSEdward Cree 	} else if (skb_is_gso(skb)) {
871af5fcba7STom Herbert 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
872179bc67fSEdward Cree 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) {
873179bc67fSEdward Cree 		uh->check = 0;
874179bc67fSEdward Cree 		uh->check = udp_v4_check(len, saddr, daddr, lco_csum(skb));
875179bc67fSEdward Cree 		if (uh->check == 0)
876179bc67fSEdward Cree 			uh->check = CSUM_MANGLED_0;
877d75f1306SEdward Cree 	} else {
878af5fcba7STom Herbert 		skb->ip_summed = CHECKSUM_PARTIAL;
879af5fcba7STom Herbert 		skb->csum_start = skb_transport_header(skb) - skb->head;
880af5fcba7STom Herbert 		skb->csum_offset = offsetof(struct udphdr, check);
881af5fcba7STom Herbert 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
882af5fcba7STom Herbert 	}
883af5fcba7STom Herbert }
884af5fcba7STom Herbert EXPORT_SYMBOL(udp_set_csum);
885af5fcba7STom Herbert 
886bec1f6f6SWillem de Bruijn static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4,
887bec1f6f6SWillem de Bruijn 			struct inet_cork *cork)
888f6b9664fSHerbert Xu {
889f6b9664fSHerbert Xu 	struct sock *sk = skb->sk;
890f6b9664fSHerbert Xu 	struct inet_sock *inet = inet_sk(sk);
891f6b9664fSHerbert Xu 	struct udphdr *uh;
892cffb8f61SMenglong Dong 	int err;
893f6b9664fSHerbert Xu 	int is_udplite = IS_UDPLITE(sk);
894f6b9664fSHerbert Xu 	int offset = skb_transport_offset(skb);
895f6b9664fSHerbert Xu 	int len = skb->len - offset;
8964094871dSJosh Hunt 	int datalen = len - sizeof(*uh);
897f6b9664fSHerbert Xu 	__wsum csum = 0;
898f6b9664fSHerbert Xu 
899f6b9664fSHerbert Xu 	/*
900f6b9664fSHerbert Xu 	 * Create a UDP header
901f6b9664fSHerbert Xu 	 */
902f6b9664fSHerbert Xu 	uh = udp_hdr(skb);
903f6b9664fSHerbert Xu 	uh->source = inet->inet_sport;
90479ab0531SDavid S. Miller 	uh->dest = fl4->fl4_dport;
905f6b9664fSHerbert Xu 	uh->len = htons(len);
906f6b9664fSHerbert Xu 	uh->check = 0;
907f6b9664fSHerbert Xu 
908bec1f6f6SWillem de Bruijn 	if (cork->gso_size) {
909bec1f6f6SWillem de Bruijn 		const int hlen = skb_network_header_len(skb) +
910bec1f6f6SWillem de Bruijn 				 sizeof(struct udphdr);
911bec1f6f6SWillem de Bruijn 
9120f149c9fSWillem de Bruijn 		if (hlen + cork->gso_size > cork->fragsize) {
9130f149c9fSWillem de Bruijn 			kfree_skb(skb);
914bec1f6f6SWillem de Bruijn 			return -EINVAL;
9150f149c9fSWillem de Bruijn 		}
916158390e4SJianguo Wu 		if (datalen > cork->gso_size * UDP_MAX_SEGMENTS) {
9170f149c9fSWillem de Bruijn 			kfree_skb(skb);
918bec1f6f6SWillem de Bruijn 			return -EINVAL;
9190f149c9fSWillem de Bruijn 		}
9200f149c9fSWillem de Bruijn 		if (sk->sk_no_check_tx) {
9210f149c9fSWillem de Bruijn 			kfree_skb(skb);
922a8c744a8SWillem de Bruijn 			return -EINVAL;
9230f149c9fSWillem de Bruijn 		}
924ff06342cSWillem de Bruijn 		if (skb->ip_summed != CHECKSUM_PARTIAL || is_udplite ||
9250f149c9fSWillem de Bruijn 		    dst_xfrm(skb_dst(skb))) {
9260f149c9fSWillem de Bruijn 			kfree_skb(skb);
927bec1f6f6SWillem de Bruijn 			return -EIO;
9280f149c9fSWillem de Bruijn 		}
929bec1f6f6SWillem de Bruijn 
9304094871dSJosh Hunt 		if (datalen > cork->gso_size) {
931bec1f6f6SWillem de Bruijn 			skb_shinfo(skb)->gso_size = cork->gso_size;
932bec1f6f6SWillem de Bruijn 			skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4;
9334094871dSJosh Hunt 			skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(datalen,
934dfec0ee2SAlexander Duyck 								 cork->gso_size);
9354094871dSJosh Hunt 		}
936a8c744a8SWillem de Bruijn 		goto csum_partial;
937bec1f6f6SWillem de Bruijn 	}
938bec1f6f6SWillem de Bruijn 
939f6b9664fSHerbert Xu 	if (is_udplite)  				 /*     UDP-Lite      */
940f6b9664fSHerbert Xu 		csum = udplite_csum(skb);
941f6b9664fSHerbert Xu 
942ab2fb7e3SWillem de Bruijn 	else if (sk->sk_no_check_tx) {			 /* UDP csum off */
943f6b9664fSHerbert Xu 
944f6b9664fSHerbert Xu 		skb->ip_summed = CHECKSUM_NONE;
945f6b9664fSHerbert Xu 		goto send;
946f6b9664fSHerbert Xu 
947f6b9664fSHerbert Xu 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
948a8c744a8SWillem de Bruijn csum_partial:
949f6b9664fSHerbert Xu 
95079ab0531SDavid S. Miller 		udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
951f6b9664fSHerbert Xu 		goto send;
952f6b9664fSHerbert Xu 
953f6b9664fSHerbert Xu 	} else
954f6b9664fSHerbert Xu 		csum = udp_csum(skb);
955f6b9664fSHerbert Xu 
956f6b9664fSHerbert Xu 	/* add protocol-dependent pseudo-header */
95779ab0531SDavid S. Miller 	uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
958f6b9664fSHerbert Xu 				      sk->sk_protocol, csum);
959f6b9664fSHerbert Xu 	if (uh->check == 0)
960f6b9664fSHerbert Xu 		uh->check = CSUM_MANGLED_0;
961f6b9664fSHerbert Xu 
962f6b9664fSHerbert Xu send:
963b5ec8eeaSEric Dumazet 	err = ip_send_skb(sock_net(sk), skb);
964f6b9664fSHerbert Xu 	if (err) {
9656b5f43eaSEric Dumazet 		if (err == -ENOBUFS &&
9666b5f43eaSEric Dumazet 		    !inet_test_bit(RECVERR, sk)) {
9676aef70a8SEric Dumazet 			UDP_INC_STATS(sock_net(sk),
968f6b9664fSHerbert Xu 				      UDP_MIB_SNDBUFERRORS, is_udplite);
969f6b9664fSHerbert Xu 			err = 0;
970f6b9664fSHerbert Xu 		}
971f6b9664fSHerbert Xu 	} else
9726aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
973f6b9664fSHerbert Xu 			      UDP_MIB_OUTDATAGRAMS, is_udplite);
974f6b9664fSHerbert Xu 	return err;
975f6b9664fSHerbert Xu }
976f6b9664fSHerbert Xu 
977db8dac20SDavid S. Miller /*
978db8dac20SDavid S. Miller  * Push out all pending data as one UDP datagram. Socket is locked.
979db8dac20SDavid S. Miller  */
9808822b64aSHannes Frederic Sowa int udp_push_pending_frames(struct sock *sk)
981db8dac20SDavid S. Miller {
982db8dac20SDavid S. Miller 	struct udp_sock  *up = udp_sk(sk);
983db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
984b6f21b26SDavid S. Miller 	struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
985db8dac20SDavid S. Miller 	struct sk_buff *skb;
986db8dac20SDavid S. Miller 	int err = 0;
987db8dac20SDavid S. Miller 
98877968b78SDavid S. Miller 	skb = ip_finish_skb(sk, fl4);
989f6b9664fSHerbert Xu 	if (!skb)
990db8dac20SDavid S. Miller 		goto out;
991db8dac20SDavid S. Miller 
992bec1f6f6SWillem de Bruijn 	err = udp_send_skb(skb, fl4, &inet->cork.base);
993db8dac20SDavid S. Miller 
994db8dac20SDavid S. Miller out:
995db8dac20SDavid S. Miller 	up->len = 0;
996db8dac20SDavid S. Miller 	up->pending = 0;
997db8dac20SDavid S. Miller 	return err;
998db8dac20SDavid S. Miller }
9998822b64aSHannes Frederic Sowa EXPORT_SYMBOL(udp_push_pending_frames);
1000db8dac20SDavid S. Miller 
10012e8de857SWillem de Bruijn static int __udp_cmsg_send(struct cmsghdr *cmsg, u16 *gso_size)
10022e8de857SWillem de Bruijn {
10032e8de857SWillem de Bruijn 	switch (cmsg->cmsg_type) {
10042e8de857SWillem de Bruijn 	case UDP_SEGMENT:
10052e8de857SWillem de Bruijn 		if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u16)))
10062e8de857SWillem de Bruijn 			return -EINVAL;
10072e8de857SWillem de Bruijn 		*gso_size = *(__u16 *)CMSG_DATA(cmsg);
10082e8de857SWillem de Bruijn 		return 0;
10092e8de857SWillem de Bruijn 	default:
10102e8de857SWillem de Bruijn 		return -EINVAL;
10112e8de857SWillem de Bruijn 	}
10122e8de857SWillem de Bruijn }
10132e8de857SWillem de Bruijn 
10142e8de857SWillem de Bruijn int udp_cmsg_send(struct sock *sk, struct msghdr *msg, u16 *gso_size)
10152e8de857SWillem de Bruijn {
10162e8de857SWillem de Bruijn 	struct cmsghdr *cmsg;
10172e8de857SWillem de Bruijn 	bool need_ip = false;
10182e8de857SWillem de Bruijn 	int err;
10192e8de857SWillem de Bruijn 
10202e8de857SWillem de Bruijn 	for_each_cmsghdr(cmsg, msg) {
10212e8de857SWillem de Bruijn 		if (!CMSG_OK(msg, cmsg))
10222e8de857SWillem de Bruijn 			return -EINVAL;
10232e8de857SWillem de Bruijn 
10242e8de857SWillem de Bruijn 		if (cmsg->cmsg_level != SOL_UDP) {
10252e8de857SWillem de Bruijn 			need_ip = true;
10262e8de857SWillem de Bruijn 			continue;
10272e8de857SWillem de Bruijn 		}
10282e8de857SWillem de Bruijn 
10292e8de857SWillem de Bruijn 		err = __udp_cmsg_send(cmsg, gso_size);
10302e8de857SWillem de Bruijn 		if (err)
10312e8de857SWillem de Bruijn 			return err;
10322e8de857SWillem de Bruijn 	}
10332e8de857SWillem de Bruijn 
10342e8de857SWillem de Bruijn 	return need_ip;
10352e8de857SWillem de Bruijn }
10362e8de857SWillem de Bruijn EXPORT_SYMBOL_GPL(udp_cmsg_send);
10372e8de857SWillem de Bruijn 
10381b784140SYing Xue int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1039db8dac20SDavid S. Miller {
1040db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1041db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
10421cedee13SAndrey Ignatov 	DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
1043e474995fSDavid S. Miller 	struct flowi4 fl4_stack;
1044b6f21b26SDavid S. Miller 	struct flowi4 *fl4;
1045db8dac20SDavid S. Miller 	int ulen = len;
1046db8dac20SDavid S. Miller 	struct ipcm_cookie ipc;
1047db8dac20SDavid S. Miller 	struct rtable *rt = NULL;
1048db8dac20SDavid S. Miller 	int free = 0;
1049db8dac20SDavid S. Miller 	int connected = 0;
1050db8dac20SDavid S. Miller 	__be32 daddr, faddr, saddr;
10510e26371dSGuillaume Nault 	u8 tos, scope;
1052db8dac20SDavid S. Miller 	__be16 dport;
1053db8dac20SDavid S. Miller 	int err, is_udplite = IS_UDPLITE(sk);
105481b36803SEric Dumazet 	int corkreq = udp_test_bit(CORK, sk) || msg->msg_flags & MSG_MORE;
1055db8dac20SDavid S. Miller 	int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
1056903ab86dSHerbert Xu 	struct sk_buff *skb;
1057f6d8bd05SEric Dumazet 	struct ip_options_data opt_copy;
1058db8dac20SDavid S. Miller 
1059db8dac20SDavid S. Miller 	if (len > 0xFFFF)
1060db8dac20SDavid S. Miller 		return -EMSGSIZE;
1061db8dac20SDavid S. Miller 
1062db8dac20SDavid S. Miller 	/*
1063db8dac20SDavid S. Miller 	 *	Check the flags.
1064db8dac20SDavid S. Miller 	 */
1065db8dac20SDavid S. Miller 
1066db8dac20SDavid S. Miller 	if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
1067db8dac20SDavid S. Miller 		return -EOPNOTSUPP;
1068db8dac20SDavid S. Miller 
1069903ab86dSHerbert Xu 	getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
1070903ab86dSHerbert Xu 
1071f5fca608SDavid S. Miller 	fl4 = &inet->cork.fl.u.ip4;
1072db8dac20SDavid S. Miller 	if (up->pending) {
1073db8dac20SDavid S. Miller 		/*
1074db8dac20SDavid S. Miller 		 * There are pending frames.
1075db8dac20SDavid S. Miller 		 * The socket lock must be held while it's corked.
1076db8dac20SDavid S. Miller 		 */
1077db8dac20SDavid S. Miller 		lock_sock(sk);
1078db8dac20SDavid S. Miller 		if (likely(up->pending)) {
1079db8dac20SDavid S. Miller 			if (unlikely(up->pending != AF_INET)) {
1080db8dac20SDavid S. Miller 				release_sock(sk);
1081db8dac20SDavid S. Miller 				return -EINVAL;
1082db8dac20SDavid S. Miller 			}
1083db8dac20SDavid S. Miller 			goto do_append_data;
1084db8dac20SDavid S. Miller 		}
1085db8dac20SDavid S. Miller 		release_sock(sk);
1086db8dac20SDavid S. Miller 	}
1087db8dac20SDavid S. Miller 	ulen += sizeof(struct udphdr);
1088db8dac20SDavid S. Miller 
1089db8dac20SDavid S. Miller 	/*
1090db8dac20SDavid S. Miller 	 *	Get and verify the address.
1091db8dac20SDavid S. Miller 	 */
10921cedee13SAndrey Ignatov 	if (usin) {
1093db8dac20SDavid S. Miller 		if (msg->msg_namelen < sizeof(*usin))
1094db8dac20SDavid S. Miller 			return -EINVAL;
1095db8dac20SDavid S. Miller 		if (usin->sin_family != AF_INET) {
1096db8dac20SDavid S. Miller 			if (usin->sin_family != AF_UNSPEC)
1097db8dac20SDavid S. Miller 				return -EAFNOSUPPORT;
1098db8dac20SDavid S. Miller 		}
1099db8dac20SDavid S. Miller 
1100db8dac20SDavid S. Miller 		daddr = usin->sin_addr.s_addr;
1101db8dac20SDavid S. Miller 		dport = usin->sin_port;
1102db8dac20SDavid S. Miller 		if (dport == 0)
1103db8dac20SDavid S. Miller 			return -EINVAL;
1104db8dac20SDavid S. Miller 	} else {
1105db8dac20SDavid S. Miller 		if (sk->sk_state != TCP_ESTABLISHED)
1106db8dac20SDavid S. Miller 			return -EDESTADDRREQ;
1107c720c7e8SEric Dumazet 		daddr = inet->inet_daddr;
1108c720c7e8SEric Dumazet 		dport = inet->inet_dport;
1109db8dac20SDavid S. Miller 		/* Open fast path for connected socket.
1110db8dac20SDavid S. Miller 		   Route will not be used, if at least one option is set.
1111db8dac20SDavid S. Miller 		 */
1112db8dac20SDavid S. Miller 		connected = 1;
1113db8dac20SDavid S. Miller 	}
1114c14ac945SSoheil Hassas Yeganeh 
111535178206SWillem de Bruijn 	ipcm_init_sk(&ipc, inet);
111618a419baSEric Dumazet 	ipc.gso_size = READ_ONCE(up->gso_size);
1117bf84a010SDaniel Borkmann 
1118db8dac20SDavid S. Miller 	if (msg->msg_controllen) {
11192e8de857SWillem de Bruijn 		err = udp_cmsg_send(sk, msg, &ipc.gso_size);
11202e8de857SWillem de Bruijn 		if (err > 0)
11212e8de857SWillem de Bruijn 			err = ip_cmsg_send(sk, msg, &ipc,
11222e8de857SWillem de Bruijn 					   sk->sk_family == AF_INET6);
11232e8de857SWillem de Bruijn 		if (unlikely(err < 0)) {
112491948309SEric Dumazet 			kfree(ipc.opt);
1125db8dac20SDavid S. Miller 			return err;
112691948309SEric Dumazet 		}
1127db8dac20SDavid S. Miller 		if (ipc.opt)
1128db8dac20SDavid S. Miller 			free = 1;
1129db8dac20SDavid S. Miller 		connected = 0;
1130db8dac20SDavid S. Miller 	}
1131f6d8bd05SEric Dumazet 	if (!ipc.opt) {
1132f6d8bd05SEric Dumazet 		struct ip_options_rcu *inet_opt;
1133f6d8bd05SEric Dumazet 
1134f6d8bd05SEric Dumazet 		rcu_read_lock();
1135f6d8bd05SEric Dumazet 		inet_opt = rcu_dereference(inet->inet_opt);
1136f6d8bd05SEric Dumazet 		if (inet_opt) {
1137f6d8bd05SEric Dumazet 			memcpy(&opt_copy, inet_opt,
1138f6d8bd05SEric Dumazet 			       sizeof(*inet_opt) + inet_opt->opt.optlen);
1139f6d8bd05SEric Dumazet 			ipc.opt = &opt_copy.opt;
1140f6d8bd05SEric Dumazet 		}
1141f6d8bd05SEric Dumazet 		rcu_read_unlock();
1142f6d8bd05SEric Dumazet 	}
1143db8dac20SDavid S. Miller 
11446fc88c35SDave Marchevsky 	if (cgroup_bpf_enabled(CGROUP_UDP4_SENDMSG) && !connected) {
11451cedee13SAndrey Ignatov 		err = BPF_CGROUP_RUN_PROG_UDP4_SENDMSG_LOCK(sk,
11461cedee13SAndrey Ignatov 					    (struct sockaddr *)usin, &ipc.addr);
11471cedee13SAndrey Ignatov 		if (err)
11481cedee13SAndrey Ignatov 			goto out_free;
11491cedee13SAndrey Ignatov 		if (usin) {
11501cedee13SAndrey Ignatov 			if (usin->sin_port == 0) {
11511cedee13SAndrey Ignatov 				/* BPF program set invalid port. Reject it. */
11521cedee13SAndrey Ignatov 				err = -EINVAL;
11531cedee13SAndrey Ignatov 				goto out_free;
11541cedee13SAndrey Ignatov 			}
11551cedee13SAndrey Ignatov 			daddr = usin->sin_addr.s_addr;
11561cedee13SAndrey Ignatov 			dport = usin->sin_port;
11571cedee13SAndrey Ignatov 		}
11581cedee13SAndrey Ignatov 	}
11591cedee13SAndrey Ignatov 
1160db8dac20SDavid S. Miller 	saddr = ipc.addr;
1161db8dac20SDavid S. Miller 	ipc.addr = faddr = daddr;
1162db8dac20SDavid S. Miller 
1163f6d8bd05SEric Dumazet 	if (ipc.opt && ipc.opt->opt.srr) {
11641b97013bSAndrey Ignatov 		if (!daddr) {
11651b97013bSAndrey Ignatov 			err = -EINVAL;
11661b97013bSAndrey Ignatov 			goto out_free;
11671b97013bSAndrey Ignatov 		}
1168f6d8bd05SEric Dumazet 		faddr = ipc.opt->opt.faddr;
1169db8dac20SDavid S. Miller 		connected = 0;
1170db8dac20SDavid S. Miller 	}
1171aa661581SFrancesco Fusco 	tos = get_rttos(&ipc, inet);
11720e26371dSGuillaume Nault 	scope = ip_sendmsg_scope(inet, &ipc, msg);
11730e26371dSGuillaume Nault 	if (scope == RT_SCOPE_LINK)
1174db8dac20SDavid S. Miller 		connected = 0;
1175db8dac20SDavid S. Miller 
1176db8dac20SDavid S. Miller 	if (ipv4_is_multicast(daddr)) {
1177854da991SRobert Shearman 		if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif))
1178db8dac20SDavid S. Miller 			ipc.oif = inet->mc_index;
1179db8dac20SDavid S. Miller 		if (!saddr)
1180db8dac20SDavid S. Miller 			saddr = inet->mc_addr;
1181db8dac20SDavid S. Miller 		connected = 0;
11829515a2e0SDavid Ahern 	} else if (!ipc.oif) {
118376e21053SErich E. Hoover 		ipc.oif = inet->uc_index;
11849515a2e0SDavid Ahern 	} else if (ipv4_is_lbcast(daddr) && inet->uc_index) {
11859515a2e0SDavid Ahern 		/* oif is set, packet is to local broadcast and
11862bdcc73cSRandy Dunlap 		 * uc_index is set. oif is most likely set
11879515a2e0SDavid Ahern 		 * by sk_bound_dev_if. If uc_index != oif check if the
11889515a2e0SDavid Ahern 		 * oif is an L3 master and uc_index is an L3 slave.
11899515a2e0SDavid Ahern 		 * If so, we want to allow the send using the uc_index.
11909515a2e0SDavid Ahern 		 */
11919515a2e0SDavid Ahern 		if (ipc.oif != inet->uc_index &&
11929515a2e0SDavid Ahern 		    ipc.oif == l3mdev_master_ifindex_by_index(sock_net(sk),
11939515a2e0SDavid Ahern 							      inet->uc_index)) {
11949515a2e0SDavid Ahern 			ipc.oif = inet->uc_index;
11959515a2e0SDavid Ahern 		}
11969515a2e0SDavid Ahern 	}
1197db8dac20SDavid S. Miller 
1198db8dac20SDavid S. Miller 	if (connected)
1199db8dac20SDavid S. Miller 		rt = (struct rtable *)sk_dst_check(sk, 0);
1200db8dac20SDavid S. Miller 
120151456b29SIan Morris 	if (!rt) {
120284a3aa00SPavel Emelyanov 		struct net *net = sock_net(sk);
12039a24abfaSDavid Ahern 		__u8 flow_flags = inet_sk_flowi_flags(sk);
120484a3aa00SPavel Emelyanov 
1205e474995fSDavid S. Miller 		fl4 = &fl4_stack;
12069a24abfaSDavid Ahern 
12070e26371dSGuillaume Nault 		flowi4_init_output(fl4, ipc.oif, ipc.sockc.mark, tos, scope,
12080e26371dSGuillaume Nault 				   sk->sk_protocol, flow_flags, faddr, saddr,
12090e26371dSGuillaume Nault 				   dport, inet->inet_sport, sk->sk_uid);
1210c0951cbcSDavid S. Miller 
12113df98d79SPaul Moore 		security_sk_classify_flow(sk, flowi4_to_flowi_common(fl4));
1212e474995fSDavid S. Miller 		rt = ip_route_output_flow(net, fl4, sk);
1213b23dd4feSDavid S. Miller 		if (IS_ERR(rt)) {
1214b23dd4feSDavid S. Miller 			err = PTR_ERR(rt);
121506dc94b1SDavid S. Miller 			rt = NULL;
1216db8dac20SDavid S. Miller 			if (err == -ENETUNREACH)
1217f1d8cba6SEric Dumazet 				IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
1218db8dac20SDavid S. Miller 			goto out;
1219db8dac20SDavid S. Miller 		}
1220db8dac20SDavid S. Miller 
1221db8dac20SDavid S. Miller 		err = -EACCES;
1222db8dac20SDavid S. Miller 		if ((rt->rt_flags & RTCF_BROADCAST) &&
1223db8dac20SDavid S. Miller 		    !sock_flag(sk, SOCK_BROADCAST))
1224db8dac20SDavid S. Miller 			goto out;
1225db8dac20SDavid S. Miller 		if (connected)
1226d8d1f30bSChangli Gao 			sk_dst_set(sk, dst_clone(&rt->dst));
1227db8dac20SDavid S. Miller 	}
1228db8dac20SDavid S. Miller 
1229db8dac20SDavid S. Miller 	if (msg->msg_flags&MSG_CONFIRM)
1230db8dac20SDavid S. Miller 		goto do_confirm;
1231db8dac20SDavid S. Miller back_from_confirm:
1232db8dac20SDavid S. Miller 
1233e474995fSDavid S. Miller 	saddr = fl4->saddr;
1234db8dac20SDavid S. Miller 	if (!ipc.addr)
1235e474995fSDavid S. Miller 		daddr = ipc.addr = fl4->daddr;
1236db8dac20SDavid S. Miller 
1237903ab86dSHerbert Xu 	/* Lockless fast path for the non-corking case. */
1238903ab86dSHerbert Xu 	if (!corkreq) {
12391cd7884dSWillem de Bruijn 		struct inet_cork cork;
12401cd7884dSWillem de Bruijn 
1241f69e6d13SAl Viro 		skb = ip_make_skb(sk, fl4, getfrag, msg, ulen,
1242903ab86dSHerbert Xu 				  sizeof(struct udphdr), &ipc, &rt,
12431cd7884dSWillem de Bruijn 				  &cork, msg->msg_flags);
1244903ab86dSHerbert Xu 		err = PTR_ERR(skb);
124550c3a487SYOSHIFUJI Hideaki / 吉藤英明 		if (!IS_ERR_OR_NULL(skb))
1246bec1f6f6SWillem de Bruijn 			err = udp_send_skb(skb, fl4, &cork);
1247903ab86dSHerbert Xu 		goto out;
1248903ab86dSHerbert Xu 	}
1249903ab86dSHerbert Xu 
1250db8dac20SDavid S. Miller 	lock_sock(sk);
1251db8dac20SDavid S. Miller 	if (unlikely(up->pending)) {
1252db8dac20SDavid S. Miller 		/* The socket is already corked while preparing it. */
1253db8dac20SDavid S. Miller 		/* ... which is an evident application bug. --ANK */
1254db8dac20SDavid S. Miller 		release_sock(sk);
1255db8dac20SDavid S. Miller 
1256197df02cSMatteo Croce 		net_dbg_ratelimited("socket already corked\n");
1257db8dac20SDavid S. Miller 		err = -EINVAL;
1258db8dac20SDavid S. Miller 		goto out;
1259db8dac20SDavid S. Miller 	}
1260db8dac20SDavid S. Miller 	/*
1261db8dac20SDavid S. Miller 	 *	Now cork the socket to pend data.
1262db8dac20SDavid S. Miller 	 */
1263b6f21b26SDavid S. Miller 	fl4 = &inet->cork.fl.u.ip4;
1264b6f21b26SDavid S. Miller 	fl4->daddr = daddr;
1265b6f21b26SDavid S. Miller 	fl4->saddr = saddr;
12669cce96dfSDavid S. Miller 	fl4->fl4_dport = dport;
12679cce96dfSDavid S. Miller 	fl4->fl4_sport = inet->inet_sport;
1268db8dac20SDavid S. Miller 	up->pending = AF_INET;
1269db8dac20SDavid S. Miller 
1270db8dac20SDavid S. Miller do_append_data:
1271db8dac20SDavid S. Miller 	up->len += ulen;
1272f69e6d13SAl Viro 	err = ip_append_data(sk, fl4, getfrag, msg, ulen,
12732e77d89bSEric Dumazet 			     sizeof(struct udphdr), &ipc, &rt,
1274db8dac20SDavid S. Miller 			     corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
1275db8dac20SDavid S. Miller 	if (err)
1276db8dac20SDavid S. Miller 		udp_flush_pending_frames(sk);
1277db8dac20SDavid S. Miller 	else if (!corkreq)
1278db8dac20SDavid S. Miller 		err = udp_push_pending_frames(sk);
1279db8dac20SDavid S. Miller 	else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
1280db8dac20SDavid S. Miller 		up->pending = 0;
1281db8dac20SDavid S. Miller 	release_sock(sk);
1282db8dac20SDavid S. Miller 
1283db8dac20SDavid S. Miller out:
1284db8dac20SDavid S. Miller 	ip_rt_put(rt);
12851b97013bSAndrey Ignatov out_free:
1286db8dac20SDavid S. Miller 	if (free)
1287db8dac20SDavid S. Miller 		kfree(ipc.opt);
1288db8dac20SDavid S. Miller 	if (!err)
1289db8dac20SDavid S. Miller 		return len;
1290db8dac20SDavid S. Miller 	/*
1291db8dac20SDavid S. Miller 	 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space.  Reporting
1292db8dac20SDavid S. Miller 	 * ENOBUFS might not be good (it's not tunable per se), but otherwise
1293db8dac20SDavid S. Miller 	 * we don't have a good statistic (IpOutDiscards but it can be too many
1294db8dac20SDavid S. Miller 	 * things).  We could add another new stat but at least for now that
1295db8dac20SDavid S. Miller 	 * seems like overkill.
1296db8dac20SDavid S. Miller 	 */
1297db8dac20SDavid S. Miller 	if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
12986aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
1299629ca23cSPavel Emelyanov 			      UDP_MIB_SNDBUFERRORS, is_udplite);
1300db8dac20SDavid S. Miller 	}
1301db8dac20SDavid S. Miller 	return err;
1302db8dac20SDavid S. Miller 
1303db8dac20SDavid S. Miller do_confirm:
13040dec879fSJulian Anastasov 	if (msg->msg_flags & MSG_PROBE)
13050dec879fSJulian Anastasov 		dst_confirm_neigh(&rt->dst, &fl4->daddr);
1306db8dac20SDavid S. Miller 	if (!(msg->msg_flags&MSG_PROBE) || len)
1307db8dac20SDavid S. Miller 		goto back_from_confirm;
1308db8dac20SDavid S. Miller 	err = 0;
1309db8dac20SDavid S. Miller 	goto out;
1310db8dac20SDavid S. Miller }
1311c482c568SEric Dumazet EXPORT_SYMBOL(udp_sendmsg);
1312db8dac20SDavid S. Miller 
13131d7e4538SDavid Howells void udp_splice_eof(struct socket *sock)
13141d7e4538SDavid Howells {
13151d7e4538SDavid Howells 	struct sock *sk = sock->sk;
13161d7e4538SDavid Howells 	struct udp_sock *up = udp_sk(sk);
13171d7e4538SDavid Howells 
131881b36803SEric Dumazet 	if (!up->pending || udp_test_bit(CORK, sk))
13191d7e4538SDavid Howells 		return;
13201d7e4538SDavid Howells 
13211d7e4538SDavid Howells 	lock_sock(sk);
132281b36803SEric Dumazet 	if (up->pending && !udp_test_bit(CORK, sk))
13231d7e4538SDavid Howells 		udp_push_pending_frames(sk);
13241d7e4538SDavid Howells 	release_sock(sk);
13251d7e4538SDavid Howells }
13261d7e4538SDavid Howells EXPORT_SYMBOL_GPL(udp_splice_eof);
13271d7e4538SDavid Howells 
1328dce4551cSPaolo Abeni #define UDP_SKB_IS_STATELESS 0x80000000
1329dce4551cSPaolo Abeni 
1330677bf08cSFlorian Westphal /* all head states (dst, sk, nf conntrack) except skb extensions are
1331677bf08cSFlorian Westphal  * cleared by udp_rcv().
1332677bf08cSFlorian Westphal  *
1333677bf08cSFlorian Westphal  * We need to preserve secpath, if present, to eventually process
1334677bf08cSFlorian Westphal  * IP_CMSG_PASSSEC at recvmsg() time.
1335677bf08cSFlorian Westphal  *
1336677bf08cSFlorian Westphal  * Other extensions can be cleared.
1337677bf08cSFlorian Westphal  */
1338677bf08cSFlorian Westphal static bool udp_try_make_stateless(struct sk_buff *skb)
1339677bf08cSFlorian Westphal {
1340677bf08cSFlorian Westphal 	if (!skb_has_extensions(skb))
1341677bf08cSFlorian Westphal 		return true;
1342677bf08cSFlorian Westphal 
1343677bf08cSFlorian Westphal 	if (!secpath_exists(skb)) {
1344677bf08cSFlorian Westphal 		skb_ext_reset(skb);
1345677bf08cSFlorian Westphal 		return true;
1346677bf08cSFlorian Westphal 	}
1347677bf08cSFlorian Westphal 
1348677bf08cSFlorian Westphal 	return false;
1349677bf08cSFlorian Westphal }
1350677bf08cSFlorian Westphal 
1351b65ac446SPaolo Abeni static void udp_set_dev_scratch(struct sk_buff *skb)
1352b65ac446SPaolo Abeni {
1353dce4551cSPaolo Abeni 	struct udp_dev_scratch *scratch = udp_skb_scratch(skb);
1354b65ac446SPaolo Abeni 
1355b65ac446SPaolo Abeni 	BUILD_BUG_ON(sizeof(struct udp_dev_scratch) > sizeof(long));
1356dce4551cSPaolo Abeni 	scratch->_tsize_state = skb->truesize;
1357dce4551cSPaolo Abeni #if BITS_PER_LONG == 64
1358b65ac446SPaolo Abeni 	scratch->len = skb->len;
1359b65ac446SPaolo Abeni 	scratch->csum_unnecessary = !!skb_csum_unnecessary(skb);
1360b65ac446SPaolo Abeni 	scratch->is_linear = !skb_is_nonlinear(skb);
1361b65ac446SPaolo Abeni #endif
1362677bf08cSFlorian Westphal 	if (udp_try_make_stateless(skb))
1363dce4551cSPaolo Abeni 		scratch->_tsize_state |= UDP_SKB_IS_STATELESS;
1364dce4551cSPaolo Abeni }
1365dce4551cSPaolo Abeni 
1366a793183cSEric Dumazet static void udp_skb_csum_unnecessary_set(struct sk_buff *skb)
1367a793183cSEric Dumazet {
1368a793183cSEric Dumazet 	/* We come here after udp_lib_checksum_complete() returned 0.
1369a793183cSEric Dumazet 	 * This means that __skb_checksum_complete() might have
1370a793183cSEric Dumazet 	 * set skb->csum_valid to 1.
1371a793183cSEric Dumazet 	 * On 64bit platforms, we can set csum_unnecessary
1372a793183cSEric Dumazet 	 * to true, but only if the skb is not shared.
1373a793183cSEric Dumazet 	 */
1374a793183cSEric Dumazet #if BITS_PER_LONG == 64
1375a793183cSEric Dumazet 	if (!skb_shared(skb))
1376a793183cSEric Dumazet 		udp_skb_scratch(skb)->csum_unnecessary = true;
1377a793183cSEric Dumazet #endif
1378a793183cSEric Dumazet }
1379a793183cSEric Dumazet 
1380dce4551cSPaolo Abeni static int udp_skb_truesize(struct sk_buff *skb)
1381dce4551cSPaolo Abeni {
1382dce4551cSPaolo Abeni 	return udp_skb_scratch(skb)->_tsize_state & ~UDP_SKB_IS_STATELESS;
1383dce4551cSPaolo Abeni }
1384dce4551cSPaolo Abeni 
1385dce4551cSPaolo Abeni static bool udp_skb_has_head_state(struct sk_buff *skb)
1386dce4551cSPaolo Abeni {
1387dce4551cSPaolo Abeni 	return !(udp_skb_scratch(skb)->_tsize_state & UDP_SKB_IS_STATELESS);
1388dce4551cSPaolo Abeni }
1389b65ac446SPaolo Abeni 
13907c13f97fSPaolo Abeni /* fully reclaim rmem/fwd memory allocated for skb */
13916dfb4367SPaolo Abeni static void udp_rmem_release(struct sock *sk, int size, int partial,
13926dfb4367SPaolo Abeni 			     bool rx_queue_lock_held)
1393f970bd9eSPaolo Abeni {
13946b229cf7SEric Dumazet 	struct udp_sock *up = udp_sk(sk);
13952276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue;
1396f970bd9eSPaolo Abeni 	int amt;
1397f970bd9eSPaolo Abeni 
13986b229cf7SEric Dumazet 	if (likely(partial)) {
13996b229cf7SEric Dumazet 		up->forward_deficit += size;
14006b229cf7SEric Dumazet 		size = up->forward_deficit;
14018a3854c7SPaolo Abeni 		if (size < READ_ONCE(up->forward_threshold) &&
1402d39ca259SPaolo Abeni 		    !skb_queue_empty(&up->reader_queue))
14036b229cf7SEric Dumazet 			return;
14046b229cf7SEric Dumazet 	} else {
14056b229cf7SEric Dumazet 		size += up->forward_deficit;
14066b229cf7SEric Dumazet 	}
14076b229cf7SEric Dumazet 	up->forward_deficit = 0;
14086b229cf7SEric Dumazet 
14096dfb4367SPaolo Abeni 	/* acquire the sk_receive_queue for fwd allocated memory scheduling,
14106dfb4367SPaolo Abeni 	 * if the called don't held it already
14116dfb4367SPaolo Abeni 	 */
14122276f58aSPaolo Abeni 	sk_queue = &sk->sk_receive_queue;
14136dfb4367SPaolo Abeni 	if (!rx_queue_lock_held)
14142276f58aSPaolo Abeni 		spin_lock(&sk_queue->lock);
14152276f58aSPaolo Abeni 
14166dfb4367SPaolo Abeni 
14175e6300e7SEric Dumazet 	sk_forward_alloc_add(sk, size);
1418100fdd1fSEric Dumazet 	amt = (sk->sk_forward_alloc - partial) & ~(PAGE_SIZE - 1);
14195e6300e7SEric Dumazet 	sk_forward_alloc_add(sk, -amt);
1420f970bd9eSPaolo Abeni 
1421f970bd9eSPaolo Abeni 	if (amt)
1422100fdd1fSEric Dumazet 		__sk_mem_reduce_allocated(sk, amt >> PAGE_SHIFT);
142302ab0d13SEric Dumazet 
142402ab0d13SEric Dumazet 	atomic_sub(size, &sk->sk_rmem_alloc);
14252276f58aSPaolo Abeni 
14262276f58aSPaolo Abeni 	/* this can save us from acquiring the rx queue lock on next receive */
14272276f58aSPaolo Abeni 	skb_queue_splice_tail_init(sk_queue, &up->reader_queue);
14282276f58aSPaolo Abeni 
14296dfb4367SPaolo Abeni 	if (!rx_queue_lock_held)
14302276f58aSPaolo Abeni 		spin_unlock(&sk_queue->lock);
1431f970bd9eSPaolo Abeni }
1432f970bd9eSPaolo Abeni 
14332276f58aSPaolo Abeni /* Note: called with reader_queue.lock held.
1434c84d9490SEric Dumazet  * Instead of using skb->truesize here, find a copy of it in skb->dev_scratch
1435c84d9490SEric Dumazet  * This avoids a cache line miss while receive_queue lock is held.
1436c84d9490SEric Dumazet  * Look at __udp_enqueue_schedule_skb() to find where this copy is done.
1437c84d9490SEric Dumazet  */
14387c13f97fSPaolo Abeni void udp_skb_destructor(struct sock *sk, struct sk_buff *skb)
1439f970bd9eSPaolo Abeni {
1440b65ac446SPaolo Abeni 	prefetch(&skb->data);
1441b65ac446SPaolo Abeni 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, false);
1442f970bd9eSPaolo Abeni }
14437c13f97fSPaolo Abeni EXPORT_SYMBOL(udp_skb_destructor);
1444f970bd9eSPaolo Abeni 
14456dfb4367SPaolo Abeni /* as above, but the caller held the rx queue lock, too */
144664f5102dSColin Ian King static void udp_skb_dtor_locked(struct sock *sk, struct sk_buff *skb)
14476dfb4367SPaolo Abeni {
1448b65ac446SPaolo Abeni 	prefetch(&skb->data);
1449b65ac446SPaolo Abeni 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, true);
14506dfb4367SPaolo Abeni }
14516dfb4367SPaolo Abeni 
14524b272750SEric Dumazet /* Idea of busylocks is to let producers grab an extra spinlock
14534b272750SEric Dumazet  * to relieve pressure on the receive_queue spinlock shared by consumer.
14544b272750SEric Dumazet  * Under flood, this means that only one producer can be in line
14554b272750SEric Dumazet  * trying to acquire the receive_queue spinlock.
14564b272750SEric Dumazet  * These busylock can be allocated on a per cpu manner, instead of a
14574b272750SEric Dumazet  * per socket one (that would consume a cache line per socket)
14584b272750SEric Dumazet  */
14594b272750SEric Dumazet static int udp_busylocks_log __read_mostly;
14604b272750SEric Dumazet static spinlock_t *udp_busylocks __read_mostly;
14614b272750SEric Dumazet 
14624b272750SEric Dumazet static spinlock_t *busylock_acquire(void *ptr)
14634b272750SEric Dumazet {
14644b272750SEric Dumazet 	spinlock_t *busy;
14654b272750SEric Dumazet 
14664b272750SEric Dumazet 	busy = udp_busylocks + hash_ptr(ptr, udp_busylocks_log);
14674b272750SEric Dumazet 	spin_lock(busy);
14684b272750SEric Dumazet 	return busy;
14694b272750SEric Dumazet }
14704b272750SEric Dumazet 
14714b272750SEric Dumazet static void busylock_release(spinlock_t *busy)
14724b272750SEric Dumazet {
14734b272750SEric Dumazet 	if (busy)
14744b272750SEric Dumazet 		spin_unlock(busy);
14754b272750SEric Dumazet }
14764b272750SEric Dumazet 
1477fd9c31f8SJason Xing static int udp_rmem_schedule(struct sock *sk, int size)
1478fd9c31f8SJason Xing {
1479fd9c31f8SJason Xing 	int delta;
1480fd9c31f8SJason Xing 
1481fd9c31f8SJason Xing 	delta = size - sk->sk_forward_alloc;
1482fd9c31f8SJason Xing 	if (delta > 0 && !__sk_mem_schedule(sk, delta, SK_MEM_RECV))
1483fd9c31f8SJason Xing 		return -ENOBUFS;
1484fd9c31f8SJason Xing 
1485fd9c31f8SJason Xing 	return 0;
1486fd9c31f8SJason Xing }
1487fd9c31f8SJason Xing 
1488f970bd9eSPaolo Abeni int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb)
1489f970bd9eSPaolo Abeni {
1490f970bd9eSPaolo Abeni 	struct sk_buff_head *list = &sk->sk_receive_queue;
1491fd9c31f8SJason Xing 	int rmem, err = -ENOMEM;
14924b272750SEric Dumazet 	spinlock_t *busy = NULL;
1493c8c8b127SEric Dumazet 	int size;
1494f970bd9eSPaolo Abeni 
1495f970bd9eSPaolo Abeni 	/* try to avoid the costly atomic add/sub pair when the receive
1496f970bd9eSPaolo Abeni 	 * queue is full; always allow at least a packet
1497f970bd9eSPaolo Abeni 	 */
1498f970bd9eSPaolo Abeni 	rmem = atomic_read(&sk->sk_rmem_alloc);
1499363dc73aSPaolo Abeni 	if (rmem > sk->sk_rcvbuf)
1500f970bd9eSPaolo Abeni 		goto drop;
1501f970bd9eSPaolo Abeni 
1502c8c8b127SEric Dumazet 	/* Under mem pressure, it might be helpful to help udp_recvmsg()
1503c8c8b127SEric Dumazet 	 * having linear skbs :
1504c8c8b127SEric Dumazet 	 * - Reduce memory overhead and thus increase receive queue capacity
1505c8c8b127SEric Dumazet 	 * - Less cache line misses at copyout() time
1506c8c8b127SEric Dumazet 	 * - Less work at consume_skb() (less alien page frag freeing)
1507c8c8b127SEric Dumazet 	 */
15084b272750SEric Dumazet 	if (rmem > (sk->sk_rcvbuf >> 1)) {
1509c8c8b127SEric Dumazet 		skb_condense(skb);
15104b272750SEric Dumazet 
15114b272750SEric Dumazet 		busy = busylock_acquire(sk);
15124b272750SEric Dumazet 	}
1513c8c8b127SEric Dumazet 	size = skb->truesize;
1514b65ac446SPaolo Abeni 	udp_set_dev_scratch(skb);
1515c8c8b127SEric Dumazet 
1516f970bd9eSPaolo Abeni 	/* we drop only if the receive buf is full and the receive
1517f970bd9eSPaolo Abeni 	 * queue contains some other skb
1518f970bd9eSPaolo Abeni 	 */
1519f970bd9eSPaolo Abeni 	rmem = atomic_add_return(size, &sk->sk_rmem_alloc);
1520feed8a4fSAntonio Messina 	if (rmem > (size + (unsigned int)sk->sk_rcvbuf))
1521f970bd9eSPaolo Abeni 		goto uncharge_drop;
1522f970bd9eSPaolo Abeni 
1523f970bd9eSPaolo Abeni 	spin_lock(&list->lock);
1524fd9c31f8SJason Xing 	err = udp_rmem_schedule(sk, size);
1525fd9c31f8SJason Xing 	if (err) {
1526f970bd9eSPaolo Abeni 		spin_unlock(&list->lock);
1527f970bd9eSPaolo Abeni 		goto uncharge_drop;
1528f970bd9eSPaolo Abeni 	}
1529f970bd9eSPaolo Abeni 
15305e6300e7SEric Dumazet 	sk_forward_alloc_add(sk, -size);
1531f970bd9eSPaolo Abeni 
15327c13f97fSPaolo Abeni 	/* no need to setup a destructor, we will explicitly release the
15337c13f97fSPaolo Abeni 	 * forward allocated memory on dequeue
15347c13f97fSPaolo Abeni 	 */
1535f970bd9eSPaolo Abeni 	sock_skb_set_dropcount(sk, skb);
1536f970bd9eSPaolo Abeni 
1537f970bd9eSPaolo Abeni 	__skb_queue_tail(list, skb);
1538f970bd9eSPaolo Abeni 	spin_unlock(&list->lock);
1539f970bd9eSPaolo Abeni 
1540f970bd9eSPaolo Abeni 	if (!sock_flag(sk, SOCK_DEAD))
15410558e167SPaolo Abeni 		INDIRECT_CALL_1(sk->sk_data_ready, sock_def_readable, sk);
1542f970bd9eSPaolo Abeni 
15434b272750SEric Dumazet 	busylock_release(busy);
1544f970bd9eSPaolo Abeni 	return 0;
1545f970bd9eSPaolo Abeni 
1546f970bd9eSPaolo Abeni uncharge_drop:
1547f970bd9eSPaolo Abeni 	atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
1548f970bd9eSPaolo Abeni 
1549f970bd9eSPaolo Abeni drop:
1550f970bd9eSPaolo Abeni 	atomic_inc(&sk->sk_drops);
15514b272750SEric Dumazet 	busylock_release(busy);
1552f970bd9eSPaolo Abeni 	return err;
1553f970bd9eSPaolo Abeni }
1554f970bd9eSPaolo Abeni EXPORT_SYMBOL_GPL(__udp_enqueue_schedule_skb);
1555f970bd9eSPaolo Abeni 
1556d38afeecSKuniyuki Iwashima void udp_destruct_common(struct sock *sk)
1557f970bd9eSPaolo Abeni {
1558f970bd9eSPaolo Abeni 	/* reclaim completely the forward allocated memory */
15592276f58aSPaolo Abeni 	struct udp_sock *up = udp_sk(sk);
15607c13f97fSPaolo Abeni 	unsigned int total = 0;
15617c13f97fSPaolo Abeni 	struct sk_buff *skb;
15627c13f97fSPaolo Abeni 
15632276f58aSPaolo Abeni 	skb_queue_splice_tail_init(&sk->sk_receive_queue, &up->reader_queue);
15642276f58aSPaolo Abeni 	while ((skb = __skb_dequeue(&up->reader_queue)) != NULL) {
15657c13f97fSPaolo Abeni 		total += skb->truesize;
15667c13f97fSPaolo Abeni 		kfree_skb(skb);
15677c13f97fSPaolo Abeni 	}
15686dfb4367SPaolo Abeni 	udp_rmem_release(sk, total, 0, true);
1569d38afeecSKuniyuki Iwashima }
1570d38afeecSKuniyuki Iwashima EXPORT_SYMBOL_GPL(udp_destruct_common);
15717c13f97fSPaolo Abeni 
1572d38afeecSKuniyuki Iwashima static void udp_destruct_sock(struct sock *sk)
1573d38afeecSKuniyuki Iwashima {
1574d38afeecSKuniyuki Iwashima 	udp_destruct_common(sk);
1575f970bd9eSPaolo Abeni 	inet_sock_destruct(sk);
1576f970bd9eSPaolo Abeni }
1577f970bd9eSPaolo Abeni 
1578f970bd9eSPaolo Abeni int udp_init_sock(struct sock *sk)
1579f970bd9eSPaolo Abeni {
15808a3854c7SPaolo Abeni 	udp_lib_init_sock(sk);
1581f970bd9eSPaolo Abeni 	sk->sk_destruct = udp_destruct_sock;
1582e993ffe3SPavel Begunkov 	set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
1583f970bd9eSPaolo Abeni 	return 0;
1584f970bd9eSPaolo Abeni }
1585f970bd9eSPaolo Abeni 
1586f970bd9eSPaolo Abeni void skb_consume_udp(struct sock *sk, struct sk_buff *skb, int len)
1587f970bd9eSPaolo Abeni {
1588f970bd9eSPaolo Abeni 	if (unlikely(READ_ONCE(sk->sk_peek_off) >= 0)) {
1589f970bd9eSPaolo Abeni 		bool slow = lock_sock_fast(sk);
1590f970bd9eSPaolo Abeni 
1591f970bd9eSPaolo Abeni 		sk_peek_offset_bwd(sk, len);
1592f970bd9eSPaolo Abeni 		unlock_sock_fast(sk, slow);
1593f970bd9eSPaolo Abeni 	}
15940a463c78SPaolo Abeni 
1595ca2c1418SPaolo Abeni 	if (!skb_unref(skb))
1596ca2c1418SPaolo Abeni 		return;
1597ca2c1418SPaolo Abeni 
1598dce4551cSPaolo Abeni 	/* In the more common cases we cleared the head states previously,
1599dce4551cSPaolo Abeni 	 * see __udp_queue_rcv_skb().
16000ddf3fb2SPaolo Abeni 	 */
1601dce4551cSPaolo Abeni 	if (unlikely(udp_skb_has_head_state(skb)))
16020ddf3fb2SPaolo Abeni 		skb_release_head_state(skb);
1603ca2c1418SPaolo Abeni 	__consume_stateless_skb(skb);
1604f970bd9eSPaolo Abeni }
1605f970bd9eSPaolo Abeni EXPORT_SYMBOL_GPL(skb_consume_udp);
1606f970bd9eSPaolo Abeni 
16072276f58aSPaolo Abeni static struct sk_buff *__first_packet_length(struct sock *sk,
16082276f58aSPaolo Abeni 					     struct sk_buff_head *rcvq,
16092276f58aSPaolo Abeni 					     int *total)
16102276f58aSPaolo Abeni {
16112276f58aSPaolo Abeni 	struct sk_buff *skb;
16122276f58aSPaolo Abeni 
16139bd780f5SPaolo Abeni 	while ((skb = skb_peek(rcvq)) != NULL) {
16149bd780f5SPaolo Abeni 		if (udp_lib_checksum_complete(skb)) {
16152276f58aSPaolo Abeni 			__UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS,
16162276f58aSPaolo Abeni 					IS_UDPLITE(sk));
16172276f58aSPaolo Abeni 			__UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS,
16182276f58aSPaolo Abeni 					IS_UDPLITE(sk));
16192276f58aSPaolo Abeni 			atomic_inc(&sk->sk_drops);
16202276f58aSPaolo Abeni 			__skb_unlink(skb, rcvq);
16212276f58aSPaolo Abeni 			*total += skb->truesize;
16222276f58aSPaolo Abeni 			kfree_skb(skb);
16239bd780f5SPaolo Abeni 		} else {
1624a793183cSEric Dumazet 			udp_skb_csum_unnecessary_set(skb);
16259bd780f5SPaolo Abeni 			break;
16269bd780f5SPaolo Abeni 		}
16272276f58aSPaolo Abeni 	}
16282276f58aSPaolo Abeni 	return skb;
16292276f58aSPaolo Abeni }
16302276f58aSPaolo Abeni 
163185584672SEric Dumazet /**
163285584672SEric Dumazet  *	first_packet_length	- return length of first packet in receive queue
163385584672SEric Dumazet  *	@sk: socket
163485584672SEric Dumazet  *
163585584672SEric Dumazet  *	Drops all bad checksum frames, until a valid one is found.
1636e83c6744SEric Dumazet  *	Returns the length of found skb, or -1 if none is found.
163785584672SEric Dumazet  */
1638e83c6744SEric Dumazet static int first_packet_length(struct sock *sk)
163985584672SEric Dumazet {
16402276f58aSPaolo Abeni 	struct sk_buff_head *rcvq = &udp_sk(sk)->reader_queue;
16412276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
164285584672SEric Dumazet 	struct sk_buff *skb;
16437c13f97fSPaolo Abeni 	int total = 0;
1644e83c6744SEric Dumazet 	int res;
164585584672SEric Dumazet 
164685584672SEric Dumazet 	spin_lock_bh(&rcvq->lock);
16472276f58aSPaolo Abeni 	skb = __first_packet_length(sk, rcvq, &total);
1648137a0dbeSEric Dumazet 	if (!skb && !skb_queue_empty_lockless(sk_queue)) {
16492276f58aSPaolo Abeni 		spin_lock(&sk_queue->lock);
16502276f58aSPaolo Abeni 		skb_queue_splice_tail_init(sk_queue, rcvq);
16512276f58aSPaolo Abeni 		spin_unlock(&sk_queue->lock);
16522276f58aSPaolo Abeni 
16532276f58aSPaolo Abeni 		skb = __first_packet_length(sk, rcvq, &total);
165485584672SEric Dumazet 	}
1655e83c6744SEric Dumazet 	res = skb ? skb->len : -1;
16567c13f97fSPaolo Abeni 	if (total)
16576dfb4367SPaolo Abeni 		udp_rmem_release(sk, total, 1, false);
165885584672SEric Dumazet 	spin_unlock_bh(&rcvq->lock);
165985584672SEric Dumazet 	return res;
166085584672SEric Dumazet }
166185584672SEric Dumazet 
16621da177e4SLinus Torvalds /*
16631da177e4SLinus Torvalds  *	IOCTL requests applicable to the UDP protocol
16641da177e4SLinus Torvalds  */
16651da177e4SLinus Torvalds 
1666e1d001faSBreno Leitao int udp_ioctl(struct sock *sk, int cmd, int *karg)
16671da177e4SLinus Torvalds {
16686516c655SStephen Hemminger 	switch (cmd) {
16691da177e4SLinus Torvalds 	case SIOCOUTQ:
16701da177e4SLinus Torvalds 	{
1671e1d001faSBreno Leitao 		*karg = sk_wmem_alloc_get(sk);
1672e1d001faSBreno Leitao 		return 0;
16731da177e4SLinus Torvalds 	}
16741da177e4SLinus Torvalds 
16751da177e4SLinus Torvalds 	case SIOCINQ:
16761da177e4SLinus Torvalds 	{
1677e1d001faSBreno Leitao 		*karg = max_t(int, 0, first_packet_length(sk));
1678e1d001faSBreno Leitao 		return 0;
16791da177e4SLinus Torvalds 	}
16801da177e4SLinus Torvalds 
16811da177e4SLinus Torvalds 	default:
16821da177e4SLinus Torvalds 		return -ENOIOCTLCMD;
16831da177e4SLinus Torvalds 	}
16846516c655SStephen Hemminger 
16856516c655SStephen Hemminger 	return 0;
16861da177e4SLinus Torvalds }
1687c482c568SEric Dumazet EXPORT_SYMBOL(udp_ioctl);
16881da177e4SLinus Torvalds 
16892276f58aSPaolo Abeni struct sk_buff *__skb_recv_udp(struct sock *sk, unsigned int flags,
1690ec095263SOliver Hartkopp 			       int *off, int *err)
16912276f58aSPaolo Abeni {
16922276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
16932276f58aSPaolo Abeni 	struct sk_buff_head *queue;
16942276f58aSPaolo Abeni 	struct sk_buff *last;
16952276f58aSPaolo Abeni 	long timeo;
16962276f58aSPaolo Abeni 	int error;
16972276f58aSPaolo Abeni 
16982276f58aSPaolo Abeni 	queue = &udp_sk(sk)->reader_queue;
16992276f58aSPaolo Abeni 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
17002276f58aSPaolo Abeni 	do {
17012276f58aSPaolo Abeni 		struct sk_buff *skb;
17022276f58aSPaolo Abeni 
17032276f58aSPaolo Abeni 		error = sock_error(sk);
17042276f58aSPaolo Abeni 		if (error)
17052276f58aSPaolo Abeni 			break;
17062276f58aSPaolo Abeni 
17072276f58aSPaolo Abeni 		error = -EAGAIN;
17082276f58aSPaolo Abeni 		do {
17092276f58aSPaolo Abeni 			spin_lock_bh(&queue->lock);
1710e427cad6SPaolo Abeni 			skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1711e427cad6SPaolo Abeni 							err, &last);
17122276f58aSPaolo Abeni 			if (skb) {
1713e427cad6SPaolo Abeni 				if (!(flags & MSG_PEEK))
1714e427cad6SPaolo Abeni 					udp_skb_destructor(sk, skb);
17152276f58aSPaolo Abeni 				spin_unlock_bh(&queue->lock);
17162276f58aSPaolo Abeni 				return skb;
17172276f58aSPaolo Abeni 			}
17182276f58aSPaolo Abeni 
1719137a0dbeSEric Dumazet 			if (skb_queue_empty_lockless(sk_queue)) {
17202276f58aSPaolo Abeni 				spin_unlock_bh(&queue->lock);
17212276f58aSPaolo Abeni 				goto busy_check;
17222276f58aSPaolo Abeni 			}
17232276f58aSPaolo Abeni 
17246dfb4367SPaolo Abeni 			/* refill the reader queue and walk it again
17256dfb4367SPaolo Abeni 			 * keep both queues locked to avoid re-acquiring
17266dfb4367SPaolo Abeni 			 * the sk_receive_queue lock if fwd memory scheduling
17276dfb4367SPaolo Abeni 			 * is needed.
17286dfb4367SPaolo Abeni 			 */
17292276f58aSPaolo Abeni 			spin_lock(&sk_queue->lock);
17302276f58aSPaolo Abeni 			skb_queue_splice_tail_init(sk_queue, queue);
17312276f58aSPaolo Abeni 
1732e427cad6SPaolo Abeni 			skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1733e427cad6SPaolo Abeni 							err, &last);
1734e427cad6SPaolo Abeni 			if (skb && !(flags & MSG_PEEK))
1735e427cad6SPaolo Abeni 				udp_skb_dtor_locked(sk, skb);
17366dfb4367SPaolo Abeni 			spin_unlock(&sk_queue->lock);
17372276f58aSPaolo Abeni 			spin_unlock_bh(&queue->lock);
1738de321ed3SAndrey Vagin 			if (skb)
17392276f58aSPaolo Abeni 				return skb;
17402276f58aSPaolo Abeni 
17412276f58aSPaolo Abeni busy_check:
17422276f58aSPaolo Abeni 			if (!sk_can_busy_loop(sk))
17432276f58aSPaolo Abeni 				break;
17442276f58aSPaolo Abeni 
17452276f58aSPaolo Abeni 			sk_busy_loop(sk, flags & MSG_DONTWAIT);
1746137a0dbeSEric Dumazet 		} while (!skb_queue_empty_lockless(sk_queue));
17472276f58aSPaolo Abeni 
17482276f58aSPaolo Abeni 		/* sk_queue is empty, reader_queue may contain peeked packets */
17492276f58aSPaolo Abeni 	} while (timeo &&
1750b50b0580SSabrina Dubroca 		 !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,
1751b50b0580SSabrina Dubroca 					      &error, &timeo,
17522276f58aSPaolo Abeni 					      (struct sk_buff *)sk_queue));
17532276f58aSPaolo Abeni 
17542276f58aSPaolo Abeni 	*err = error;
17552276f58aSPaolo Abeni 	return NULL;
17562276f58aSPaolo Abeni }
17577e823644SJiri Kosina EXPORT_SYMBOL(__skb_recv_udp);
17582276f58aSPaolo Abeni 
1759965b57b4SCong Wang int udp_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
1760d7f57118SCong Wang {
1761d7f57118SCong Wang 	struct sk_buff *skb;
176278fa0d61SJohn Fastabend 	int err;
1763d7f57118SCong Wang 
176431f1fbcbSPeilin Ye try_again:
1765ec095263SOliver Hartkopp 	skb = skb_recv_udp(sk, MSG_DONTWAIT, &err);
1766d7f57118SCong Wang 	if (!skb)
1767d7f57118SCong Wang 		return err;
1768099f896fSCong Wang 
1769099f896fSCong Wang 	if (udp_lib_checksum_complete(skb)) {
177031f1fbcbSPeilin Ye 		int is_udplite = IS_UDPLITE(sk);
177131f1fbcbSPeilin Ye 		struct net *net = sock_net(sk);
177231f1fbcbSPeilin Ye 
177331f1fbcbSPeilin Ye 		__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, is_udplite);
177431f1fbcbSPeilin Ye 		__UDP_INC_STATS(net, UDP_MIB_INERRORS, is_udplite);
1775099f896fSCong Wang 		atomic_inc(&sk->sk_drops);
1776099f896fSCong Wang 		kfree_skb(skb);
177731f1fbcbSPeilin Ye 		goto try_again;
1778099f896fSCong Wang 	}
1779099f896fSCong Wang 
1780db39dfdcSPeilin Ye 	WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk));
178178fa0d61SJohn Fastabend 	return recv_actor(sk, skb);
1782d7f57118SCong Wang }
1783965b57b4SCong Wang EXPORT_SYMBOL(udp_read_skb);
1784d7f57118SCong Wang 
1785db8dac20SDavid S. Miller /*
1786db8dac20SDavid S. Miller  * 	This should be easy, if there is something there we
1787db8dac20SDavid S. Miller  * 	return it, otherwise we block.
1788db8dac20SDavid S. Miller  */
1789db8dac20SDavid S. Miller 
1790ec095263SOliver Hartkopp int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags,
1791ec095263SOliver Hartkopp 		int *addr_len)
1792db8dac20SDavid S. Miller {
1793db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1794342dfc30SSteffen Hurrle 	DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
1795db8dac20SDavid S. Miller 	struct sk_buff *skb;
179659c2cdaeSDavid S. Miller 	unsigned int ulen, copied;
1797fd69c399SPaolo Abeni 	int off, err, peeking = flags & MSG_PEEK;
1798db8dac20SDavid S. Miller 	int is_udplite = IS_UDPLITE(sk);
1799197c949eSEric Dumazet 	bool checksum_valid = false;
1800db8dac20SDavid S. Miller 
1801db8dac20SDavid S. Miller 	if (flags & MSG_ERRQUEUE)
180285fbaa75SHannes Frederic Sowa 		return ip_recv_error(sk, msg, len, addr_len);
1803db8dac20SDavid S. Miller 
1804db8dac20SDavid S. Miller try_again:
1805a0917e0bSMatthew Dawson 	off = sk_peek_offset(sk, flags);
1806ec095263SOliver Hartkopp 	skb = __skb_recv_udp(sk, flags, &off, &err);
1807db8dac20SDavid S. Miller 	if (!skb)
1808627d2d6bSsamanthakumar 		return err;
1809db8dac20SDavid S. Miller 
1810b65ac446SPaolo Abeni 	ulen = udp_skb_len(skb);
181159c2cdaeSDavid S. Miller 	copied = len;
1812627d2d6bSsamanthakumar 	if (copied > ulen - off)
1813627d2d6bSsamanthakumar 		copied = ulen - off;
181459c2cdaeSDavid S. Miller 	else if (copied < ulen)
1815db8dac20SDavid S. Miller 		msg->msg_flags |= MSG_TRUNC;
1816db8dac20SDavid S. Miller 
1817db8dac20SDavid S. Miller 	/*
1818db8dac20SDavid S. Miller 	 * If checksum is needed at all, try to do it while copying the
1819db8dac20SDavid S. Miller 	 * data.  If the data is truncated, or if we only want a partial
1820db8dac20SDavid S. Miller 	 * coverage checksum (UDP-Lite), do it before the copy.
1821db8dac20SDavid S. Miller 	 */
1822db8dac20SDavid S. Miller 
1823d21dbdfeSEric Dumazet 	if (copied < ulen || peeking ||
1824d21dbdfeSEric Dumazet 	    (is_udplite && UDP_SKB_CB(skb)->partial_cov)) {
1825b65ac446SPaolo Abeni 		checksum_valid = udp_skb_csum_unnecessary(skb) ||
1826b65ac446SPaolo Abeni 				!__udp_lib_checksum_complete(skb);
1827197c949eSEric Dumazet 		if (!checksum_valid)
1828db8dac20SDavid S. Miller 			goto csum_copy_err;
1829db8dac20SDavid S. Miller 	}
1830db8dac20SDavid S. Miller 
1831b65ac446SPaolo Abeni 	if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
1832b65ac446SPaolo Abeni 		if (udp_skb_is_linear(skb))
1833b65ac446SPaolo Abeni 			err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
1834b65ac446SPaolo Abeni 		else
1835627d2d6bSsamanthakumar 			err = skb_copy_datagram_msg(skb, off, msg, copied);
1836b65ac446SPaolo Abeni 	} else {
1837627d2d6bSsamanthakumar 		err = skb_copy_and_csum_datagram_msg(skb, off, msg);
1838db8dac20SDavid S. Miller 
1839db8dac20SDavid S. Miller 		if (err == -EINVAL)
1840db8dac20SDavid S. Miller 			goto csum_copy_err;
1841db8dac20SDavid S. Miller 	}
1842db8dac20SDavid S. Miller 
184322911fc5SEric Dumazet 	if (unlikely(err)) {
1844fd69c399SPaolo Abeni 		if (!peeking) {
1845979402b1SEric Dumazet 			atomic_inc(&sk->sk_drops);
18466aef70a8SEric Dumazet 			UDP_INC_STATS(sock_net(sk),
1847979402b1SEric Dumazet 				      UDP_MIB_INERRORS, is_udplite);
1848979402b1SEric Dumazet 		}
1849850cbaddSPaolo Abeni 		kfree_skb(skb);
1850627d2d6bSsamanthakumar 		return err;
185122911fc5SEric Dumazet 	}
1852db8dac20SDavid S. Miller 
1853fd69c399SPaolo Abeni 	if (!peeking)
18546aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
1855629ca23cSPavel Emelyanov 			      UDP_MIB_INDATAGRAMS, is_udplite);
1856db8dac20SDavid S. Miller 
18576fd1d51cSErin MacNeil 	sock_recv_cmsgs(msg, sk, skb);
1858db8dac20SDavid S. Miller 
1859db8dac20SDavid S. Miller 	/* Copy the address. */
1860c482c568SEric Dumazet 	if (sin) {
1861db8dac20SDavid S. Miller 		sin->sin_family = AF_INET;
1862db8dac20SDavid S. Miller 		sin->sin_port = udp_hdr(skb)->source;
1863db8dac20SDavid S. Miller 		sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
1864db8dac20SDavid S. Miller 		memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
1865bceaa902SHannes Frederic Sowa 		*addr_len = sizeof(*sin);
1866983695faSDaniel Borkmann 
1867983695faSDaniel Borkmann 		BPF_CGROUP_RUN_PROG_UDP4_RECVMSG_LOCK(sk,
1868983695faSDaniel Borkmann 						      (struct sockaddr *)sin);
1869db8dac20SDavid S. Miller 	}
1870bcd1665eSPaolo Abeni 
1871e1dc0615SEric Dumazet 	if (udp_test_bit(GRO_ENABLED, sk))
1872bcd1665eSPaolo Abeni 		udp_cmsg_recv(msg, sk, skb);
1873bcd1665eSPaolo Abeni 
1874c274af22SEric Dumazet 	if (inet_cmsg_flags(inet))
1875ad959036SPaolo Abeni 		ip_cmsg_recv_offset(msg, sk, skb, sizeof(struct udphdr), off);
1876db8dac20SDavid S. Miller 
187759c2cdaeSDavid S. Miller 	err = copied;
1878db8dac20SDavid S. Miller 	if (flags & MSG_TRUNC)
1879db8dac20SDavid S. Miller 		err = ulen;
1880db8dac20SDavid S. Miller 
1881850cbaddSPaolo Abeni 	skb_consume_udp(sk, skb, peeking ? -err : err);
1882db8dac20SDavid S. Miller 	return err;
1883db8dac20SDavid S. Miller 
1884db8dac20SDavid S. Miller csum_copy_err:
18852276f58aSPaolo Abeni 	if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags,
18862276f58aSPaolo Abeni 				 udp_skb_destructor)) {
18876aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
18886aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
18896a5dc9e5SEric Dumazet 	}
1890850cbaddSPaolo Abeni 	kfree_skb(skb);
1891db8dac20SDavid S. Miller 
1892beb39db5SEric Dumazet 	/* starting over for a new packet, but check if we need to yield */
1893beb39db5SEric Dumazet 	cond_resched();
18949cfaa8deSXufeng Zhang 	msg->msg_flags &= ~MSG_TRUNC;
1895db8dac20SDavid S. Miller 	goto try_again;
1896db8dac20SDavid S. Miller }
1897db8dac20SDavid S. Miller 
1898d74bad4eSAndrey Ignatov int udp_pre_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
1899d74bad4eSAndrey Ignatov {
1900d74bad4eSAndrey Ignatov 	/* This check is replicated from __ip4_datagram_connect() and
1901d74bad4eSAndrey Ignatov 	 * intended to prevent BPF program called below from accessing bytes
1902d74bad4eSAndrey Ignatov 	 * that are out of the bound specified by user in addr_len.
1903d74bad4eSAndrey Ignatov 	 */
1904d74bad4eSAndrey Ignatov 	if (addr_len < sizeof(struct sockaddr_in))
1905d74bad4eSAndrey Ignatov 		return -EINVAL;
1906d74bad4eSAndrey Ignatov 
1907d74bad4eSAndrey Ignatov 	return BPF_CGROUP_RUN_PROG_INET4_CONNECT_LOCK(sk, uaddr);
1908d74bad4eSAndrey Ignatov }
1909d74bad4eSAndrey Ignatov EXPORT_SYMBOL(udp_pre_connect);
1910d74bad4eSAndrey Ignatov 
1911286c72deSEric Dumazet int __udp_disconnect(struct sock *sk, int flags)
19121da177e4SLinus Torvalds {
19131da177e4SLinus Torvalds 	struct inet_sock *inet = inet_sk(sk);
19141da177e4SLinus Torvalds 	/*
19151da177e4SLinus Torvalds 	 *	1003.1g - break association.
19161da177e4SLinus Torvalds 	 */
19171da177e4SLinus Torvalds 
19181da177e4SLinus Torvalds 	sk->sk_state = TCP_CLOSE;
1919c720c7e8SEric Dumazet 	inet->inet_daddr = 0;
1920c720c7e8SEric Dumazet 	inet->inet_dport = 0;
1921bdeab991STom Herbert 	sock_rps_reset_rxhash(sk);
19221da177e4SLinus Torvalds 	sk->sk_bound_dev_if = 0;
1923303d0403SWillem de Bruijn 	if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) {
19241da177e4SLinus Torvalds 		inet_reset_saddr(sk);
1925303d0403SWillem de Bruijn 		if (sk->sk_prot->rehash &&
1926303d0403SWillem de Bruijn 		    (sk->sk_userlocks & SOCK_BINDPORT_LOCK))
1927303d0403SWillem de Bruijn 			sk->sk_prot->rehash(sk);
1928303d0403SWillem de Bruijn 	}
19291da177e4SLinus Torvalds 
19301da177e4SLinus Torvalds 	if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
19311da177e4SLinus Torvalds 		sk->sk_prot->unhash(sk);
1932c720c7e8SEric Dumazet 		inet->inet_sport = 0;
19331da177e4SLinus Torvalds 	}
19341da177e4SLinus Torvalds 	sk_dst_reset(sk);
19351da177e4SLinus Torvalds 	return 0;
19361da177e4SLinus Torvalds }
1937286c72deSEric Dumazet EXPORT_SYMBOL(__udp_disconnect);
1938286c72deSEric Dumazet 
1939286c72deSEric Dumazet int udp_disconnect(struct sock *sk, int flags)
1940286c72deSEric Dumazet {
1941286c72deSEric Dumazet 	lock_sock(sk);
1942286c72deSEric Dumazet 	__udp_disconnect(sk, flags);
1943286c72deSEric Dumazet 	release_sock(sk);
1944286c72deSEric Dumazet 	return 0;
1945286c72deSEric Dumazet }
1946c482c568SEric Dumazet EXPORT_SYMBOL(udp_disconnect);
19471da177e4SLinus Torvalds 
1948645ca708SEric Dumazet void udp_lib_unhash(struct sock *sk)
1949645ca708SEric Dumazet {
1950723b4610SEric Dumazet 	if (sk_hashed(sk)) {
195167fb4330SKuniyuki Iwashima 		struct udp_table *udptable = udp_get_table_prot(sk);
1952512615b6SEric Dumazet 		struct udp_hslot *hslot, *hslot2;
1953512615b6SEric Dumazet 
1954512615b6SEric Dumazet 		hslot  = udp_hashslot(udptable, sock_net(sk),
1955d4cada4aSEric Dumazet 				      udp_sk(sk)->udp_port_hash);
1956512615b6SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
1957645ca708SEric Dumazet 
1958c8db3fecSEric Dumazet 		spin_lock_bh(&hslot->lock);
1959e32ea7e7SCraig Gallek 		if (rcu_access_pointer(sk->sk_reuseport_cb))
1960e32ea7e7SCraig Gallek 			reuseport_detach_sock(sk);
1961ca065d0cSEric Dumazet 		if (sk_del_node_init_rcu(sk)) {
1962fdcc8aa9SEric Dumazet 			hslot->count--;
1963c720c7e8SEric Dumazet 			inet_sk(sk)->inet_num = 0;
1964645ca708SEric Dumazet 			sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
1965512615b6SEric Dumazet 
1966512615b6SEric Dumazet 			spin_lock(&hslot2->lock);
1967ca065d0cSEric Dumazet 			hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
1968512615b6SEric Dumazet 			hslot2->count--;
1969512615b6SEric Dumazet 			spin_unlock(&hslot2->lock);
1970645ca708SEric Dumazet 		}
1971c8db3fecSEric Dumazet 		spin_unlock_bh(&hslot->lock);
1972645ca708SEric Dumazet 	}
1973723b4610SEric Dumazet }
1974645ca708SEric Dumazet EXPORT_SYMBOL(udp_lib_unhash);
1975645ca708SEric Dumazet 
1976719f8358SEric Dumazet /*
1977719f8358SEric Dumazet  * inet_rcv_saddr was changed, we must rehash secondary hash
1978719f8358SEric Dumazet  */
1979719f8358SEric Dumazet void udp_lib_rehash(struct sock *sk, u16 newhash)
1980719f8358SEric Dumazet {
1981719f8358SEric Dumazet 	if (sk_hashed(sk)) {
198267fb4330SKuniyuki Iwashima 		struct udp_table *udptable = udp_get_table_prot(sk);
1983719f8358SEric Dumazet 		struct udp_hslot *hslot, *hslot2, *nhslot2;
1984719f8358SEric Dumazet 
1985719f8358SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
1986719f8358SEric Dumazet 		nhslot2 = udp_hashslot2(udptable, newhash);
1987719f8358SEric Dumazet 		udp_sk(sk)->udp_portaddr_hash = newhash;
1988e32ea7e7SCraig Gallek 
1989e32ea7e7SCraig Gallek 		if (hslot2 != nhslot2 ||
1990e32ea7e7SCraig Gallek 		    rcu_access_pointer(sk->sk_reuseport_cb)) {
1991719f8358SEric Dumazet 			hslot = udp_hashslot(udptable, sock_net(sk),
1992719f8358SEric Dumazet 					     udp_sk(sk)->udp_port_hash);
1993719f8358SEric Dumazet 			/* we must lock primary chain too */
1994719f8358SEric Dumazet 			spin_lock_bh(&hslot->lock);
1995e32ea7e7SCraig Gallek 			if (rcu_access_pointer(sk->sk_reuseport_cb))
1996e32ea7e7SCraig Gallek 				reuseport_detach_sock(sk);
1997719f8358SEric Dumazet 
1998e32ea7e7SCraig Gallek 			if (hslot2 != nhslot2) {
1999719f8358SEric Dumazet 				spin_lock(&hslot2->lock);
2000ca065d0cSEric Dumazet 				hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
2001719f8358SEric Dumazet 				hslot2->count--;
2002719f8358SEric Dumazet 				spin_unlock(&hslot2->lock);
2003719f8358SEric Dumazet 
2004719f8358SEric Dumazet 				spin_lock(&nhslot2->lock);
2005ca065d0cSEric Dumazet 				hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
2006719f8358SEric Dumazet 							 &nhslot2->head);
2007719f8358SEric Dumazet 				nhslot2->count++;
2008719f8358SEric Dumazet 				spin_unlock(&nhslot2->lock);
2009e32ea7e7SCraig Gallek 			}
2010719f8358SEric Dumazet 
2011719f8358SEric Dumazet 			spin_unlock_bh(&hslot->lock);
2012719f8358SEric Dumazet 		}
2013719f8358SEric Dumazet 	}
2014719f8358SEric Dumazet }
2015719f8358SEric Dumazet EXPORT_SYMBOL(udp_lib_rehash);
2016719f8358SEric Dumazet 
20178f6b5392SAlexey Kodanev void udp_v4_rehash(struct sock *sk)
2018719f8358SEric Dumazet {
2019f0b1e64cSMartin KaFai Lau 	u16 new_hash = ipv4_portaddr_hash(sock_net(sk),
2020719f8358SEric Dumazet 					  inet_sk(sk)->inet_rcv_saddr,
2021719f8358SEric Dumazet 					  inet_sk(sk)->inet_num);
2022719f8358SEric Dumazet 	udp_lib_rehash(sk, new_hash);
2023719f8358SEric Dumazet }
2024719f8358SEric Dumazet 
2025a3f96c47SPaolo Abeni static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
202693821778SHerbert Xu {
2027fec5e652STom Herbert 	int rc;
202893821778SHerbert Xu 
2029005ec974SShawn Bohrer 	if (inet_sk(sk)->inet_daddr) {
2030bdeab991STom Herbert 		sock_rps_save_rxhash(sk, skb);
2031005ec974SShawn Bohrer 		sk_mark_napi_id(sk, skb);
20322c8c56e1SEric Dumazet 		sk_incoming_cpu_update(sk);
2033e68b6e50SEric Dumazet 	} else {
2034e68b6e50SEric Dumazet 		sk_mark_napi_id_once(sk, skb);
2035005ec974SShawn Bohrer 	}
2036fec5e652STom Herbert 
2037850cbaddSPaolo Abeni 	rc = __udp_enqueue_schedule_skb(sk, skb);
2038766e9037SEric Dumazet 	if (rc < 0) {
2039766e9037SEric Dumazet 		int is_udplite = IS_UDPLITE(sk);
204008d4c037SMenglong Dong 		int drop_reason;
2041766e9037SEric Dumazet 
204293821778SHerbert Xu 		/* Note that an ENOMEM error is charged twice */
204308d4c037SMenglong Dong 		if (rc == -ENOMEM) {
2044e61da9e2SEric Dumazet 			UDP_INC_STATS(sock_net(sk), UDP_MIB_RCVBUFERRORS,
204593821778SHerbert Xu 					is_udplite);
204608d4c037SMenglong Dong 			drop_reason = SKB_DROP_REASON_SOCKET_RCVBUFF;
204708d4c037SMenglong Dong 		} else {
2048a3ce2b10SMenglong Dong 			UDP_INC_STATS(sock_net(sk), UDP_MIB_MEMERRORS,
2049a3ce2b10SMenglong Dong 				      is_udplite);
205008d4c037SMenglong Dong 			drop_reason = SKB_DROP_REASON_PROTO_MEM;
205108d4c037SMenglong Dong 		}
2052e61da9e2SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
205308d4c037SMenglong Dong 		kfree_skb_reason(skb, drop_reason);
2054296f7ea7SSatoru Moriya 		trace_udp_fail_queue_rcv_skb(rc, sk);
2055766e9037SEric Dumazet 		return -1;
205693821778SHerbert Xu 	}
205793821778SHerbert Xu 
205893821778SHerbert Xu 	return 0;
205993821778SHerbert Xu }
206093821778SHerbert Xu 
2061db8dac20SDavid S. Miller /* returns:
2062db8dac20SDavid S. Miller  *  -1: error
2063db8dac20SDavid S. Miller  *   0: success
2064db8dac20SDavid S. Miller  *  >0: "udp encap" protocol resubmission
2065db8dac20SDavid S. Miller  *
2066db8dac20SDavid S. Miller  * Note that in the success and error cases, the skb is assumed to
2067db8dac20SDavid S. Miller  * have either been requeued or freed.
2068db8dac20SDavid S. Miller  */
2069cf329aa4SPaolo Abeni static int udp_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
2070db8dac20SDavid S. Miller {
20711379a92dSMenglong Dong 	int drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2072db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
2073db8dac20SDavid S. Miller 	int is_udplite = IS_UDPLITE(sk);
2074db8dac20SDavid S. Miller 
2075db8dac20SDavid S. Miller 	/*
2076db8dac20SDavid S. Miller 	 *	Charge it to the socket, dropping if the queue is full.
2077db8dac20SDavid S. Miller 	 */
20781379a92dSMenglong Dong 	if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
20791379a92dSMenglong Dong 		drop_reason = SKB_DROP_REASON_XFRM_POLICY;
2080db8dac20SDavid S. Miller 		goto drop;
20811379a92dSMenglong Dong 	}
2082895b5c9fSFlorian Westphal 	nf_reset_ct(skb);
2083db8dac20SDavid S. Miller 
208470a36f57SEric Dumazet 	if (static_branch_unlikely(&udp_encap_needed_key) &&
208570a36f57SEric Dumazet 	    READ_ONCE(up->encap_type)) {
20860ad92ad0SEric Dumazet 		int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
20870ad92ad0SEric Dumazet 
2088db8dac20SDavid S. Miller 		/*
2089db8dac20SDavid S. Miller 		 * This is an encapsulation socket so pass the skb to
2090db8dac20SDavid S. Miller 		 * the socket's udp_encap_rcv() hook. Otherwise, just
2091db8dac20SDavid S. Miller 		 * fall through and pass this up the UDP socket.
2092db8dac20SDavid S. Miller 		 * up->encap_rcv() returns the following value:
2093db8dac20SDavid S. Miller 		 * =0 if skb was successfully passed to the encap
2094db8dac20SDavid S. Miller 		 *    handler or was discarded by it.
2095db8dac20SDavid S. Miller 		 * >0 if skb should be passed on to UDP.
2096db8dac20SDavid S. Miller 		 * <0 if skb should be resubmitted as proto -N
2097db8dac20SDavid S. Miller 		 */
2098db8dac20SDavid S. Miller 
2099db8dac20SDavid S. Miller 		/* if we're overly short, let UDP handle it */
21006aa7de05SMark Rutland 		encap_rcv = READ_ONCE(up->encap_rcv);
2101e5aed006SHannes Frederic Sowa 		if (encap_rcv) {
2102db8dac20SDavid S. Miller 			int ret;
2103db8dac20SDavid S. Miller 
21040a80966bSTom Herbert 			/* Verify checksum before giving to encap */
21050a80966bSTom Herbert 			if (udp_lib_checksum_complete(skb))
21060a80966bSTom Herbert 				goto csum_error;
21070a80966bSTom Herbert 
21080ad92ad0SEric Dumazet 			ret = encap_rcv(sk, skb);
2109db8dac20SDavid S. Miller 			if (ret <= 0) {
211002c22347SEric Dumazet 				__UDP_INC_STATS(sock_net(sk),
21110283328eSPavel Emelyanov 						UDP_MIB_INDATAGRAMS,
2112db8dac20SDavid S. Miller 						is_udplite);
2113db8dac20SDavid S. Miller 				return -ret;
2114db8dac20SDavid S. Miller 			}
2115db8dac20SDavid S. Miller 		}
2116db8dac20SDavid S. Miller 
2117db8dac20SDavid S. Miller 		/* FALLTHROUGH -- it's a UDP Packet */
2118db8dac20SDavid S. Miller 	}
2119db8dac20SDavid S. Miller 
2120db8dac20SDavid S. Miller 	/*
2121db8dac20SDavid S. Miller 	 * 	UDP-Lite specific tests, ignored on UDP sockets
2122db8dac20SDavid S. Miller 	 */
2123*882af43aSEric Dumazet 	if (udp_test_bit(UDPLITE_RECV_CC, sk) && UDP_SKB_CB(skb)->partial_cov) {
2124*882af43aSEric Dumazet 		u16 pcrlen = READ_ONCE(up->pcrlen);
2125db8dac20SDavid S. Miller 
2126db8dac20SDavid S. Miller 		/*
2127db8dac20SDavid S. Miller 		 * MIB statistics other than incrementing the error count are
2128db8dac20SDavid S. Miller 		 * disabled for the following two types of errors: these depend
2129db8dac20SDavid S. Miller 		 * on the application settings, not on the functioning of the
2130db8dac20SDavid S. Miller 		 * protocol stack as such.
2131db8dac20SDavid S. Miller 		 *
2132db8dac20SDavid S. Miller 		 * RFC 3828 here recommends (sec 3.3): "There should also be a
2133db8dac20SDavid S. Miller 		 * way ... to ... at least let the receiving application block
2134db8dac20SDavid S. Miller 		 * delivery of packets with coverage values less than a value
2135db8dac20SDavid S. Miller 		 * provided by the application."
2136db8dac20SDavid S. Miller 		 */
2137*882af43aSEric Dumazet 		if (pcrlen == 0) {          /* full coverage was set  */
2138ba7a46f1SJoe Perches 			net_dbg_ratelimited("UDPLite: partial coverage %d while full coverage %d requested\n",
2139db8dac20SDavid S. Miller 					    UDP_SKB_CB(skb)->cscov, skb->len);
2140db8dac20SDavid S. Miller 			goto drop;
2141db8dac20SDavid S. Miller 		}
2142db8dac20SDavid S. Miller 		/* The next case involves violating the min. coverage requested
2143db8dac20SDavid S. Miller 		 * by the receiver. This is subtle: if receiver wants x and x is
2144db8dac20SDavid S. Miller 		 * greater than the buffersize/MTU then receiver will complain
2145db8dac20SDavid S. Miller 		 * that it wants x while sender emits packets of smaller size y.
2146db8dac20SDavid S. Miller 		 * Therefore the above ...()->partial_cov statement is essential.
2147db8dac20SDavid S. Miller 		 */
2148*882af43aSEric Dumazet 		if (UDP_SKB_CB(skb)->cscov < pcrlen) {
2149ba7a46f1SJoe Perches 			net_dbg_ratelimited("UDPLite: coverage %d too small, need min %d\n",
2150*882af43aSEric Dumazet 					    UDP_SKB_CB(skb)->cscov, pcrlen);
2151db8dac20SDavid S. Miller 			goto drop;
2152db8dac20SDavid S. Miller 		}
2153db8dac20SDavid S. Miller 	}
2154db8dac20SDavid S. Miller 
2155dd99e425SPaolo Abeni 	prefetch(&sk->sk_rmem_alloc);
2156ce25d66aSEric Dumazet 	if (rcu_access_pointer(sk->sk_filter) &&
2157ce25d66aSEric Dumazet 	    udp_lib_checksum_complete(skb))
21586a5dc9e5SEric Dumazet 			goto csum_error;
2159ce25d66aSEric Dumazet 
21601379a92dSMenglong Dong 	if (sk_filter_trim_cap(sk, skb, sizeof(struct udphdr))) {
21611379a92dSMenglong Dong 		drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
2162a6127697SMichal Kubeček 		goto drop;
21631379a92dSMenglong Dong 	}
2164db8dac20SDavid S. Miller 
2165e6afc8acSsamanthakumar 	udp_csum_pull_header(skb);
2166db8dac20SDavid S. Miller 
2167fbf8866dSShawn Bohrer 	ipv4_pktinfo_prepare(sk, skb);
2168850cbaddSPaolo Abeni 	return __udp_queue_rcv_skb(sk, skb);
2169db8dac20SDavid S. Miller 
21706a5dc9e5SEric Dumazet csum_error:
21711379a92dSMenglong Dong 	drop_reason = SKB_DROP_REASON_UDP_CSUM;
217202c22347SEric Dumazet 	__UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
2173db8dac20SDavid S. Miller drop:
217402c22347SEric Dumazet 	__UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
21758edf19c2SEric Dumazet 	atomic_inc(&sk->sk_drops);
21761379a92dSMenglong Dong 	kfree_skb_reason(skb, drop_reason);
2177db8dac20SDavid S. Miller 	return -1;
2178db8dac20SDavid S. Miller }
2179db8dac20SDavid S. Miller 
2180cf329aa4SPaolo Abeni static int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2181cf329aa4SPaolo Abeni {
2182cf329aa4SPaolo Abeni 	struct sk_buff *next, *segs;
2183cf329aa4SPaolo Abeni 	int ret;
2184cf329aa4SPaolo Abeni 
2185cf329aa4SPaolo Abeni 	if (likely(!udp_unexpected_gso(sk, skb)))
2186cf329aa4SPaolo Abeni 		return udp_queue_rcv_one_skb(sk, skb);
2187cf329aa4SPaolo Abeni 
2188a08e7fd9SCambda Zhu 	BUILD_BUG_ON(sizeof(struct udp_skb_cb) > SKB_GSO_CB_OFFSET);
2189cf329aa4SPaolo Abeni 	__skb_push(skb, -skb_mac_offset(skb));
2190cf329aa4SPaolo Abeni 	segs = udp_rcv_segment(sk, skb, true);
21911a186c14SJason A. Donenfeld 	skb_list_walk_safe(segs, skb, next) {
2192cf329aa4SPaolo Abeni 		__skb_pull(skb, skb_transport_offset(skb));
2193000ac44dSPaolo Abeni 
2194000ac44dSPaolo Abeni 		udp_post_segment_fix_csum(skb);
2195cf329aa4SPaolo Abeni 		ret = udp_queue_rcv_one_skb(sk, skb);
2196cf329aa4SPaolo Abeni 		if (ret > 0)
219710c678bdSXin Long 			ip_protocol_deliver_rcu(dev_net(skb->dev), skb, ret);
2198cf329aa4SPaolo Abeni 	}
2199cf329aa4SPaolo Abeni 	return 0;
2200cf329aa4SPaolo Abeni }
2201cf329aa4SPaolo Abeni 
220297502231SEric Dumazet /* For TCP sockets, sk_rx_dst is protected by socket lock
2203e47eb5dfSEric Dumazet  * For UDP, we use xchg() to guard against concurrent changes.
220497502231SEric Dumazet  */
220564f0f5d1SPaolo Abeni bool udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
2206421b3885SShawn Bohrer {
220797502231SEric Dumazet 	struct dst_entry *old;
2208421b3885SShawn Bohrer 
2209d24406c8SWei Wang 	if (dst_hold_safe(dst)) {
22108f905c0eSEric Dumazet 		old = xchg((__force struct dst_entry **)&sk->sk_rx_dst, dst);
221197502231SEric Dumazet 		dst_release(old);
221264f0f5d1SPaolo Abeni 		return old != dst;
221397502231SEric Dumazet 	}
221464f0f5d1SPaolo Abeni 	return false;
2215d24406c8SWei Wang }
2216c9f2c1aeSPaolo Abeni EXPORT_SYMBOL(udp_sk_rx_dst_set);
2217421b3885SShawn Bohrer 
2218db8dac20SDavid S. Miller /*
2219db8dac20SDavid S. Miller  *	Multicasts and broadcasts go to each listener.
2220db8dac20SDavid S. Miller  *
22211240d137SEric Dumazet  *	Note: called only from the BH handler context.
2222db8dac20SDavid S. Miller  */
2223e3163493SPavel Emelyanov static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
2224db8dac20SDavid S. Miller 				    struct udphdr  *uh,
2225db8dac20SDavid S. Miller 				    __be32 saddr, __be32 daddr,
222636cbb245SRick Jones 				    struct udp_table *udptable,
222736cbb245SRick Jones 				    int proto)
2228db8dac20SDavid S. Miller {
2229ca065d0cSEric Dumazet 	struct sock *sk, *first = NULL;
22305cf3d461SDavid Held 	unsigned short hnum = ntohs(uh->dest);
22315cf3d461SDavid Held 	struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum);
22322dc41cffSDavid Held 	unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10);
2233ca065d0cSEric Dumazet 	unsigned int offset = offsetof(typeof(*sk), sk_node);
2234ca065d0cSEric Dumazet 	int dif = skb->dev->ifindex;
2235fb74c277SDavid Ahern 	int sdif = inet_sdif(skb);
2236ca065d0cSEric Dumazet 	struct hlist_node *node;
2237ca065d0cSEric Dumazet 	struct sk_buff *nskb;
22382dc41cffSDavid Held 
22392dc41cffSDavid Held 	if (use_hash2) {
2240f0b1e64cSMartin KaFai Lau 		hash2_any = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum) &
224173e2d5e3SPablo Neira 			    udptable->mask;
2242f0b1e64cSMartin KaFai Lau 		hash2 = ipv4_portaddr_hash(net, daddr, hnum) & udptable->mask;
22432dc41cffSDavid Held start_lookup:
224473e2d5e3SPablo Neira 		hslot = &udptable->hash2[hash2];
22452dc41cffSDavid Held 		offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
22462dc41cffSDavid Held 	}
2247db8dac20SDavid S. Miller 
2248ca065d0cSEric Dumazet 	sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
2249ca065d0cSEric Dumazet 		if (!__udp_is_mcast_sock(net, sk, uh->dest, daddr,
2250fb74c277SDavid Ahern 					 uh->source, saddr, dif, sdif, hnum))
2251ca065d0cSEric Dumazet 			continue;
22521240d137SEric Dumazet 
2253ca065d0cSEric Dumazet 		if (!first) {
2254ca065d0cSEric Dumazet 			first = sk;
2255ca065d0cSEric Dumazet 			continue;
2256ca065d0cSEric Dumazet 		}
2257ca065d0cSEric Dumazet 		nskb = skb_clone(skb, GFP_ATOMIC);
2258ca065d0cSEric Dumazet 
2259ca065d0cSEric Dumazet 		if (unlikely(!nskb)) {
2260ca065d0cSEric Dumazet 			atomic_inc(&sk->sk_drops);
226102c22347SEric Dumazet 			__UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS,
2262ca065d0cSEric Dumazet 					IS_UDPLITE(sk));
226302c22347SEric Dumazet 			__UDP_INC_STATS(net, UDP_MIB_INERRORS,
2264ca065d0cSEric Dumazet 					IS_UDPLITE(sk));
2265ca065d0cSEric Dumazet 			continue;
2266ca065d0cSEric Dumazet 		}
2267ca065d0cSEric Dumazet 		if (udp_queue_rcv_skb(sk, nskb) > 0)
2268ca065d0cSEric Dumazet 			consume_skb(nskb);
2269ca065d0cSEric Dumazet 	}
22701240d137SEric Dumazet 
22712dc41cffSDavid Held 	/* Also lookup *:port if we are using hash2 and haven't done so yet. */
22722dc41cffSDavid Held 	if (use_hash2 && hash2 != hash2_any) {
22732dc41cffSDavid Held 		hash2 = hash2_any;
22742dc41cffSDavid Held 		goto start_lookup;
22752dc41cffSDavid Held 	}
22762dc41cffSDavid Held 
2277ca065d0cSEric Dumazet 	if (first) {
2278ca065d0cSEric Dumazet 		if (udp_queue_rcv_skb(first, skb) > 0)
2279ca065d0cSEric Dumazet 			consume_skb(skb);
22801240d137SEric Dumazet 	} else {
2281ca065d0cSEric Dumazet 		kfree_skb(skb);
228202c22347SEric Dumazet 		__UDP_INC_STATS(net, UDP_MIB_IGNOREDMULTI,
228336cbb245SRick Jones 				proto == IPPROTO_UDPLITE);
22841240d137SEric Dumazet 	}
2285db8dac20SDavid S. Miller 	return 0;
2286db8dac20SDavid S. Miller }
2287db8dac20SDavid S. Miller 
2288db8dac20SDavid S. Miller /* Initialize UDP checksum. If exited with zero value (success),
2289db8dac20SDavid S. Miller  * CHECKSUM_UNNECESSARY means, that no more checks are required.
2290666a3d6eSSu Yanjun  * Otherwise, csum completion requires checksumming packet body,
2291db8dac20SDavid S. Miller  * including udp header and folding it to skb->csum.
2292db8dac20SDavid S. Miller  */
2293db8dac20SDavid S. Miller static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
2294db8dac20SDavid S. Miller 				 int proto)
2295db8dac20SDavid S. Miller {
2296db8dac20SDavid S. Miller 	int err;
2297db8dac20SDavid S. Miller 
2298db8dac20SDavid S. Miller 	UDP_SKB_CB(skb)->partial_cov = 0;
2299db8dac20SDavid S. Miller 	UDP_SKB_CB(skb)->cscov = skb->len;
2300db8dac20SDavid S. Miller 
2301db8dac20SDavid S. Miller 	if (proto == IPPROTO_UDPLITE) {
2302db8dac20SDavid S. Miller 		err = udplite_checksum_init(skb, uh);
2303db8dac20SDavid S. Miller 		if (err)
2304db8dac20SDavid S. Miller 			return err;
230515f35d49SAlexey Kodanev 
230615f35d49SAlexey Kodanev 		if (UDP_SKB_CB(skb)->partial_cov) {
230715f35d49SAlexey Kodanev 			skb->csum = inet_compute_pseudo(skb, proto);
230815f35d49SAlexey Kodanev 			return 0;
230915f35d49SAlexey Kodanev 		}
2310db8dac20SDavid S. Miller 	}
2311db8dac20SDavid S. Miller 
2312b46d9f62SHannes Frederic Sowa 	/* Note, we are only interested in != 0 or == 0, thus the
2313b46d9f62SHannes Frederic Sowa 	 * force to int.
2314b46d9f62SHannes Frederic Sowa 	 */
2315db4f1be3SSean Tranchetti 	err = (__force int)skb_checksum_init_zero_check(skb, proto, uh->check,
2316ed70fcfcSTom Herbert 							inet_compute_pseudo);
2317db4f1be3SSean Tranchetti 	if (err)
2318db4f1be3SSean Tranchetti 		return err;
2319db4f1be3SSean Tranchetti 
2320db4f1be3SSean Tranchetti 	if (skb->ip_summed == CHECKSUM_COMPLETE && !skb->csum_valid) {
2321db4f1be3SSean Tranchetti 		/* If SW calculated the value, we know it's bad */
2322db4f1be3SSean Tranchetti 		if (skb->csum_complete_sw)
2323db4f1be3SSean Tranchetti 			return 1;
2324db4f1be3SSean Tranchetti 
2325db4f1be3SSean Tranchetti 		/* HW says the value is bad. Let's validate that.
2326db4f1be3SSean Tranchetti 		 * skb->csum is no longer the full packet checksum,
2327db4f1be3SSean Tranchetti 		 * so don't treat it as such.
2328db4f1be3SSean Tranchetti 		 */
2329db4f1be3SSean Tranchetti 		skb_checksum_complete_unset(skb);
2330db4f1be3SSean Tranchetti 	}
2331db4f1be3SSean Tranchetti 
2332db4f1be3SSean Tranchetti 	return 0;
2333db8dac20SDavid S. Miller }
2334db8dac20SDavid S. Miller 
23352b5a9217SPaolo Abeni /* wrapper for udp_queue_rcv_skb tacking care of csum conversion and
23362b5a9217SPaolo Abeni  * return code conversion for ip layer consumption
23372b5a9217SPaolo Abeni  */
23382b5a9217SPaolo Abeni static int udp_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb,
23392b5a9217SPaolo Abeni 			       struct udphdr *uh)
23402b5a9217SPaolo Abeni {
23412b5a9217SPaolo Abeni 	int ret;
23422b5a9217SPaolo Abeni 
23432b5a9217SPaolo Abeni 	if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk))
2344e4aa33adSLi RongQing 		skb_checksum_try_convert(skb, IPPROTO_UDP, inet_compute_pseudo);
23452b5a9217SPaolo Abeni 
23462b5a9217SPaolo Abeni 	ret = udp_queue_rcv_skb(sk, skb);
23472b5a9217SPaolo Abeni 
23482b5a9217SPaolo Abeni 	/* a return value > 0 means to resubmit the input, but
23492b5a9217SPaolo Abeni 	 * it wants the return to be -protocol, or 0
23502b5a9217SPaolo Abeni 	 */
23512b5a9217SPaolo Abeni 	if (ret > 0)
23522b5a9217SPaolo Abeni 		return -ret;
23532b5a9217SPaolo Abeni 	return 0;
23542b5a9217SPaolo Abeni }
23552b5a9217SPaolo Abeni 
2356db8dac20SDavid S. Miller /*
2357db8dac20SDavid S. Miller  *	All we need to do is get the socket, and then do a checksum.
2358db8dac20SDavid S. Miller  */
2359db8dac20SDavid S. Miller 
2360645ca708SEric Dumazet int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
2361db8dac20SDavid S. Miller 		   int proto)
2362db8dac20SDavid S. Miller {
2363db8dac20SDavid S. Miller 	struct sock *sk;
23647b5e56f9SJesper Dangaard Brouer 	struct udphdr *uh;
2365db8dac20SDavid S. Miller 	unsigned short ulen;
2366adf30907SEric Dumazet 	struct rtable *rt = skb_rtable(skb);
23672783ef23SJesper Dangaard Brouer 	__be32 saddr, daddr;
23680283328eSPavel Emelyanov 	struct net *net = dev_net(skb->dev);
236971489e21SJoe Stringer 	bool refcounted;
23701c7fab70SMenglong Dong 	int drop_reason;
23711c7fab70SMenglong Dong 
23721c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2373db8dac20SDavid S. Miller 
2374db8dac20SDavid S. Miller 	/*
2375db8dac20SDavid S. Miller 	 *  Validate the packet.
2376db8dac20SDavid S. Miller 	 */
2377db8dac20SDavid S. Miller 	if (!pskb_may_pull(skb, sizeof(struct udphdr)))
2378db8dac20SDavid S. Miller 		goto drop;		/* No space for header. */
2379db8dac20SDavid S. Miller 
23807b5e56f9SJesper Dangaard Brouer 	uh   = udp_hdr(skb);
2381db8dac20SDavid S. Miller 	ulen = ntohs(uh->len);
2382ccc2d97cSBjørn Mork 	saddr = ip_hdr(skb)->saddr;
2383ccc2d97cSBjørn Mork 	daddr = ip_hdr(skb)->daddr;
2384ccc2d97cSBjørn Mork 
2385db8dac20SDavid S. Miller 	if (ulen > skb->len)
2386db8dac20SDavid S. Miller 		goto short_packet;
2387db8dac20SDavid S. Miller 
2388db8dac20SDavid S. Miller 	if (proto == IPPROTO_UDP) {
2389db8dac20SDavid S. Miller 		/* UDP validates ulen. */
2390db8dac20SDavid S. Miller 		if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
2391db8dac20SDavid S. Miller 			goto short_packet;
2392db8dac20SDavid S. Miller 		uh = udp_hdr(skb);
2393db8dac20SDavid S. Miller 	}
2394db8dac20SDavid S. Miller 
2395db8dac20SDavid S. Miller 	if (udp4_csum_init(skb, uh, proto))
2396db8dac20SDavid S. Miller 		goto csum_error;
2397db8dac20SDavid S. Miller 
23989c02bec9SLorenz Bauer 	sk = inet_steal_sock(net, skb, sizeof(struct udphdr), saddr, uh->source, daddr, uh->dest,
23999c02bec9SLorenz Bauer 			     &refcounted, udp_ehashfn);
24009c02bec9SLorenz Bauer 	if (IS_ERR(sk))
24019c02bec9SLorenz Bauer 		goto no_sk;
24029c02bec9SLorenz Bauer 
24038afdd99aSEric Dumazet 	if (sk) {
240497502231SEric Dumazet 		struct dst_entry *dst = skb_dst(skb);
2405421b3885SShawn Bohrer 		int ret;
2406421b3885SShawn Bohrer 
24078f905c0eSEric Dumazet 		if (unlikely(rcu_dereference(sk->sk_rx_dst) != dst))
240897502231SEric Dumazet 			udp_sk_rx_dst_set(sk, dst);
2409421b3885SShawn Bohrer 
24102b5a9217SPaolo Abeni 		ret = udp_unicast_rcv_skb(sk, skb, uh);
241171489e21SJoe Stringer 		if (refcounted)
24128afdd99aSEric Dumazet 			sock_put(sk);
24132b5a9217SPaolo Abeni 		return ret;
2414c18450a5SFabian Frederick 	}
2415c18450a5SFabian Frederick 
2416db8dac20SDavid S. Miller 	if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
2417e3163493SPavel Emelyanov 		return __udp4_lib_mcast_deliver(net, skb, uh,
241836cbb245SRick Jones 						saddr, daddr, udptable, proto);
2419db8dac20SDavid S. Miller 
2420607c4aafSKOVACS Krisztian 	sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
24212b5a9217SPaolo Abeni 	if (sk)
24222b5a9217SPaolo Abeni 		return udp_unicast_rcv_skb(sk, skb, uh);
24239c02bec9SLorenz Bauer no_sk:
2424db8dac20SDavid S. Miller 	if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
2425db8dac20SDavid S. Miller 		goto drop;
2426895b5c9fSFlorian Westphal 	nf_reset_ct(skb);
2427db8dac20SDavid S. Miller 
2428db8dac20SDavid S. Miller 	/* No socket. Drop packet silently, if checksum is wrong */
2429db8dac20SDavid S. Miller 	if (udp_lib_checksum_complete(skb))
2430db8dac20SDavid S. Miller 		goto csum_error;
2431db8dac20SDavid S. Miller 
24321c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_NO_SOCKET;
243302c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
2434db8dac20SDavid S. Miller 	icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
2435db8dac20SDavid S. Miller 
2436db8dac20SDavid S. Miller 	/*
2437db8dac20SDavid S. Miller 	 * Hmm.  We got an UDP packet to a port to which we
2438db8dac20SDavid S. Miller 	 * don't wanna listen.  Ignore it.
2439db8dac20SDavid S. Miller 	 */
24401c7fab70SMenglong Dong 	kfree_skb_reason(skb, drop_reason);
2441db8dac20SDavid S. Miller 	return 0;
2442db8dac20SDavid S. Miller 
2443db8dac20SDavid S. Miller short_packet:
24441c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_PKT_TOO_SMALL;
2445ba7a46f1SJoe Perches 	net_dbg_ratelimited("UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
2446afd46503SJoe Perches 			    proto == IPPROTO_UDPLITE ? "Lite" : "",
2447afd46503SJoe Perches 			    &saddr, ntohs(uh->source),
2448afd46503SJoe Perches 			    ulen, skb->len,
2449afd46503SJoe Perches 			    &daddr, ntohs(uh->dest));
2450db8dac20SDavid S. Miller 	goto drop;
2451db8dac20SDavid S. Miller 
2452db8dac20SDavid S. Miller csum_error:
2453db8dac20SDavid S. Miller 	/*
2454db8dac20SDavid S. Miller 	 * RFC1122: OK.  Discards the bad packet silently (as far as
2455db8dac20SDavid S. Miller 	 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
2456db8dac20SDavid S. Miller 	 */
24571c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_UDP_CSUM;
2458ba7a46f1SJoe Perches 	net_dbg_ratelimited("UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
2459afd46503SJoe Perches 			    proto == IPPROTO_UDPLITE ? "Lite" : "",
2460afd46503SJoe Perches 			    &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
2461db8dac20SDavid S. Miller 			    ulen);
246202c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
2463db8dac20SDavid S. Miller drop:
246402c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
24651c7fab70SMenglong Dong 	kfree_skb_reason(skb, drop_reason);
2466db8dac20SDavid S. Miller 	return 0;
2467db8dac20SDavid S. Miller }
2468db8dac20SDavid S. Miller 
2469421b3885SShawn Bohrer /* We can only early demux multicast if there is a single matching socket.
2470421b3885SShawn Bohrer  * If more than one socket found returns NULL
2471421b3885SShawn Bohrer  */
2472421b3885SShawn Bohrer static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net,
2473421b3885SShawn Bohrer 						  __be16 loc_port, __be32 loc_addr,
2474421b3885SShawn Bohrer 						  __be16 rmt_port, __be32 rmt_addr,
2475fb74c277SDavid Ahern 						  int dif, int sdif)
2476421b3885SShawn Bohrer {
2477ba6aac15SKuniyuki Iwashima 	struct udp_table *udptable = net->ipv4.udp_table;
2478421b3885SShawn Bohrer 	unsigned short hnum = ntohs(loc_port);
2479919dfa0bSKuniyuki Iwashima 	struct sock *sk, *result;
2480919dfa0bSKuniyuki Iwashima 	struct udp_hslot *hslot;
2481919dfa0bSKuniyuki Iwashima 	unsigned int slot;
2482919dfa0bSKuniyuki Iwashima 
2483ba6aac15SKuniyuki Iwashima 	slot = udp_hashfn(net, hnum, udptable->mask);
2484ba6aac15SKuniyuki Iwashima 	hslot = &udptable->hash[slot];
2485421b3885SShawn Bohrer 
248663c6f81cSEric Dumazet 	/* Do not bother scanning a too big list */
248763c6f81cSEric Dumazet 	if (hslot->count > 10)
248863c6f81cSEric Dumazet 		return NULL;
248963c6f81cSEric Dumazet 
2490421b3885SShawn Bohrer 	result = NULL;
2491ca065d0cSEric Dumazet 	sk_for_each_rcu(sk, &hslot->head) {
2492ca065d0cSEric Dumazet 		if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr,
2493fb74c277SDavid Ahern 					rmt_port, rmt_addr, dif, sdif, hnum)) {
2494ca065d0cSEric Dumazet 			if (result)
2495ca065d0cSEric Dumazet 				return NULL;
2496421b3885SShawn Bohrer 			result = sk;
2497421b3885SShawn Bohrer 		}
2498421b3885SShawn Bohrer 	}
2499421b3885SShawn Bohrer 
2500421b3885SShawn Bohrer 	return result;
2501421b3885SShawn Bohrer }
2502421b3885SShawn Bohrer 
2503421b3885SShawn Bohrer /* For unicast we should only early demux connected sockets or we can
2504421b3885SShawn Bohrer  * break forwarding setups.  The chains here can be long so only check
2505421b3885SShawn Bohrer  * if the first socket is an exact match and if not move on.
2506421b3885SShawn Bohrer  */
2507421b3885SShawn Bohrer static struct sock *__udp4_lib_demux_lookup(struct net *net,
2508421b3885SShawn Bohrer 					    __be16 loc_port, __be32 loc_addr,
2509421b3885SShawn Bohrer 					    __be16 rmt_port, __be32 rmt_addr,
25103fa6f616SDavid Ahern 					    int dif, int sdif)
2511421b3885SShawn Bohrer {
2512ba6aac15SKuniyuki Iwashima 	struct udp_table *udptable = net->ipv4.udp_table;
2513c7228317SJoe Perches 	INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr);
2514919dfa0bSKuniyuki Iwashima 	unsigned short hnum = ntohs(loc_port);
2515919dfa0bSKuniyuki Iwashima 	unsigned int hash2, slot2;
2516919dfa0bSKuniyuki Iwashima 	struct udp_hslot *hslot2;
2517919dfa0bSKuniyuki Iwashima 	__portpair ports;
2518ca065d0cSEric Dumazet 	struct sock *sk;
2519421b3885SShawn Bohrer 
2520919dfa0bSKuniyuki Iwashima 	hash2 = ipv4_portaddr_hash(net, loc_addr, hnum);
2521ba6aac15SKuniyuki Iwashima 	slot2 = hash2 & udptable->mask;
2522ba6aac15SKuniyuki Iwashima 	hslot2 = &udptable->hash2[slot2];
2523919dfa0bSKuniyuki Iwashima 	ports = INET_COMBINED_PORTS(rmt_port, hnum);
2524919dfa0bSKuniyuki Iwashima 
2525ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
2526eda090c3SEric Dumazet 		if (inet_match(net, sk, acookie, ports, dif, sdif))
2527ca065d0cSEric Dumazet 			return sk;
2528421b3885SShawn Bohrer 		/* Only check first socket in chain */
2529421b3885SShawn Bohrer 		break;
2530421b3885SShawn Bohrer 	}
2531ca065d0cSEric Dumazet 	return NULL;
2532421b3885SShawn Bohrer }
2533421b3885SShawn Bohrer 
25347487449cSPaolo Abeni int udp_v4_early_demux(struct sk_buff *skb)
2535421b3885SShawn Bohrer {
2536610438b7SEric Dumazet 	struct net *net = dev_net(skb->dev);
2537bc044e8dSPaolo Abeni 	struct in_device *in_dev = NULL;
2538610438b7SEric Dumazet 	const struct iphdr *iph;
2539610438b7SEric Dumazet 	const struct udphdr *uh;
2540ca065d0cSEric Dumazet 	struct sock *sk = NULL;
2541421b3885SShawn Bohrer 	struct dst_entry *dst;
2542421b3885SShawn Bohrer 	int dif = skb->dev->ifindex;
2543fb74c277SDavid Ahern 	int sdif = inet_sdif(skb);
25446e540309SShawn Bohrer 	int ours;
2545421b3885SShawn Bohrer 
2546421b3885SShawn Bohrer 	/* validate the packet */
2547421b3885SShawn Bohrer 	if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)))
25487487449cSPaolo Abeni 		return 0;
2549421b3885SShawn Bohrer 
2550610438b7SEric Dumazet 	iph = ip_hdr(skb);
2551610438b7SEric Dumazet 	uh = udp_hdr(skb);
2552610438b7SEric Dumazet 
2553996b44fcSPaolo Abeni 	if (skb->pkt_type == PACKET_MULTICAST) {
2554bc044e8dSPaolo Abeni 		in_dev = __in_dev_get_rcu(skb->dev);
25556e540309SShawn Bohrer 
25566e540309SShawn Bohrer 		if (!in_dev)
25577487449cSPaolo Abeni 			return 0;
25586e540309SShawn Bohrer 
25596e540309SShawn Bohrer 		ours = ip_check_mc_rcu(in_dev, iph->daddr, iph->saddr,
25606e540309SShawn Bohrer 				       iph->protocol);
25616e540309SShawn Bohrer 		if (!ours)
25627487449cSPaolo Abeni 			return 0;
2563ad0ea198SPaolo Abeni 
2564421b3885SShawn Bohrer 		sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr,
2565fb74c277SDavid Ahern 						   uh->source, iph->saddr,
2566fb74c277SDavid Ahern 						   dif, sdif);
25676e540309SShawn Bohrer 	} else if (skb->pkt_type == PACKET_HOST) {
2568421b3885SShawn Bohrer 		sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr,
25693fa6f616SDavid Ahern 					     uh->source, iph->saddr, dif, sdif);
25706e540309SShawn Bohrer 	}
2571421b3885SShawn Bohrer 
257241c6d650SReshetova, Elena 	if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
25737487449cSPaolo Abeni 		return 0;
2574421b3885SShawn Bohrer 
2575421b3885SShawn Bohrer 	skb->sk = sk;
257682eabd9eSAlexander Duyck 	skb->destructor = sock_efree;
25778f905c0eSEric Dumazet 	dst = rcu_dereference(sk->sk_rx_dst);
2578421b3885SShawn Bohrer 
2579421b3885SShawn Bohrer 	if (dst)
2580421b3885SShawn Bohrer 		dst = dst_check(dst, 0);
258110e2eb87SEric Dumazet 	if (dst) {
2582bc044e8dSPaolo Abeni 		u32 itag = 0;
2583bc044e8dSPaolo Abeni 
2584d24406c8SWei Wang 		/* set noref for now.
2585d24406c8SWei Wang 		 * any place which wants to hold dst has to call
2586d24406c8SWei Wang 		 * dst_hold_safe()
2587d24406c8SWei Wang 		 */
2588421b3885SShawn Bohrer 		skb_dst_set_noref(skb, dst);
2589bc044e8dSPaolo Abeni 
2590bc044e8dSPaolo Abeni 		/* for unconnected multicast sockets we need to validate
2591bc044e8dSPaolo Abeni 		 * the source on each packet
2592bc044e8dSPaolo Abeni 		 */
2593bc044e8dSPaolo Abeni 		if (!inet_sk(sk)->inet_daddr && in_dev)
2594bc044e8dSPaolo Abeni 			return ip_mc_validate_source(skb, iph->daddr,
25958d2b51b0SGuillaume Nault 						     iph->saddr,
25968d2b51b0SGuillaume Nault 						     iph->tos & IPTOS_RT_MASK,
2597bc044e8dSPaolo Abeni 						     skb->dev, in_dev, &itag);
2598421b3885SShawn Bohrer 	}
25997487449cSPaolo Abeni 	return 0;
260010e2eb87SEric Dumazet }
2601421b3885SShawn Bohrer 
2602db8dac20SDavid S. Miller int udp_rcv(struct sk_buff *skb)
2603db8dac20SDavid S. Miller {
2604ba6aac15SKuniyuki Iwashima 	return __udp4_lib_rcv(skb, dev_net(skb->dev)->ipv4.udp_table, IPPROTO_UDP);
2605db8dac20SDavid S. Miller }
2606db8dac20SDavid S. Miller 
26077d06b2e0SBrian Haley void udp_destroy_sock(struct sock *sk)
2608db8dac20SDavid S. Miller {
260944046a59STom Parkin 	struct udp_sock *up = udp_sk(sk);
26108a74ad60SEric Dumazet 	bool slow = lock_sock_fast(sk);
2611a8b897c7SPaolo Abeni 
2612a8b897c7SPaolo Abeni 	/* protects from races with udp_abort() */
2613a8b897c7SPaolo Abeni 	sock_set_flag(sk, SOCK_DEAD);
2614db8dac20SDavid S. Miller 	udp_flush_pending_frames(sk);
26158a74ad60SEric Dumazet 	unlock_sock_fast(sk, slow);
261660fb9567SPaolo Abeni 	if (static_branch_unlikely(&udp_encap_needed_key)) {
261760fb9567SPaolo Abeni 		if (up->encap_type) {
261844046a59STom Parkin 			void (*encap_destroy)(struct sock *sk);
26196aa7de05SMark Rutland 			encap_destroy = READ_ONCE(up->encap_destroy);
262044046a59STom Parkin 			if (encap_destroy)
262144046a59STom Parkin 				encap_destroy(sk);
262244046a59STom Parkin 		}
2623ac9a7f4cSEric Dumazet 		if (udp_test_bit(ENCAP_ENABLED, sk))
26249c480601SPaolo Abeni 			static_branch_dec(&udp_encap_needed_key);
262560fb9567SPaolo Abeni 	}
2626db8dac20SDavid S. Miller }
2627db8dac20SDavid S. Miller 
26281da177e4SLinus Torvalds /*
26291da177e4SLinus Torvalds  *	Socket option code for UDP
26301da177e4SLinus Torvalds  */
26314c0a6cb0SGerrit Renker int udp_lib_setsockopt(struct sock *sk, int level, int optname,
263291ac1ccaSChristoph Hellwig 		       sockptr_t optval, unsigned int optlen,
26334c0a6cb0SGerrit Renker 		       int (*push_pending_frames)(struct sock *))
26341da177e4SLinus Torvalds {
26351da177e4SLinus Torvalds 	struct udp_sock *up = udp_sk(sk);
26361c19448cSTom Herbert 	int val, valbool;
26371da177e4SLinus Torvalds 	int err = 0;
2638b2bf1e26SWang Chen 	int is_udplite = IS_UDPLITE(sk);
26391da177e4SLinus Torvalds 
26408a3854c7SPaolo Abeni 	if (level == SOL_SOCKET) {
26418a3854c7SPaolo Abeni 		err = sk_setsockopt(sk, level, optname, optval, optlen);
26428a3854c7SPaolo Abeni 
26438a3854c7SPaolo Abeni 		if (optname == SO_RCVBUF || optname == SO_RCVBUFFORCE) {
26448a3854c7SPaolo Abeni 			sockopt_lock_sock(sk);
26458a3854c7SPaolo Abeni 			/* paired with READ_ONCE in udp_rmem_release() */
26468a3854c7SPaolo Abeni 			WRITE_ONCE(up->forward_threshold, sk->sk_rcvbuf >> 2);
26478a3854c7SPaolo Abeni 			sockopt_release_sock(sk);
26488a3854c7SPaolo Abeni 		}
26498a3854c7SPaolo Abeni 		return err;
26508a3854c7SPaolo Abeni 	}
26518a3854c7SPaolo Abeni 
26521da177e4SLinus Torvalds 	if (optlen < sizeof(int))
26531da177e4SLinus Torvalds 		return -EINVAL;
26541da177e4SLinus Torvalds 
265591ac1ccaSChristoph Hellwig 	if (copy_from_sockptr(&val, optval, sizeof(val)))
26561da177e4SLinus Torvalds 		return -EFAULT;
26571da177e4SLinus Torvalds 
26581c19448cSTom Herbert 	valbool = val ? 1 : 0;
26591c19448cSTom Herbert 
26601da177e4SLinus Torvalds 	switch (optname) {
26611da177e4SLinus Torvalds 	case UDP_CORK:
26621da177e4SLinus Torvalds 		if (val != 0) {
266381b36803SEric Dumazet 			udp_set_bit(CORK, sk);
26641da177e4SLinus Torvalds 		} else {
266581b36803SEric Dumazet 			udp_clear_bit(CORK, sk);
26661da177e4SLinus Torvalds 			lock_sock(sk);
26674243cdc2SJoe Perches 			push_pending_frames(sk);
26681da177e4SLinus Torvalds 			release_sock(sk);
26691da177e4SLinus Torvalds 		}
26701da177e4SLinus Torvalds 		break;
26711da177e4SLinus Torvalds 
26721da177e4SLinus Torvalds 	case UDP_ENCAP:
26731da177e4SLinus Torvalds 		switch (val) {
26741da177e4SLinus Torvalds 		case 0:
2675fd1ac07fSAlexey Dobriyan #ifdef CONFIG_XFRM
26761da177e4SLinus Torvalds 		case UDP_ENCAP_ESPINUDP:
26771da177e4SLinus Torvalds 		case UDP_ENCAP_ESPINUDP_NON_IKE:
26780146dca7SSabrina Dubroca #if IS_ENABLED(CONFIG_IPV6)
26790146dca7SSabrina Dubroca 			if (sk->sk_family == AF_INET6)
26806d5a12ebSEric Dumazet 				WRITE_ONCE(up->encap_rcv,
26816d5a12ebSEric Dumazet 					   ipv6_stub->xfrm6_udp_encap_rcv);
26820146dca7SSabrina Dubroca 			else
26830146dca7SSabrina Dubroca #endif
26846d5a12ebSEric Dumazet 				WRITE_ONCE(up->encap_rcv,
26856d5a12ebSEric Dumazet 					   xfrm4_udp_encap_rcv);
2686fd1ac07fSAlexey Dobriyan #endif
2687a8eceea8SJoe Perches 			fallthrough;
2688342f0234SJames Chapman 		case UDP_ENCAP_L2TPINUDP:
268970a36f57SEric Dumazet 			WRITE_ONCE(up->encap_type, val);
2690ac9a7f4cSEric Dumazet 			udp_tunnel_encap_enable(sk);
26911da177e4SLinus Torvalds 			break;
26921da177e4SLinus Torvalds 		default:
26931da177e4SLinus Torvalds 			err = -ENOPROTOOPT;
26941da177e4SLinus Torvalds 			break;
26951da177e4SLinus Torvalds 		}
26961da177e4SLinus Torvalds 		break;
26971da177e4SLinus Torvalds 
26981c19448cSTom Herbert 	case UDP_NO_CHECK6_TX:
2699a0002127SEric Dumazet 		udp_set_no_check6_tx(sk, valbool);
27001c19448cSTom Herbert 		break;
27011c19448cSTom Herbert 
27021c19448cSTom Herbert 	case UDP_NO_CHECK6_RX:
2703bcbc1b1dSEric Dumazet 		udp_set_no_check6_rx(sk, valbool);
27041c19448cSTom Herbert 		break;
27051c19448cSTom Herbert 
2706bec1f6f6SWillem de Bruijn 	case UDP_SEGMENT:
2707bec1f6f6SWillem de Bruijn 		if (val < 0 || val > USHRT_MAX)
2708bec1f6f6SWillem de Bruijn 			return -EINVAL;
270918a419baSEric Dumazet 		WRITE_ONCE(up->gso_size, val);
2710bec1f6f6SWillem de Bruijn 		break;
2711bec1f6f6SWillem de Bruijn 
2712e20cf8d3SPaolo Abeni 	case UDP_GRO:
271378352f73SPaolo Abeni 
271478352f73SPaolo Abeni 		/* when enabling GRO, accept the related GSO packet type */
2715e20cf8d3SPaolo Abeni 		if (valbool)
2716ac9a7f4cSEric Dumazet 			udp_tunnel_encap_enable(sk);
2717e1dc0615SEric Dumazet 		udp_assign_bit(GRO_ENABLED, sk, valbool);
2718f5f52f08SEric Dumazet 		udp_assign_bit(ACCEPT_L4, sk, valbool);
2719e20cf8d3SPaolo Abeni 		break;
2720e20cf8d3SPaolo Abeni 
2721ba4e58ecSGerrit Renker 	/*
2722ba4e58ecSGerrit Renker 	 * 	UDP-Lite's partial checksum coverage (RFC 3828).
2723ba4e58ecSGerrit Renker 	 */
2724ba4e58ecSGerrit Renker 	/* The sender sets actual checksum coverage length via this option.
2725ba4e58ecSGerrit Renker 	 * The case coverage > packet length is handled by send module. */
2726ba4e58ecSGerrit Renker 	case UDPLITE_SEND_CSCOV:
2727b2bf1e26SWang Chen 		if (!is_udplite)         /* Disable the option on UDP sockets */
2728ba4e58ecSGerrit Renker 			return -ENOPROTOOPT;
2729ba4e58ecSGerrit Renker 		if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
2730ba4e58ecSGerrit Renker 			val = 8;
27314be929beSAlexey Dobriyan 		else if (val > USHRT_MAX)
27324be929beSAlexey Dobriyan 			val = USHRT_MAX;
2733*882af43aSEric Dumazet 		WRITE_ONCE(up->pcslen, val);
2734*882af43aSEric Dumazet 		udp_set_bit(UDPLITE_SEND_CC, sk);
2735ba4e58ecSGerrit Renker 		break;
2736ba4e58ecSGerrit Renker 
2737ba4e58ecSGerrit Renker 	/* The receiver specifies a minimum checksum coverage value. To make
2738ba4e58ecSGerrit Renker 	 * sense, this should be set to at least 8 (as done below). If zero is
2739ba4e58ecSGerrit Renker 	 * used, this again means full checksum coverage.                     */
2740ba4e58ecSGerrit Renker 	case UDPLITE_RECV_CSCOV:
2741b2bf1e26SWang Chen 		if (!is_udplite)         /* Disable the option on UDP sockets */
2742ba4e58ecSGerrit Renker 			return -ENOPROTOOPT;
2743ba4e58ecSGerrit Renker 		if (val != 0 && val < 8) /* Avoid silly minimal values.       */
2744ba4e58ecSGerrit Renker 			val = 8;
27454be929beSAlexey Dobriyan 		else if (val > USHRT_MAX)
27464be929beSAlexey Dobriyan 			val = USHRT_MAX;
2747*882af43aSEric Dumazet 		WRITE_ONCE(up->pcrlen, val);
2748*882af43aSEric Dumazet 		udp_set_bit(UDPLITE_RECV_CC, sk);
2749ba4e58ecSGerrit Renker 		break;
2750ba4e58ecSGerrit Renker 
27511da177e4SLinus Torvalds 	default:
27521da177e4SLinus Torvalds 		err = -ENOPROTOOPT;
27531da177e4SLinus Torvalds 		break;
27546516c655SStephen Hemminger 	}
27551da177e4SLinus Torvalds 
27561da177e4SLinus Torvalds 	return err;
27571da177e4SLinus Torvalds }
2758c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_setsockopt);
27591da177e4SLinus Torvalds 
2760a7b75c5aSChristoph Hellwig int udp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
2761a7b75c5aSChristoph Hellwig 		   unsigned int optlen)
2762db8dac20SDavid S. Miller {
27638a3854c7SPaolo Abeni 	if (level == SOL_UDP  ||  level == SOL_UDPLITE || level == SOL_SOCKET)
276491ac1ccaSChristoph Hellwig 		return udp_lib_setsockopt(sk, level, optname,
2765a7b75c5aSChristoph Hellwig 					  optval, optlen,
2766db8dac20SDavid S. Miller 					  udp_push_pending_frames);
2767db8dac20SDavid S. Miller 	return ip_setsockopt(sk, level, optname, optval, optlen);
2768db8dac20SDavid S. Miller }
2769db8dac20SDavid S. Miller 
27704c0a6cb0SGerrit Renker int udp_lib_getsockopt(struct sock *sk, int level, int optname,
27711da177e4SLinus Torvalds 		       char __user *optval, int __user *optlen)
27721da177e4SLinus Torvalds {
27731da177e4SLinus Torvalds 	struct udp_sock *up = udp_sk(sk);
27741da177e4SLinus Torvalds 	int val, len;
27751da177e4SLinus Torvalds 
27761da177e4SLinus Torvalds 	if (get_user(len, optlen))
27771da177e4SLinus Torvalds 		return -EFAULT;
27781da177e4SLinus Torvalds 
27791da177e4SLinus Torvalds 	len = min_t(unsigned int, len, sizeof(int));
27801da177e4SLinus Torvalds 
27811da177e4SLinus Torvalds 	if (len < 0)
27821da177e4SLinus Torvalds 		return -EINVAL;
27831da177e4SLinus Torvalds 
27841da177e4SLinus Torvalds 	switch (optname) {
27851da177e4SLinus Torvalds 	case UDP_CORK:
278681b36803SEric Dumazet 		val = udp_test_bit(CORK, sk);
27871da177e4SLinus Torvalds 		break;
27881da177e4SLinus Torvalds 
27891da177e4SLinus Torvalds 	case UDP_ENCAP:
279070a36f57SEric Dumazet 		val = READ_ONCE(up->encap_type);
27911da177e4SLinus Torvalds 		break;
27921da177e4SLinus Torvalds 
27931c19448cSTom Herbert 	case UDP_NO_CHECK6_TX:
2794a0002127SEric Dumazet 		val = udp_get_no_check6_tx(sk);
27951c19448cSTom Herbert 		break;
27961c19448cSTom Herbert 
27971c19448cSTom Herbert 	case UDP_NO_CHECK6_RX:
2798bcbc1b1dSEric Dumazet 		val = udp_get_no_check6_rx(sk);
27991c19448cSTom Herbert 		break;
28001c19448cSTom Herbert 
2801bec1f6f6SWillem de Bruijn 	case UDP_SEGMENT:
280218a419baSEric Dumazet 		val = READ_ONCE(up->gso_size);
2803bec1f6f6SWillem de Bruijn 		break;
2804bec1f6f6SWillem de Bruijn 
280598184612SNorman Maurer 	case UDP_GRO:
2806e1dc0615SEric Dumazet 		val = udp_test_bit(GRO_ENABLED, sk);
280798184612SNorman Maurer 		break;
280898184612SNorman Maurer 
2809ba4e58ecSGerrit Renker 	/* The following two cannot be changed on UDP sockets, the return is
2810ba4e58ecSGerrit Renker 	 * always 0 (which corresponds to the full checksum coverage of UDP). */
2811ba4e58ecSGerrit Renker 	case UDPLITE_SEND_CSCOV:
2812*882af43aSEric Dumazet 		val = READ_ONCE(up->pcslen);
2813ba4e58ecSGerrit Renker 		break;
2814ba4e58ecSGerrit Renker 
2815ba4e58ecSGerrit Renker 	case UDPLITE_RECV_CSCOV:
2816*882af43aSEric Dumazet 		val = READ_ONCE(up->pcrlen);
2817ba4e58ecSGerrit Renker 		break;
2818ba4e58ecSGerrit Renker 
28191da177e4SLinus Torvalds 	default:
28201da177e4SLinus Torvalds 		return -ENOPROTOOPT;
28216516c655SStephen Hemminger 	}
28221da177e4SLinus Torvalds 
28231da177e4SLinus Torvalds 	if (put_user(len, optlen))
28241da177e4SLinus Torvalds 		return -EFAULT;
28251da177e4SLinus Torvalds 	if (copy_to_user(optval, &val, len))
28261da177e4SLinus Torvalds 		return -EFAULT;
28271da177e4SLinus Torvalds 	return 0;
28281da177e4SLinus Torvalds }
2829c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_getsockopt);
28301da177e4SLinus Torvalds 
2831db8dac20SDavid S. Miller int udp_getsockopt(struct sock *sk, int level, int optname,
2832db8dac20SDavid S. Miller 		   char __user *optval, int __user *optlen)
2833db8dac20SDavid S. Miller {
2834db8dac20SDavid S. Miller 	if (level == SOL_UDP  ||  level == SOL_UDPLITE)
2835db8dac20SDavid S. Miller 		return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2836db8dac20SDavid S. Miller 	return ip_getsockopt(sk, level, optname, optval, optlen);
2837db8dac20SDavid S. Miller }
2838db8dac20SDavid S. Miller 
28391da177e4SLinus Torvalds /**
28401da177e4SLinus Torvalds  * 	udp_poll - wait for a UDP event.
28413628e3cbSAndrew Lunn  *	@file: - file struct
28423628e3cbSAndrew Lunn  *	@sock: - socket
28433628e3cbSAndrew Lunn  *	@wait: - poll table
28441da177e4SLinus Torvalds  *
28451da177e4SLinus Torvalds  *	This is same as datagram poll, except for the special case of
28461da177e4SLinus Torvalds  *	blocking sockets. If application is using a blocking fd
28471da177e4SLinus Torvalds  *	and a packet with checksum error is in the queue;
28481da177e4SLinus Torvalds  *	then it could get return from select indicating data available
28491da177e4SLinus Torvalds  *	but then block when reading it. Add special case code
28501da177e4SLinus Torvalds  *	to work around these arguably broken applications.
28511da177e4SLinus Torvalds  */
2852a11e1d43SLinus Torvalds __poll_t udp_poll(struct file *file, struct socket *sock, poll_table *wait)
28531da177e4SLinus Torvalds {
2854a11e1d43SLinus Torvalds 	__poll_t mask = datagram_poll(file, sock, wait);
28551da177e4SLinus Torvalds 	struct sock *sk = sock->sk;
28561da177e4SLinus Torvalds 
28573ef7cf57SEric Dumazet 	if (!skb_queue_empty_lockless(&udp_sk(sk)->reader_queue))
2858a9a08845SLinus Torvalds 		mask |= EPOLLIN | EPOLLRDNORM;
28592276f58aSPaolo Abeni 
28601da177e4SLinus Torvalds 	/* Check for false positives due to checksum errors */
2861a11e1d43SLinus Torvalds 	if ((mask & EPOLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
2862e83c6744SEric Dumazet 	    !(sk->sk_shutdown & RCV_SHUTDOWN) && first_packet_length(sk) == -1)
2863a9a08845SLinus Torvalds 		mask &= ~(EPOLLIN | EPOLLRDNORM);
28641da177e4SLinus Torvalds 
2865af493388SCong Wang 	/* psock ingress_msg queue should not contain any bad checksum frames */
2866af493388SCong Wang 	if (sk_is_readable(sk))
2867af493388SCong Wang 		mask |= EPOLLIN | EPOLLRDNORM;
28681da177e4SLinus Torvalds 	return mask;
28691da177e4SLinus Torvalds 
28701da177e4SLinus Torvalds }
2871a11e1d43SLinus Torvalds EXPORT_SYMBOL(udp_poll);
28721da177e4SLinus Torvalds 
28735d77dca8SDavid Ahern int udp_abort(struct sock *sk, int err)
28745d77dca8SDavid Ahern {
28754ddbcb88SAditi Ghag 	if (!has_current_bpf_ctx())
28765d77dca8SDavid Ahern 		lock_sock(sk);
28775d77dca8SDavid Ahern 
2878a8b897c7SPaolo Abeni 	/* udp{v6}_destroy_sock() sets it under the sk lock, avoid racing
2879a8b897c7SPaolo Abeni 	 * with close()
2880a8b897c7SPaolo Abeni 	 */
2881a8b897c7SPaolo Abeni 	if (sock_flag(sk, SOCK_DEAD))
2882a8b897c7SPaolo Abeni 		goto out;
2883a8b897c7SPaolo Abeni 
28845d77dca8SDavid Ahern 	sk->sk_err = err;
2885e3ae2365SAlexander Aring 	sk_error_report(sk);
2886286c72deSEric Dumazet 	__udp_disconnect(sk, 0);
28875d77dca8SDavid Ahern 
2888a8b897c7SPaolo Abeni out:
28894ddbcb88SAditi Ghag 	if (!has_current_bpf_ctx())
28905d77dca8SDavid Ahern 		release_sock(sk);
28915d77dca8SDavid Ahern 
28925d77dca8SDavid Ahern 	return 0;
28935d77dca8SDavid Ahern }
28945d77dca8SDavid Ahern EXPORT_SYMBOL_GPL(udp_abort);
28955d77dca8SDavid Ahern 
2896db8dac20SDavid S. Miller struct proto udp_prot = {
2897db8dac20SDavid S. Miller 	.name			= "UDP",
2898db8dac20SDavid S. Miller 	.owner			= THIS_MODULE,
2899db8dac20SDavid S. Miller 	.close			= udp_lib_close,
2900d74bad4eSAndrey Ignatov 	.pre_connect		= udp_pre_connect,
2901db8dac20SDavid S. Miller 	.connect		= ip4_datagram_connect,
2902db8dac20SDavid S. Miller 	.disconnect		= udp_disconnect,
2903db8dac20SDavid S. Miller 	.ioctl			= udp_ioctl,
2904850cbaddSPaolo Abeni 	.init			= udp_init_sock,
2905db8dac20SDavid S. Miller 	.destroy		= udp_destroy_sock,
2906db8dac20SDavid S. Miller 	.setsockopt		= udp_setsockopt,
2907db8dac20SDavid S. Miller 	.getsockopt		= udp_getsockopt,
2908db8dac20SDavid S. Miller 	.sendmsg		= udp_sendmsg,
2909db8dac20SDavid S. Miller 	.recvmsg		= udp_recvmsg,
29101d7e4538SDavid Howells 	.splice_eof		= udp_splice_eof,
29118141ed9fSSteffen Klassert 	.release_cb		= ip4_datagram_release_cb,
2912db8dac20SDavid S. Miller 	.hash			= udp_lib_hash,
2913db8dac20SDavid S. Miller 	.unhash			= udp_lib_unhash,
2914719f8358SEric Dumazet 	.rehash			= udp_v4_rehash,
2915db8dac20SDavid S. Miller 	.get_port		= udp_v4_get_port,
291691a760b2SMenglong Dong 	.put_port		= udp_lib_unhash,
29178a59f9d1SCong Wang #ifdef CONFIG_BPF_SYSCALL
29188a59f9d1SCong Wang 	.psock_update_sk_prot	= udp_bpf_update_proto,
29198a59f9d1SCong Wang #endif
2920db8dac20SDavid S. Miller 	.memory_allocated	= &udp_memory_allocated,
29210defbb0aSEric Dumazet 	.per_cpu_fw_alloc	= &udp_memory_per_cpu_fw_alloc,
29220defbb0aSEric Dumazet 
2923db8dac20SDavid S. Miller 	.sysctl_mem		= sysctl_udp_mem,
29241e802951STonghao Zhang 	.sysctl_wmem_offset	= offsetof(struct net, ipv4.sysctl_udp_wmem_min),
29251e802951STonghao Zhang 	.sysctl_rmem_offset	= offsetof(struct net, ipv4.sysctl_udp_rmem_min),
2926db8dac20SDavid S. Miller 	.obj_size		= sizeof(struct udp_sock),
292767fb4330SKuniyuki Iwashima 	.h.udp_table		= NULL,
29285d77dca8SDavid Ahern 	.diag_destroy		= udp_abort,
2929db8dac20SDavid S. Miller };
2930c482c568SEric Dumazet EXPORT_SYMBOL(udp_prot);
29311da177e4SLinus Torvalds 
29321da177e4SLinus Torvalds /* ------------------------------------------------------------------------ */
29331da177e4SLinus Torvalds #ifdef CONFIG_PROC_FS
29341da177e4SLinus Torvalds 
2935f44b1c51SAditi Ghag static unsigned short seq_file_family(const struct seq_file *seq);
2936f44b1c51SAditi Ghag static bool seq_sk_match(struct seq_file *seq, const struct sock *sk)
2937f44b1c51SAditi Ghag {
2938f44b1c51SAditi Ghag 	unsigned short family = seq_file_family(seq);
2939f44b1c51SAditi Ghag 
2940f44b1c51SAditi Ghag 	/* AF_UNSPEC is used as a match all */
2941f44b1c51SAditi Ghag 	return ((family == AF_UNSPEC || family == sk->sk_family) &&
2942f44b1c51SAditi Ghag 		net_eq(sock_net(sk), seq_file_net(seq)));
2943f44b1c51SAditi Ghag }
2944f44b1c51SAditi Ghag 
2945e4fe1bf1SAditi Ghag #ifdef CONFIG_BPF_SYSCALL
2946e4fe1bf1SAditi Ghag static const struct seq_operations bpf_iter_udp_seq_ops;
2947e4fe1bf1SAditi Ghag #endif
29487625d2e9SAditi Ghag static struct udp_table *udp_get_table_seq(struct seq_file *seq,
2949478aee5dSKuniyuki Iwashima 					   struct net *net)
2950478aee5dSKuniyuki Iwashima {
29517625d2e9SAditi Ghag 	const struct udp_seq_afinfo *afinfo;
29527625d2e9SAditi Ghag 
2953e4fe1bf1SAditi Ghag #ifdef CONFIG_BPF_SYSCALL
2954e4fe1bf1SAditi Ghag 	if (seq->op == &bpf_iter_udp_seq_ops)
29557625d2e9SAditi Ghag 		return net->ipv4.udp_table;
2956e4fe1bf1SAditi Ghag #endif
29577625d2e9SAditi Ghag 
29587625d2e9SAditi Ghag 	afinfo = pde_data(file_inode(seq->file));
2959478aee5dSKuniyuki Iwashima 	return afinfo->udp_table ? : net->ipv4.udp_table;
2960478aee5dSKuniyuki Iwashima }
2961478aee5dSKuniyuki Iwashima 
2962645ca708SEric Dumazet static struct sock *udp_get_first(struct seq_file *seq, int start)
29631da177e4SLinus Torvalds {
29641da177e4SLinus Torvalds 	struct udp_iter_state *state = seq->private;
29656f191efeSDenis V. Lunev 	struct net *net = seq_file_net(seq);
2966478aee5dSKuniyuki Iwashima 	struct udp_table *udptable;
2967919dfa0bSKuniyuki Iwashima 	struct sock *sk;
29681da177e4SLinus Torvalds 
29697625d2e9SAditi Ghag 	udptable = udp_get_table_seq(seq, net);
2970478aee5dSKuniyuki Iwashima 
2971478aee5dSKuniyuki Iwashima 	for (state->bucket = start; state->bucket <= udptable->mask;
2972f86dcc5aSEric Dumazet 	     ++state->bucket) {
2973478aee5dSKuniyuki Iwashima 		struct udp_hslot *hslot = &udptable->hash[state->bucket];
2974f86dcc5aSEric Dumazet 
2975ca065d0cSEric Dumazet 		if (hlist_empty(&hslot->head))
2976f86dcc5aSEric Dumazet 			continue;
2977f86dcc5aSEric Dumazet 
2978645ca708SEric Dumazet 		spin_lock_bh(&hslot->lock);
2979ca065d0cSEric Dumazet 		sk_for_each(sk, &hslot->head) {
2980f44b1c51SAditi Ghag 			if (seq_sk_match(seq, sk))
29811da177e4SLinus Torvalds 				goto found;
29821da177e4SLinus Torvalds 		}
2983645ca708SEric Dumazet 		spin_unlock_bh(&hslot->lock);
29841da177e4SLinus Torvalds 	}
29851da177e4SLinus Torvalds 	sk = NULL;
29861da177e4SLinus Torvalds found:
29871da177e4SLinus Torvalds 	return sk;
29881da177e4SLinus Torvalds }
29891da177e4SLinus Torvalds 
29901da177e4SLinus Torvalds static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
29911da177e4SLinus Torvalds {
29921da177e4SLinus Torvalds 	struct udp_iter_state *state = seq->private;
29936f191efeSDenis V. Lunev 	struct net *net = seq_file_net(seq);
2994478aee5dSKuniyuki Iwashima 	struct udp_table *udptable;
29951da177e4SLinus Torvalds 
29961da177e4SLinus Torvalds 	do {
2997ca065d0cSEric Dumazet 		sk = sk_next(sk);
2998f44b1c51SAditi Ghag 	} while (sk && !seq_sk_match(seq, sk));
29991da177e4SLinus Torvalds 
3000645ca708SEric Dumazet 	if (!sk) {
30017625d2e9SAditi Ghag 		udptable = udp_get_table_seq(seq, net);
3002478aee5dSKuniyuki Iwashima 
3003478aee5dSKuniyuki Iwashima 		if (state->bucket <= udptable->mask)
3004478aee5dSKuniyuki Iwashima 			spin_unlock_bh(&udptable->hash[state->bucket].lock);
3005478aee5dSKuniyuki Iwashima 
3006645ca708SEric Dumazet 		return udp_get_first(seq, state->bucket + 1);
30071da177e4SLinus Torvalds 	}
30081da177e4SLinus Torvalds 	return sk;
30091da177e4SLinus Torvalds }
30101da177e4SLinus Torvalds 
30111da177e4SLinus Torvalds static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
30121da177e4SLinus Torvalds {
3013645ca708SEric Dumazet 	struct sock *sk = udp_get_first(seq, 0);
30141da177e4SLinus Torvalds 
30151da177e4SLinus Torvalds 	if (sk)
30161da177e4SLinus Torvalds 		while (pos && (sk = udp_get_next(seq, sk)) != NULL)
30171da177e4SLinus Torvalds 			--pos;
30181da177e4SLinus Torvalds 	return pos ? NULL : sk;
30191da177e4SLinus Torvalds }
30201da177e4SLinus Torvalds 
3021a3d2599bSChristoph Hellwig void *udp_seq_start(struct seq_file *seq, loff_t *pos)
30221da177e4SLinus Torvalds {
302330842f29SVitaly Mayatskikh 	struct udp_iter_state *state = seq->private;
3024f86dcc5aSEric Dumazet 	state->bucket = MAX_UDP_PORTS;
302530842f29SVitaly Mayatskikh 
3026b50660f1SYOSHIFUJI Hideaki 	return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
30271da177e4SLinus Torvalds }
3028a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_start);
30291da177e4SLinus Torvalds 
3030a3d2599bSChristoph Hellwig void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
30311da177e4SLinus Torvalds {
30321da177e4SLinus Torvalds 	struct sock *sk;
30331da177e4SLinus Torvalds 
3034b50660f1SYOSHIFUJI Hideaki 	if (v == SEQ_START_TOKEN)
30351da177e4SLinus Torvalds 		sk = udp_get_idx(seq, 0);
30361da177e4SLinus Torvalds 	else
30371da177e4SLinus Torvalds 		sk = udp_get_next(seq, v);
30381da177e4SLinus Torvalds 
30391da177e4SLinus Torvalds 	++*pos;
30401da177e4SLinus Torvalds 	return sk;
30411da177e4SLinus Torvalds }
3042a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_next);
30431da177e4SLinus Torvalds 
3044a3d2599bSChristoph Hellwig void udp_seq_stop(struct seq_file *seq, void *v)
30451da177e4SLinus Torvalds {
3046645ca708SEric Dumazet 	struct udp_iter_state *state = seq->private;
3047478aee5dSKuniyuki Iwashima 	struct udp_table *udptable;
3048645ca708SEric Dumazet 
30497625d2e9SAditi Ghag 	udptable = udp_get_table_seq(seq, seq_file_net(seq));
3050478aee5dSKuniyuki Iwashima 
3051478aee5dSKuniyuki Iwashima 	if (state->bucket <= udptable->mask)
3052478aee5dSKuniyuki Iwashima 		spin_unlock_bh(&udptable->hash[state->bucket].lock);
30531da177e4SLinus Torvalds }
3054a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_stop);
3055db8dac20SDavid S. Miller 
3056db8dac20SDavid S. Miller /* ------------------------------------------------------------------------ */
30575e659e4cSPavel Emelyanov static void udp4_format_sock(struct sock *sp, struct seq_file *f,
3058652586dfSTetsuo Handa 		int bucket)
3059db8dac20SDavid S. Miller {
3060db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sp);
3061c720c7e8SEric Dumazet 	__be32 dest = inet->inet_daddr;
3062c720c7e8SEric Dumazet 	__be32 src  = inet->inet_rcv_saddr;
3063c720c7e8SEric Dumazet 	__u16 destp	  = ntohs(inet->inet_dport);
3064c720c7e8SEric Dumazet 	__u16 srcp	  = ntohs(inet->inet_sport);
3065db8dac20SDavid S. Miller 
3066f86dcc5aSEric Dumazet 	seq_printf(f, "%5d: %08X:%04X %08X:%04X"
3067ea9a0379SPatrick Talbert 		" %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %u",
3068db8dac20SDavid S. Miller 		bucket, src, srcp, dest, destp, sp->sk_state,
306931e6d363SEric Dumazet 		sk_wmem_alloc_get(sp),
30706c206b20SPaolo Abeni 		udp_rqueue_get(sp),
3071a7cb5a49SEric W. Biederman 		0, 0L, 0,
3072a7cb5a49SEric W. Biederman 		from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
3073a7cb5a49SEric W. Biederman 		0, sock_i_ino(sp),
307441c6d650SReshetova, Elena 		refcount_read(&sp->sk_refcnt), sp,
3075652586dfSTetsuo Handa 		atomic_read(&sp->sk_drops));
3076db8dac20SDavid S. Miller }
3077db8dac20SDavid S. Miller 
3078db8dac20SDavid S. Miller int udp4_seq_show(struct seq_file *seq, void *v)
3079db8dac20SDavid S. Miller {
3080652586dfSTetsuo Handa 	seq_setwidth(seq, 127);
3081db8dac20SDavid S. Miller 	if (v == SEQ_START_TOKEN)
3082652586dfSTetsuo Handa 		seq_puts(seq, "   sl  local_address rem_address   st tx_queue "
3083db8dac20SDavid S. Miller 			   "rx_queue tr tm->when retrnsmt   uid  timeout "
3084cb61cb9bSEric Dumazet 			   "inode ref pointer drops");
3085db8dac20SDavid S. Miller 	else {
3086db8dac20SDavid S. Miller 		struct udp_iter_state *state = seq->private;
3087db8dac20SDavid S. Miller 
3088652586dfSTetsuo Handa 		udp4_format_sock(v, seq, state->bucket);
3089db8dac20SDavid S. Miller 	}
3090652586dfSTetsuo Handa 	seq_pad(seq, '\n');
3091db8dac20SDavid S. Miller 	return 0;
3092db8dac20SDavid S. Miller }
3093db8dac20SDavid S. Miller 
30945788b3a0SYonghong Song #ifdef CONFIG_BPF_SYSCALL
30955788b3a0SYonghong Song struct bpf_iter__udp {
30965788b3a0SYonghong Song 	__bpf_md_ptr(struct bpf_iter_meta *, meta);
30975788b3a0SYonghong Song 	__bpf_md_ptr(struct udp_sock *, udp_sk);
30985788b3a0SYonghong Song 	uid_t uid __aligned(8);
30995788b3a0SYonghong Song 	int bucket __aligned(8);
31005788b3a0SYonghong Song };
31015788b3a0SYonghong Song 
3102c96dac8dSAditi Ghag struct bpf_udp_iter_state {
3103c96dac8dSAditi Ghag 	struct udp_iter_state state;
3104c96dac8dSAditi Ghag 	unsigned int cur_sk;
3105c96dac8dSAditi Ghag 	unsigned int end_sk;
3106c96dac8dSAditi Ghag 	unsigned int max_sk;
3107c96dac8dSAditi Ghag 	int offset;
3108c96dac8dSAditi Ghag 	struct sock **batch;
3109c96dac8dSAditi Ghag 	bool st_bucket_done;
3110c96dac8dSAditi Ghag };
3111c96dac8dSAditi Ghag 
3112c96dac8dSAditi Ghag static int bpf_iter_udp_realloc_batch(struct bpf_udp_iter_state *iter,
3113c96dac8dSAditi Ghag 				      unsigned int new_batch_sz);
3114c96dac8dSAditi Ghag static struct sock *bpf_iter_udp_batch(struct seq_file *seq)
3115c96dac8dSAditi Ghag {
3116c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = seq->private;
3117c96dac8dSAditi Ghag 	struct udp_iter_state *state = &iter->state;
3118c96dac8dSAditi Ghag 	struct net *net = seq_file_net(seq);
3119c96dac8dSAditi Ghag 	struct udp_table *udptable;
3120c96dac8dSAditi Ghag 	unsigned int batch_sks = 0;
3121c96dac8dSAditi Ghag 	bool resized = false;
3122c96dac8dSAditi Ghag 	struct sock *sk;
3123c96dac8dSAditi Ghag 
3124c96dac8dSAditi Ghag 	/* The current batch is done, so advance the bucket. */
3125c96dac8dSAditi Ghag 	if (iter->st_bucket_done) {
3126c96dac8dSAditi Ghag 		state->bucket++;
3127c96dac8dSAditi Ghag 		iter->offset = 0;
3128c96dac8dSAditi Ghag 	}
3129c96dac8dSAditi Ghag 
3130c96dac8dSAditi Ghag 	udptable = udp_get_table_seq(seq, net);
3131c96dac8dSAditi Ghag 
3132c96dac8dSAditi Ghag again:
3133c96dac8dSAditi Ghag 	/* New batch for the next bucket.
3134c96dac8dSAditi Ghag 	 * Iterate over the hash table to find a bucket with sockets matching
3135c96dac8dSAditi Ghag 	 * the iterator attributes, and return the first matching socket from
3136c96dac8dSAditi Ghag 	 * the bucket. The remaining matched sockets from the bucket are batched
3137c96dac8dSAditi Ghag 	 * before releasing the bucket lock. This allows BPF programs that are
3138c96dac8dSAditi Ghag 	 * called in seq_show to acquire the bucket lock if needed.
3139c96dac8dSAditi Ghag 	 */
3140c96dac8dSAditi Ghag 	iter->cur_sk = 0;
3141c96dac8dSAditi Ghag 	iter->end_sk = 0;
3142c96dac8dSAditi Ghag 	iter->st_bucket_done = false;
3143c96dac8dSAditi Ghag 	batch_sks = 0;
3144c96dac8dSAditi Ghag 
3145c96dac8dSAditi Ghag 	for (; state->bucket <= udptable->mask; state->bucket++) {
3146c96dac8dSAditi Ghag 		struct udp_hslot *hslot2 = &udptable->hash2[state->bucket];
3147c96dac8dSAditi Ghag 
3148c96dac8dSAditi Ghag 		if (hlist_empty(&hslot2->head)) {
3149c96dac8dSAditi Ghag 			iter->offset = 0;
3150c96dac8dSAditi Ghag 			continue;
3151c96dac8dSAditi Ghag 		}
3152c96dac8dSAditi Ghag 
3153c96dac8dSAditi Ghag 		spin_lock_bh(&hslot2->lock);
3154c96dac8dSAditi Ghag 		udp_portaddr_for_each_entry(sk, &hslot2->head) {
3155c96dac8dSAditi Ghag 			if (seq_sk_match(seq, sk)) {
3156c96dac8dSAditi Ghag 				/* Resume from the last iterated socket at the
3157c96dac8dSAditi Ghag 				 * offset in the bucket before iterator was stopped.
3158c96dac8dSAditi Ghag 				 */
3159c96dac8dSAditi Ghag 				if (iter->offset) {
3160c96dac8dSAditi Ghag 					--iter->offset;
3161c96dac8dSAditi Ghag 					continue;
3162c96dac8dSAditi Ghag 				}
3163c96dac8dSAditi Ghag 				if (iter->end_sk < iter->max_sk) {
3164c96dac8dSAditi Ghag 					sock_hold(sk);
3165c96dac8dSAditi Ghag 					iter->batch[iter->end_sk++] = sk;
3166c96dac8dSAditi Ghag 				}
3167c96dac8dSAditi Ghag 				batch_sks++;
3168c96dac8dSAditi Ghag 			}
3169c96dac8dSAditi Ghag 		}
3170c96dac8dSAditi Ghag 		spin_unlock_bh(&hslot2->lock);
3171c96dac8dSAditi Ghag 
3172c96dac8dSAditi Ghag 		if (iter->end_sk)
3173c96dac8dSAditi Ghag 			break;
3174c96dac8dSAditi Ghag 
3175c96dac8dSAditi Ghag 		/* Reset the current bucket's offset before moving to the next bucket. */
3176c96dac8dSAditi Ghag 		iter->offset = 0;
3177c96dac8dSAditi Ghag 	}
3178c96dac8dSAditi Ghag 
3179c96dac8dSAditi Ghag 	/* All done: no batch made. */
3180c96dac8dSAditi Ghag 	if (!iter->end_sk)
3181c96dac8dSAditi Ghag 		return NULL;
3182c96dac8dSAditi Ghag 
3183c96dac8dSAditi Ghag 	if (iter->end_sk == batch_sks) {
3184c96dac8dSAditi Ghag 		/* Batching is done for the current bucket; return the first
3185c96dac8dSAditi Ghag 		 * socket to be iterated from the batch.
3186c96dac8dSAditi Ghag 		 */
3187c96dac8dSAditi Ghag 		iter->st_bucket_done = true;
3188c96dac8dSAditi Ghag 		goto done;
3189c96dac8dSAditi Ghag 	}
3190c96dac8dSAditi Ghag 	if (!resized && !bpf_iter_udp_realloc_batch(iter, batch_sks * 3 / 2)) {
3191c96dac8dSAditi Ghag 		resized = true;
3192c96dac8dSAditi Ghag 		/* After allocating a larger batch, retry one more time to grab
3193c96dac8dSAditi Ghag 		 * the whole bucket.
3194c96dac8dSAditi Ghag 		 */
3195c96dac8dSAditi Ghag 		state->bucket--;
3196c96dac8dSAditi Ghag 		goto again;
3197c96dac8dSAditi Ghag 	}
3198c96dac8dSAditi Ghag done:
3199c96dac8dSAditi Ghag 	return iter->batch[0];
3200c96dac8dSAditi Ghag }
3201c96dac8dSAditi Ghag 
3202c96dac8dSAditi Ghag static void *bpf_iter_udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3203c96dac8dSAditi Ghag {
3204c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = seq->private;
3205c96dac8dSAditi Ghag 	struct sock *sk;
3206c96dac8dSAditi Ghag 
3207c96dac8dSAditi Ghag 	/* Whenever seq_next() is called, the iter->cur_sk is
3208c96dac8dSAditi Ghag 	 * done with seq_show(), so unref the iter->cur_sk.
3209c96dac8dSAditi Ghag 	 */
3210c96dac8dSAditi Ghag 	if (iter->cur_sk < iter->end_sk) {
3211c96dac8dSAditi Ghag 		sock_put(iter->batch[iter->cur_sk++]);
3212c96dac8dSAditi Ghag 		++iter->offset;
3213c96dac8dSAditi Ghag 	}
3214c96dac8dSAditi Ghag 
3215c96dac8dSAditi Ghag 	/* After updating iter->cur_sk, check if there are more sockets
3216c96dac8dSAditi Ghag 	 * available in the current bucket batch.
3217c96dac8dSAditi Ghag 	 */
3218c96dac8dSAditi Ghag 	if (iter->cur_sk < iter->end_sk)
3219c96dac8dSAditi Ghag 		sk = iter->batch[iter->cur_sk];
3220c96dac8dSAditi Ghag 	else
3221c96dac8dSAditi Ghag 		/* Prepare a new batch. */
3222c96dac8dSAditi Ghag 		sk = bpf_iter_udp_batch(seq);
3223c96dac8dSAditi Ghag 
3224c96dac8dSAditi Ghag 	++*pos;
3225c96dac8dSAditi Ghag 	return sk;
3226c96dac8dSAditi Ghag }
3227c96dac8dSAditi Ghag 
3228c96dac8dSAditi Ghag static void *bpf_iter_udp_seq_start(struct seq_file *seq, loff_t *pos)
3229c96dac8dSAditi Ghag {
3230c96dac8dSAditi Ghag 	/* bpf iter does not support lseek, so it always
3231c96dac8dSAditi Ghag 	 * continue from where it was stop()-ped.
3232c96dac8dSAditi Ghag 	 */
3233c96dac8dSAditi Ghag 	if (*pos)
3234c96dac8dSAditi Ghag 		return bpf_iter_udp_batch(seq);
3235c96dac8dSAditi Ghag 
3236c96dac8dSAditi Ghag 	return SEQ_START_TOKEN;
3237c96dac8dSAditi Ghag }
3238c96dac8dSAditi Ghag 
32395788b3a0SYonghong Song static int udp_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
32405788b3a0SYonghong Song 			     struct udp_sock *udp_sk, uid_t uid, int bucket)
32415788b3a0SYonghong Song {
32425788b3a0SYonghong Song 	struct bpf_iter__udp ctx;
32435788b3a0SYonghong Song 
32445788b3a0SYonghong Song 	meta->seq_num--;  /* skip SEQ_START_TOKEN */
32455788b3a0SYonghong Song 	ctx.meta = meta;
32465788b3a0SYonghong Song 	ctx.udp_sk = udp_sk;
32475788b3a0SYonghong Song 	ctx.uid = uid;
32485788b3a0SYonghong Song 	ctx.bucket = bucket;
32495788b3a0SYonghong Song 	return bpf_iter_run_prog(prog, &ctx);
32505788b3a0SYonghong Song }
32515788b3a0SYonghong Song 
32525788b3a0SYonghong Song static int bpf_iter_udp_seq_show(struct seq_file *seq, void *v)
32535788b3a0SYonghong Song {
32545788b3a0SYonghong Song 	struct udp_iter_state *state = seq->private;
32555788b3a0SYonghong Song 	struct bpf_iter_meta meta;
32565788b3a0SYonghong Song 	struct bpf_prog *prog;
32575788b3a0SYonghong Song 	struct sock *sk = v;
32585788b3a0SYonghong Song 	uid_t uid;
3259c96dac8dSAditi Ghag 	int ret;
32605788b3a0SYonghong Song 
32615788b3a0SYonghong Song 	if (v == SEQ_START_TOKEN)
32625788b3a0SYonghong Song 		return 0;
32635788b3a0SYonghong Song 
3264c96dac8dSAditi Ghag 	lock_sock(sk);
3265c96dac8dSAditi Ghag 
3266c96dac8dSAditi Ghag 	if (unlikely(sk_unhashed(sk))) {
3267c96dac8dSAditi Ghag 		ret = SEQ_SKIP;
3268c96dac8dSAditi Ghag 		goto unlock;
3269c96dac8dSAditi Ghag 	}
3270c96dac8dSAditi Ghag 
32715788b3a0SYonghong Song 	uid = from_kuid_munged(seq_user_ns(seq), sock_i_uid(sk));
32725788b3a0SYonghong Song 	meta.seq = seq;
32735788b3a0SYonghong Song 	prog = bpf_iter_get_info(&meta, false);
3274c96dac8dSAditi Ghag 	ret = udp_prog_seq_show(prog, &meta, v, uid, state->bucket);
3275c96dac8dSAditi Ghag 
3276c96dac8dSAditi Ghag unlock:
3277c96dac8dSAditi Ghag 	release_sock(sk);
3278c96dac8dSAditi Ghag 	return ret;
3279c96dac8dSAditi Ghag }
3280c96dac8dSAditi Ghag 
3281c96dac8dSAditi Ghag static void bpf_iter_udp_put_batch(struct bpf_udp_iter_state *iter)
3282c96dac8dSAditi Ghag {
3283c96dac8dSAditi Ghag 	while (iter->cur_sk < iter->end_sk)
3284c96dac8dSAditi Ghag 		sock_put(iter->batch[iter->cur_sk++]);
32855788b3a0SYonghong Song }
32865788b3a0SYonghong Song 
32875788b3a0SYonghong Song static void bpf_iter_udp_seq_stop(struct seq_file *seq, void *v)
32885788b3a0SYonghong Song {
3289c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = seq->private;
32905788b3a0SYonghong Song 	struct bpf_iter_meta meta;
32915788b3a0SYonghong Song 	struct bpf_prog *prog;
32925788b3a0SYonghong Song 
32935788b3a0SYonghong Song 	if (!v) {
32945788b3a0SYonghong Song 		meta.seq = seq;
32955788b3a0SYonghong Song 		prog = bpf_iter_get_info(&meta, true);
32965788b3a0SYonghong Song 		if (prog)
32975788b3a0SYonghong Song 			(void)udp_prog_seq_show(prog, &meta, v, 0, 0);
32985788b3a0SYonghong Song 	}
32995788b3a0SYonghong Song 
3300c96dac8dSAditi Ghag 	if (iter->cur_sk < iter->end_sk) {
3301c96dac8dSAditi Ghag 		bpf_iter_udp_put_batch(iter);
3302c96dac8dSAditi Ghag 		iter->st_bucket_done = false;
3303c96dac8dSAditi Ghag 	}
33045788b3a0SYonghong Song }
33055788b3a0SYonghong Song 
33065788b3a0SYonghong Song static const struct seq_operations bpf_iter_udp_seq_ops = {
3307c96dac8dSAditi Ghag 	.start		= bpf_iter_udp_seq_start,
3308c96dac8dSAditi Ghag 	.next		= bpf_iter_udp_seq_next,
33095788b3a0SYonghong Song 	.stop		= bpf_iter_udp_seq_stop,
33105788b3a0SYonghong Song 	.show		= bpf_iter_udp_seq_show,
33115788b3a0SYonghong Song };
33125788b3a0SYonghong Song #endif
33135788b3a0SYonghong Song 
3314f44b1c51SAditi Ghag static unsigned short seq_file_family(const struct seq_file *seq)
3315f44b1c51SAditi Ghag {
3316f44b1c51SAditi Ghag 	const struct udp_seq_afinfo *afinfo;
3317f44b1c51SAditi Ghag 
3318f44b1c51SAditi Ghag #ifdef CONFIG_BPF_SYSCALL
3319f44b1c51SAditi Ghag 	/* BPF iterator: bpf programs to filter sockets. */
3320f44b1c51SAditi Ghag 	if (seq->op == &bpf_iter_udp_seq_ops)
3321f44b1c51SAditi Ghag 		return AF_UNSPEC;
3322f44b1c51SAditi Ghag #endif
3323f44b1c51SAditi Ghag 
3324f44b1c51SAditi Ghag 	/* Proc fs iterator */
3325f44b1c51SAditi Ghag 	afinfo = pde_data(file_inode(seq->file));
3326f44b1c51SAditi Ghag 	return afinfo->family;
3327f44b1c51SAditi Ghag }
3328f44b1c51SAditi Ghag 
3329c3506372SChristoph Hellwig const struct seq_operations udp_seq_ops = {
3330a3d2599bSChristoph Hellwig 	.start		= udp_seq_start,
3331a3d2599bSChristoph Hellwig 	.next		= udp_seq_next,
3332a3d2599bSChristoph Hellwig 	.stop		= udp_seq_stop,
3333a3d2599bSChristoph Hellwig 	.show		= udp4_seq_show,
3334a3d2599bSChristoph Hellwig };
3335c3506372SChristoph Hellwig EXPORT_SYMBOL(udp_seq_ops);
333673cb88ecSArjan van de Ven 
3337db8dac20SDavid S. Miller static struct udp_seq_afinfo udp4_seq_afinfo = {
3338db8dac20SDavid S. Miller 	.family		= AF_INET,
3339478aee5dSKuniyuki Iwashima 	.udp_table	= NULL,
3340db8dac20SDavid S. Miller };
3341db8dac20SDavid S. Miller 
33422c8c1e72SAlexey Dobriyan static int __net_init udp4_proc_init_net(struct net *net)
334315439febSPavel Emelyanov {
3344c3506372SChristoph Hellwig 	if (!proc_create_net_data("udp", 0444, net->proc_net, &udp_seq_ops,
3345c3506372SChristoph Hellwig 			sizeof(struct udp_iter_state), &udp4_seq_afinfo))
3346a3d2599bSChristoph Hellwig 		return -ENOMEM;
3347a3d2599bSChristoph Hellwig 	return 0;
334815439febSPavel Emelyanov }
334915439febSPavel Emelyanov 
33502c8c1e72SAlexey Dobriyan static void __net_exit udp4_proc_exit_net(struct net *net)
335115439febSPavel Emelyanov {
3352a3d2599bSChristoph Hellwig 	remove_proc_entry("udp", net->proc_net);
335315439febSPavel Emelyanov }
335415439febSPavel Emelyanov 
335515439febSPavel Emelyanov static struct pernet_operations udp4_net_ops = {
335615439febSPavel Emelyanov 	.init = udp4_proc_init_net,
335715439febSPavel Emelyanov 	.exit = udp4_proc_exit_net,
335815439febSPavel Emelyanov };
335915439febSPavel Emelyanov 
3360db8dac20SDavid S. Miller int __init udp4_proc_init(void)
3361db8dac20SDavid S. Miller {
336215439febSPavel Emelyanov 	return register_pernet_subsys(&udp4_net_ops);
3363db8dac20SDavid S. Miller }
3364db8dac20SDavid S. Miller 
3365db8dac20SDavid S. Miller void udp4_proc_exit(void)
3366db8dac20SDavid S. Miller {
336715439febSPavel Emelyanov 	unregister_pernet_subsys(&udp4_net_ops);
3368db8dac20SDavid S. Miller }
33691da177e4SLinus Torvalds #endif /* CONFIG_PROC_FS */
33701da177e4SLinus Torvalds 
3371f86dcc5aSEric Dumazet static __initdata unsigned long uhash_entries;
3372f86dcc5aSEric Dumazet static int __init set_uhash_entries(char *str)
3373645ca708SEric Dumazet {
3374413c27d8SEldad Zack 	ssize_t ret;
3375413c27d8SEldad Zack 
3376f86dcc5aSEric Dumazet 	if (!str)
3377f86dcc5aSEric Dumazet 		return 0;
3378413c27d8SEldad Zack 
3379413c27d8SEldad Zack 	ret = kstrtoul(str, 0, &uhash_entries);
3380413c27d8SEldad Zack 	if (ret)
3381413c27d8SEldad Zack 		return 0;
3382413c27d8SEldad Zack 
3383f86dcc5aSEric Dumazet 	if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
3384f86dcc5aSEric Dumazet 		uhash_entries = UDP_HTABLE_SIZE_MIN;
3385f86dcc5aSEric Dumazet 	return 1;
3386f86dcc5aSEric Dumazet }
3387f86dcc5aSEric Dumazet __setup("uhash_entries=", set_uhash_entries);
3388645ca708SEric Dumazet 
3389f86dcc5aSEric Dumazet void __init udp_table_init(struct udp_table *table, const char *name)
3390f86dcc5aSEric Dumazet {
3391f86dcc5aSEric Dumazet 	unsigned int i;
3392f86dcc5aSEric Dumazet 
3393f86dcc5aSEric Dumazet 	table->hash = alloc_large_system_hash(name,
3394512615b6SEric Dumazet 					      2 * sizeof(struct udp_hslot),
3395f86dcc5aSEric Dumazet 					      uhash_entries,
3396f86dcc5aSEric Dumazet 					      21, /* one slot per 2 MB */
3397f86dcc5aSEric Dumazet 					      0,
3398f86dcc5aSEric Dumazet 					      &table->log,
3399f86dcc5aSEric Dumazet 					      &table->mask,
340031fe62b9STim Bird 					      UDP_HTABLE_SIZE_MIN,
34019804985bSKuniyuki Iwashima 					      UDP_HTABLE_SIZE_MAX);
340231fe62b9STim Bird 
3403512615b6SEric Dumazet 	table->hash2 = table->hash + (table->mask + 1);
3404f86dcc5aSEric Dumazet 	for (i = 0; i <= table->mask; i++) {
3405ca065d0cSEric Dumazet 		INIT_HLIST_HEAD(&table->hash[i].head);
3406fdcc8aa9SEric Dumazet 		table->hash[i].count = 0;
3407645ca708SEric Dumazet 		spin_lock_init(&table->hash[i].lock);
3408645ca708SEric Dumazet 	}
3409512615b6SEric Dumazet 	for (i = 0; i <= table->mask; i++) {
3410ca065d0cSEric Dumazet 		INIT_HLIST_HEAD(&table->hash2[i].head);
3411512615b6SEric Dumazet 		table->hash2[i].count = 0;
3412512615b6SEric Dumazet 		spin_lock_init(&table->hash2[i].lock);
3413512615b6SEric Dumazet 	}
3414645ca708SEric Dumazet }
3415645ca708SEric Dumazet 
3416723b8e46STom Herbert u32 udp_flow_hashrnd(void)
3417723b8e46STom Herbert {
3418723b8e46STom Herbert 	static u32 hashrnd __read_mostly;
3419723b8e46STom Herbert 
3420723b8e46STom Herbert 	net_get_random_once(&hashrnd, sizeof(hashrnd));
3421723b8e46STom Herbert 
3422723b8e46STom Herbert 	return hashrnd;
3423723b8e46STom Herbert }
3424723b8e46STom Herbert EXPORT_SYMBOL(udp_flow_hashrnd);
3425723b8e46STom Herbert 
34269804985bSKuniyuki Iwashima static void __net_init udp_sysctl_init(struct net *net)
34271e802951STonghao Zhang {
3428100fdd1fSEric Dumazet 	net->ipv4.sysctl_udp_rmem_min = PAGE_SIZE;
3429100fdd1fSEric Dumazet 	net->ipv4.sysctl_udp_wmem_min = PAGE_SIZE;
34301e802951STonghao Zhang 
34311e802951STonghao Zhang #ifdef CONFIG_NET_L3_MASTER_DEV
34321e802951STonghao Zhang 	net->ipv4.sysctl_udp_l3mdev_accept = 0;
34331e802951STonghao Zhang #endif
34349804985bSKuniyuki Iwashima }
34359804985bSKuniyuki Iwashima 
34369804985bSKuniyuki Iwashima static struct udp_table __net_init *udp_pernet_table_alloc(unsigned int hash_entries)
34379804985bSKuniyuki Iwashima {
34389804985bSKuniyuki Iwashima 	struct udp_table *udptable;
34399804985bSKuniyuki Iwashima 	int i;
34409804985bSKuniyuki Iwashima 
34419804985bSKuniyuki Iwashima 	udptable = kmalloc(sizeof(*udptable), GFP_KERNEL);
34429804985bSKuniyuki Iwashima 	if (!udptable)
34439804985bSKuniyuki Iwashima 		goto out;
34449804985bSKuniyuki Iwashima 
34459804985bSKuniyuki Iwashima 	udptable->hash = vmalloc_huge(hash_entries * 2 * sizeof(struct udp_hslot),
34469804985bSKuniyuki Iwashima 				      GFP_KERNEL_ACCOUNT);
34479804985bSKuniyuki Iwashima 	if (!udptable->hash)
34489804985bSKuniyuki Iwashima 		goto free_table;
34499804985bSKuniyuki Iwashima 
34509804985bSKuniyuki Iwashima 	udptable->hash2 = udptable->hash + hash_entries;
34519804985bSKuniyuki Iwashima 	udptable->mask = hash_entries - 1;
34529804985bSKuniyuki Iwashima 	udptable->log = ilog2(hash_entries);
34539804985bSKuniyuki Iwashima 
34549804985bSKuniyuki Iwashima 	for (i = 0; i < hash_entries; i++) {
34559804985bSKuniyuki Iwashima 		INIT_HLIST_HEAD(&udptable->hash[i].head);
34569804985bSKuniyuki Iwashima 		udptable->hash[i].count = 0;
34579804985bSKuniyuki Iwashima 		spin_lock_init(&udptable->hash[i].lock);
34589804985bSKuniyuki Iwashima 
34599804985bSKuniyuki Iwashima 		INIT_HLIST_HEAD(&udptable->hash2[i].head);
34609804985bSKuniyuki Iwashima 		udptable->hash2[i].count = 0;
34619804985bSKuniyuki Iwashima 		spin_lock_init(&udptable->hash2[i].lock);
34629804985bSKuniyuki Iwashima 	}
34639804985bSKuniyuki Iwashima 
34649804985bSKuniyuki Iwashima 	return udptable;
34659804985bSKuniyuki Iwashima 
34669804985bSKuniyuki Iwashima free_table:
34679804985bSKuniyuki Iwashima 	kfree(udptable);
34689804985bSKuniyuki Iwashima out:
34699804985bSKuniyuki Iwashima 	return NULL;
34709804985bSKuniyuki Iwashima }
34719804985bSKuniyuki Iwashima 
34729804985bSKuniyuki Iwashima static void __net_exit udp_pernet_table_free(struct net *net)
34739804985bSKuniyuki Iwashima {
34749804985bSKuniyuki Iwashima 	struct udp_table *udptable = net->ipv4.udp_table;
34759804985bSKuniyuki Iwashima 
34769804985bSKuniyuki Iwashima 	if (udptable == &udp_table)
34779804985bSKuniyuki Iwashima 		return;
34789804985bSKuniyuki Iwashima 
34799804985bSKuniyuki Iwashima 	kvfree(udptable->hash);
34809804985bSKuniyuki Iwashima 	kfree(udptable);
34819804985bSKuniyuki Iwashima }
34829804985bSKuniyuki Iwashima 
34839804985bSKuniyuki Iwashima static void __net_init udp_set_table(struct net *net)
34849804985bSKuniyuki Iwashima {
34859804985bSKuniyuki Iwashima 	struct udp_table *udptable;
34869804985bSKuniyuki Iwashima 	unsigned int hash_entries;
34879804985bSKuniyuki Iwashima 	struct net *old_net;
34889804985bSKuniyuki Iwashima 
34899804985bSKuniyuki Iwashima 	if (net_eq(net, &init_net))
34909804985bSKuniyuki Iwashima 		goto fallback;
34919804985bSKuniyuki Iwashima 
34929804985bSKuniyuki Iwashima 	old_net = current->nsproxy->net_ns;
34939804985bSKuniyuki Iwashima 	hash_entries = READ_ONCE(old_net->ipv4.sysctl_udp_child_hash_entries);
34949804985bSKuniyuki Iwashima 	if (!hash_entries)
34959804985bSKuniyuki Iwashima 		goto fallback;
34969804985bSKuniyuki Iwashima 
34979804985bSKuniyuki Iwashima 	/* Set min to keep the bitmap on stack in udp_lib_get_port() */
34989804985bSKuniyuki Iwashima 	if (hash_entries < UDP_HTABLE_SIZE_MIN_PERNET)
34999804985bSKuniyuki Iwashima 		hash_entries = UDP_HTABLE_SIZE_MIN_PERNET;
35009804985bSKuniyuki Iwashima 	else
35019804985bSKuniyuki Iwashima 		hash_entries = roundup_pow_of_two(hash_entries);
35029804985bSKuniyuki Iwashima 
35039804985bSKuniyuki Iwashima 	udptable = udp_pernet_table_alloc(hash_entries);
35049804985bSKuniyuki Iwashima 	if (udptable) {
35059804985bSKuniyuki Iwashima 		net->ipv4.udp_table = udptable;
35069804985bSKuniyuki Iwashima 	} else {
35079804985bSKuniyuki Iwashima 		pr_warn("Failed to allocate UDP hash table (entries: %u) "
35089804985bSKuniyuki Iwashima 			"for a netns, fallback to the global one\n",
35099804985bSKuniyuki Iwashima 			hash_entries);
35109804985bSKuniyuki Iwashima fallback:
35119804985bSKuniyuki Iwashima 		net->ipv4.udp_table = &udp_table;
35129804985bSKuniyuki Iwashima 	}
35139804985bSKuniyuki Iwashima }
35149804985bSKuniyuki Iwashima 
35159804985bSKuniyuki Iwashima static int __net_init udp_pernet_init(struct net *net)
35169804985bSKuniyuki Iwashima {
35179804985bSKuniyuki Iwashima 	udp_sysctl_init(net);
35189804985bSKuniyuki Iwashima 	udp_set_table(net);
35191e802951STonghao Zhang 
35201e802951STonghao Zhang 	return 0;
35211e802951STonghao Zhang }
35221e802951STonghao Zhang 
35239804985bSKuniyuki Iwashima static void __net_exit udp_pernet_exit(struct net *net)
35249804985bSKuniyuki Iwashima {
35259804985bSKuniyuki Iwashima 	udp_pernet_table_free(net);
35269804985bSKuniyuki Iwashima }
35279804985bSKuniyuki Iwashima 
35281e802951STonghao Zhang static struct pernet_operations __net_initdata udp_sysctl_ops = {
35299804985bSKuniyuki Iwashima 	.init	= udp_pernet_init,
35309804985bSKuniyuki Iwashima 	.exit	= udp_pernet_exit,
35311e802951STonghao Zhang };
35321e802951STonghao Zhang 
35335788b3a0SYonghong Song #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
35345788b3a0SYonghong Song DEFINE_BPF_ITER_FUNC(udp, struct bpf_iter_meta *meta,
35355788b3a0SYonghong Song 		     struct udp_sock *udp_sk, uid_t uid, int bucket)
35365788b3a0SYonghong Song 
3537c96dac8dSAditi Ghag static int bpf_iter_udp_realloc_batch(struct bpf_udp_iter_state *iter,
3538c96dac8dSAditi Ghag 				      unsigned int new_batch_sz)
35395788b3a0SYonghong Song {
3540c96dac8dSAditi Ghag 	struct sock **new_batch;
35415788b3a0SYonghong Song 
3542c96dac8dSAditi Ghag 	new_batch = kvmalloc_array(new_batch_sz, sizeof(*new_batch),
3543c96dac8dSAditi Ghag 				   GFP_USER | __GFP_NOWARN);
3544c96dac8dSAditi Ghag 	if (!new_batch)
35455788b3a0SYonghong Song 		return -ENOMEM;
35465788b3a0SYonghong Song 
3547c96dac8dSAditi Ghag 	bpf_iter_udp_put_batch(iter);
3548c96dac8dSAditi Ghag 	kvfree(iter->batch);
3549c96dac8dSAditi Ghag 	iter->batch = new_batch;
3550c96dac8dSAditi Ghag 	iter->max_sk = new_batch_sz;
3551c96dac8dSAditi Ghag 
3552c96dac8dSAditi Ghag 	return 0;
3553c96dac8dSAditi Ghag }
3554c96dac8dSAditi Ghag 
3555c96dac8dSAditi Ghag #define INIT_BATCH_SZ 16
3556c96dac8dSAditi Ghag 
35575788b3a0SYonghong Song static int bpf_iter_init_udp(void *priv_data, struct bpf_iter_aux_info *aux)
35585788b3a0SYonghong Song {
3559c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = priv_data;
3560c96dac8dSAditi Ghag 	int ret;
3561c96dac8dSAditi Ghag 
3562f9c79272SYonghong Song 	ret = bpf_iter_init_seq_net(priv_data, aux);
35635788b3a0SYonghong Song 	if (ret)
3564c96dac8dSAditi Ghag 		return ret;
3565c96dac8dSAditi Ghag 
3566c96dac8dSAditi Ghag 	ret = bpf_iter_udp_realloc_batch(iter, INIT_BATCH_SZ);
3567c96dac8dSAditi Ghag 	if (ret)
3568c96dac8dSAditi Ghag 		bpf_iter_fini_seq_net(priv_data);
3569c96dac8dSAditi Ghag 
35705788b3a0SYonghong Song 	return ret;
35715788b3a0SYonghong Song }
35725788b3a0SYonghong Song 
35735788b3a0SYonghong Song static void bpf_iter_fini_udp(void *priv_data)
35745788b3a0SYonghong Song {
3575c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = priv_data;
35765788b3a0SYonghong Song 
35775788b3a0SYonghong Song 	bpf_iter_fini_seq_net(priv_data);
3578c96dac8dSAditi Ghag 	kvfree(iter->batch);
35795788b3a0SYonghong Song }
35805788b3a0SYonghong Song 
358114fc6bd6SYonghong Song static const struct bpf_iter_seq_info udp_seq_info = {
35825788b3a0SYonghong Song 	.seq_ops		= &bpf_iter_udp_seq_ops,
35835788b3a0SYonghong Song 	.init_seq_private	= bpf_iter_init_udp,
35845788b3a0SYonghong Song 	.fini_seq_private	= bpf_iter_fini_udp,
3585c96dac8dSAditi Ghag 	.seq_priv_size		= sizeof(struct bpf_udp_iter_state),
358614fc6bd6SYonghong Song };
358714fc6bd6SYonghong Song 
358814fc6bd6SYonghong Song static struct bpf_iter_reg udp_reg_info = {
358914fc6bd6SYonghong Song 	.target			= "udp",
35905788b3a0SYonghong Song 	.ctx_arg_info_size	= 1,
35915788b3a0SYonghong Song 	.ctx_arg_info		= {
35925788b3a0SYonghong Song 		{ offsetof(struct bpf_iter__udp, udp_sk),
35934ddbcb88SAditi Ghag 		  PTR_TO_BTF_ID_OR_NULL | PTR_TRUSTED },
35945788b3a0SYonghong Song 	},
359514fc6bd6SYonghong Song 	.seq_info		= &udp_seq_info,
35965788b3a0SYonghong Song };
35975788b3a0SYonghong Song 
35985788b3a0SYonghong Song static void __init bpf_iter_register(void)
35995788b3a0SYonghong Song {
3600951cf368SYonghong Song 	udp_reg_info.ctx_arg_info[0].btf_id = btf_sock_ids[BTF_SOCK_TYPE_UDP];
36015788b3a0SYonghong Song 	if (bpf_iter_reg_target(&udp_reg_info))
36025788b3a0SYonghong Song 		pr_warn("Warning: could not register bpf iterator udp\n");
36035788b3a0SYonghong Song }
36045788b3a0SYonghong Song #endif
36055788b3a0SYonghong Song 
360695766fffSHideo Aoki void __init udp_init(void)
360795766fffSHideo Aoki {
3608f03d78dbSEric Dumazet 	unsigned long limit;
36094b272750SEric Dumazet 	unsigned int i;
361095766fffSHideo Aoki 
3611f86dcc5aSEric Dumazet 	udp_table_init(&udp_table, "UDP");
3612f03d78dbSEric Dumazet 	limit = nr_free_buffer_pages() / 8;
361395766fffSHideo Aoki 	limit = max(limit, 128UL);
361495766fffSHideo Aoki 	sysctl_udp_mem[0] = limit / 4 * 3;
361595766fffSHideo Aoki 	sysctl_udp_mem[1] = limit;
361695766fffSHideo Aoki 	sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
361795766fffSHideo Aoki 
36184b272750SEric Dumazet 	/* 16 spinlocks per cpu */
36194b272750SEric Dumazet 	udp_busylocks_log = ilog2(nr_cpu_ids) + 4;
36204b272750SEric Dumazet 	udp_busylocks = kmalloc(sizeof(spinlock_t) << udp_busylocks_log,
36214b272750SEric Dumazet 				GFP_KERNEL);
36224b272750SEric Dumazet 	if (!udp_busylocks)
36234b272750SEric Dumazet 		panic("UDP: failed to alloc udp_busylocks\n");
36244b272750SEric Dumazet 	for (i = 0; i < (1U << udp_busylocks_log); i++)
36254b272750SEric Dumazet 		spin_lock_init(udp_busylocks + i);
36261e802951STonghao Zhang 
36271e802951STonghao Zhang 	if (register_pernet_subsys(&udp_sysctl_ops))
36281e802951STonghao Zhang 		panic("UDP: failed to init sysctl parameters.\n");
36295788b3a0SYonghong Song 
36305788b3a0SYonghong Song #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
36315788b3a0SYonghong Song 	bpf_iter_register();
36325788b3a0SYonghong Song #endif
363395766fffSHideo Aoki }
3634