xref: /linux/net/ipv4/udp.c (revision fd9c31f834416e3060061dbcb45ababaa25cdfe2)
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>
1061da177e4SLinus Torvalds #include <net/xfrm.h>
107296f7ea7SSatoru Moriya #include <trace/events/udp.h>
108447167bfSEric Dumazet #include <linux/static_key.h>
109951cf368SYonghong Song #include <linux/btf_ids.h>
11022911fc5SEric Dumazet #include <trace/events/skb.h>
111076bb0c8SEliezer Tamir #include <net/busy_poll.h>
112ba4e58ecSGerrit Renker #include "udp_impl.h"
113e32ea7e7SCraig Gallek #include <net/sock_reuseport.h>
114217375a0SEric Dumazet #include <net/addrconf.h>
11560fb9567SPaolo Abeni #include <net/udp_tunnel.h>
1160146dca7SSabrina Dubroca #if IS_ENABLED(CONFIG_IPV6)
1170146dca7SSabrina Dubroca #include <net/ipv6_stubs.h>
1180146dca7SSabrina Dubroca #endif
1191da177e4SLinus Torvalds 
120f86dcc5aSEric Dumazet struct udp_table udp_table __read_mostly;
121645ca708SEric Dumazet EXPORT_SYMBOL(udp_table);
1221da177e4SLinus Torvalds 
1238d987e5cSEric Dumazet long sysctl_udp_mem[3] __read_mostly;
12495766fffSHideo Aoki EXPORT_SYMBOL(sysctl_udp_mem);
125c482c568SEric Dumazet 
12691b6d325SEric Dumazet atomic_long_t udp_memory_allocated ____cacheline_aligned_in_smp;
12795766fffSHideo Aoki EXPORT_SYMBOL(udp_memory_allocated);
1280defbb0aSEric Dumazet DEFINE_PER_CPU(int, udp_memory_per_cpu_fw_alloc);
1290defbb0aSEric Dumazet EXPORT_PER_CPU_SYMBOL_GPL(udp_memory_per_cpu_fw_alloc);
13095766fffSHideo Aoki 
131f86dcc5aSEric Dumazet #define MAX_UDP_PORTS 65536
1329804985bSKuniyuki Iwashima #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN_PERNET)
13398322f22SEric Dumazet 
13467fb4330SKuniyuki Iwashima static struct udp_table *udp_get_table_prot(struct sock *sk)
13567fb4330SKuniyuki Iwashima {
13667fb4330SKuniyuki Iwashima 	return sk->sk_prot->h.udp_table ? : sock_net(sk)->ipv4.udp_table;
13767fb4330SKuniyuki Iwashima }
13867fb4330SKuniyuki Iwashima 
139f24d43c0SEric Dumazet static int udp_lib_lport_inuse(struct net *net, __u16 num,
140645ca708SEric Dumazet 			       const struct udp_hslot *hslot,
14198322f22SEric Dumazet 			       unsigned long *bitmap,
142fe38d2a1SJosef Bacik 			       struct sock *sk, unsigned int log)
14325030a7fSGerrit Renker {
144f24d43c0SEric Dumazet 	struct sock *sk2;
145ba418fa3STom Herbert 	kuid_t uid = sock_i_uid(sk);
14625030a7fSGerrit Renker 
147ca065d0cSEric Dumazet 	sk_for_each(sk2, &hslot->head) {
148f24d43c0SEric Dumazet 		if (net_eq(sock_net(sk2), net) &&
149f24d43c0SEric Dumazet 		    sk2 != sk &&
150d4cada4aSEric Dumazet 		    (bitmap || udp_sk(sk2)->udp_port_hash == num) &&
151f24d43c0SEric Dumazet 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
1529d4fb27dSJoe Perches 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
1539d4fb27dSJoe Perches 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
154fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, true)) {
155df560056SEric Garver 			if (sk2->sk_reuseport && sk->sk_reuseport &&
156df560056SEric Garver 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
157df560056SEric Garver 			    uid_eq(uid, sock_i_uid(sk2))) {
158df560056SEric Garver 				if (!bitmap)
159df560056SEric Garver 					return 0;
160df560056SEric Garver 			} else {
1614243cdc2SJoe Perches 				if (!bitmap)
162fc038410SDavid S. Miller 					return 1;
163df560056SEric Garver 				__set_bit(udp_sk(sk2)->udp_port_hash >> log,
164df560056SEric Garver 					  bitmap);
165df560056SEric Garver 			}
1664243cdc2SJoe Perches 		}
16798322f22SEric Dumazet 	}
16825030a7fSGerrit Renker 	return 0;
16925030a7fSGerrit Renker }
17025030a7fSGerrit Renker 
17130fff923SEric Dumazet /*
17230fff923SEric Dumazet  * Note: we still hold spinlock of primary hash chain, so no other writer
17330fff923SEric Dumazet  * can insert/delete a socket with local_port == num
17430fff923SEric Dumazet  */
17530fff923SEric Dumazet static int udp_lib_lport_inuse2(struct net *net, __u16 num,
17630fff923SEric Dumazet 				struct udp_hslot *hslot2,
177fe38d2a1SJosef Bacik 				struct sock *sk)
17830fff923SEric Dumazet {
17930fff923SEric Dumazet 	struct sock *sk2;
180ba418fa3STom Herbert 	kuid_t uid = sock_i_uid(sk);
18130fff923SEric Dumazet 	int res = 0;
18230fff923SEric Dumazet 
18330fff923SEric Dumazet 	spin_lock(&hslot2->lock);
184ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry(sk2, &hslot2->head) {
18530fff923SEric Dumazet 		if (net_eq(sock_net(sk2), net) &&
18630fff923SEric Dumazet 		    sk2 != sk &&
18730fff923SEric Dumazet 		    (udp_sk(sk2)->udp_port_hash == num) &&
18830fff923SEric Dumazet 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
1899d4fb27dSJoe Perches 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
1909d4fb27dSJoe Perches 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
191fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, true)) {
192df560056SEric Garver 			if (sk2->sk_reuseport && sk->sk_reuseport &&
193df560056SEric Garver 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
194df560056SEric Garver 			    uid_eq(uid, sock_i_uid(sk2))) {
195df560056SEric Garver 				res = 0;
196df560056SEric Garver 			} else {
19730fff923SEric Dumazet 				res = 1;
198df560056SEric Garver 			}
19930fff923SEric Dumazet 			break;
20030fff923SEric Dumazet 		}
2014243cdc2SJoe Perches 	}
20230fff923SEric Dumazet 	spin_unlock(&hslot2->lock);
20330fff923SEric Dumazet 	return res;
20430fff923SEric Dumazet }
20530fff923SEric Dumazet 
206fe38d2a1SJosef Bacik static int udp_reuseport_add_sock(struct sock *sk, struct udp_hslot *hslot)
207e32ea7e7SCraig Gallek {
208e32ea7e7SCraig Gallek 	struct net *net = sock_net(sk);
209e32ea7e7SCraig Gallek 	kuid_t uid = sock_i_uid(sk);
210e32ea7e7SCraig Gallek 	struct sock *sk2;
211e32ea7e7SCraig Gallek 
212ca065d0cSEric Dumazet 	sk_for_each(sk2, &hslot->head) {
213e32ea7e7SCraig Gallek 		if (net_eq(sock_net(sk2), net) &&
214e32ea7e7SCraig Gallek 		    sk2 != sk &&
215e32ea7e7SCraig Gallek 		    sk2->sk_family == sk->sk_family &&
216e32ea7e7SCraig Gallek 		    ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
217e32ea7e7SCraig Gallek 		    (udp_sk(sk2)->udp_port_hash == udp_sk(sk)->udp_port_hash) &&
218e32ea7e7SCraig Gallek 		    (sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
219e32ea7e7SCraig Gallek 		    sk2->sk_reuseport && uid_eq(uid, sock_i_uid(sk2)) &&
220fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, false)) {
2212dbb9b9eSMartin KaFai Lau 			return reuseport_add_sock(sk, sk2,
2222dbb9b9eSMartin KaFai Lau 						  inet_rcv_saddr_any(sk));
223e32ea7e7SCraig Gallek 		}
224e32ea7e7SCraig Gallek 	}
225e32ea7e7SCraig Gallek 
2262dbb9b9eSMartin KaFai Lau 	return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
227e32ea7e7SCraig Gallek }
228e32ea7e7SCraig Gallek 
22925030a7fSGerrit Renker /**
2306ba5a3c5SPavel Emelyanov  *  udp_lib_get_port  -  UDP/-Lite port lookup for IPv4 and IPv6
23125030a7fSGerrit Renker  *
23225030a7fSGerrit Renker  *  @sk:          socket struct in question
23325030a7fSGerrit Renker  *  @snum:        port number to look up
23425985edcSLucas De Marchi  *  @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
23530fff923SEric Dumazet  *                   with NULL address
23625030a7fSGerrit Renker  */
2376ba5a3c5SPavel Emelyanov int udp_lib_get_port(struct sock *sk, unsigned short snum,
23830fff923SEric Dumazet 		     unsigned int hash2_nulladdr)
2391da177e4SLinus Torvalds {
24067fb4330SKuniyuki Iwashima 	struct udp_table *udptable = udp_get_table_prot(sk);
241919dfa0bSKuniyuki Iwashima 	struct udp_hslot *hslot, *hslot2;
2423b1e0a65SYOSHIFUJI Hideaki 	struct net *net = sock_net(sk);
2437a7160edSKuniyuki Iwashima 	int error = -EADDRINUSE;
2441da177e4SLinus Torvalds 
24532c1da70SStephen Hemminger 	if (!snum) {
246919dfa0bSKuniyuki Iwashima 		DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
247919dfa0bSKuniyuki Iwashima 		unsigned short first, last;
2489088c560SEric Dumazet 		int low, high, remaining;
24995c96174SEric Dumazet 		unsigned int rand;
2501da177e4SLinus Torvalds 
25191d0b78cSJakub Sitnicki 		inet_sk_get_local_port_range(sk, &low, &high);
252a25de534SAnton Arapov 		remaining = (high - low) + 1;
253227b60f5SStephen Hemminger 
254a251c17aSJason A. Donenfeld 		rand = get_random_u32();
2558fc54f68SDaniel Borkmann 		first = reciprocal_scale(rand, remaining) + low;
25698322f22SEric Dumazet 		/*
25798322f22SEric Dumazet 		 * force rand to be an odd multiple of UDP_HTABLE_SIZE
25898322f22SEric Dumazet 		 */
259f86dcc5aSEric Dumazet 		rand = (rand | 1) * (udptable->mask + 1);
2605781b235SEric Dumazet 		last = first + udptable->mask + 1;
2615781b235SEric Dumazet 		do {
262f86dcc5aSEric Dumazet 			hslot = udp_hashslot(udptable, net, first);
26398322f22SEric Dumazet 			bitmap_zero(bitmap, PORTS_PER_CHAIN);
264645ca708SEric Dumazet 			spin_lock_bh(&hslot->lock);
26598322f22SEric Dumazet 			udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
266fe38d2a1SJosef Bacik 					    udptable->log);
26798322f22SEric Dumazet 
26898322f22SEric Dumazet 			snum = first;
26998322f22SEric Dumazet 			/*
27098322f22SEric Dumazet 			 * Iterate on all possible values of snum for this hash.
27198322f22SEric Dumazet 			 * Using steps of an odd multiple of UDP_HTABLE_SIZE
27298322f22SEric Dumazet 			 * give us randomization and full range coverage.
27398322f22SEric Dumazet 			 */
2749088c560SEric Dumazet 			do {
27598322f22SEric Dumazet 				if (low <= snum && snum <= high &&
276e3826f1eSAmerigo Wang 				    !test_bit(snum >> udptable->log, bitmap) &&
277122ff243SWANG Cong 				    !inet_is_local_reserved_port(net, snum))
27898322f22SEric Dumazet 					goto found;
27998322f22SEric Dumazet 				snum += rand;
28098322f22SEric Dumazet 			} while (snum != first);
28198322f22SEric Dumazet 			spin_unlock_bh(&hslot->lock);
282df560056SEric Garver 			cond_resched();
2835781b235SEric Dumazet 		} while (++first != last);
28498322f22SEric Dumazet 		goto fail;
285645ca708SEric Dumazet 	} else {
286f86dcc5aSEric Dumazet 		hslot = udp_hashslot(udptable, net, snum);
287645ca708SEric Dumazet 		spin_lock_bh(&hslot->lock);
28830fff923SEric Dumazet 		if (hslot->count > 10) {
28930fff923SEric Dumazet 			int exist;
29030fff923SEric Dumazet 			unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
29130fff923SEric Dumazet 
29230fff923SEric Dumazet 			slot2          &= udptable->mask;
29330fff923SEric Dumazet 			hash2_nulladdr &= udptable->mask;
29430fff923SEric Dumazet 
29530fff923SEric Dumazet 			hslot2 = udp_hashslot2(udptable, slot2);
29630fff923SEric Dumazet 			if (hslot->count < hslot2->count)
29730fff923SEric Dumazet 				goto scan_primary_hash;
29830fff923SEric Dumazet 
299fe38d2a1SJosef Bacik 			exist = udp_lib_lport_inuse2(net, snum, hslot2, sk);
30030fff923SEric Dumazet 			if (!exist && (hash2_nulladdr != slot2)) {
30130fff923SEric Dumazet 				hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
30230fff923SEric Dumazet 				exist = udp_lib_lport_inuse2(net, snum, hslot2,
303fe38d2a1SJosef Bacik 							     sk);
30430fff923SEric Dumazet 			}
30530fff923SEric Dumazet 			if (exist)
30630fff923SEric Dumazet 				goto fail_unlock;
30730fff923SEric Dumazet 			else
30830fff923SEric Dumazet 				goto found;
30930fff923SEric Dumazet 		}
31030fff923SEric Dumazet scan_primary_hash:
311fe38d2a1SJosef Bacik 		if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, 0))
312645ca708SEric Dumazet 			goto fail_unlock;
313645ca708SEric Dumazet 	}
31498322f22SEric Dumazet found:
315c720c7e8SEric Dumazet 	inet_sk(sk)->inet_num = snum;
316d4cada4aSEric Dumazet 	udp_sk(sk)->udp_port_hash = snum;
317d4cada4aSEric Dumazet 	udp_sk(sk)->udp_portaddr_hash ^= snum;
3181da177e4SLinus Torvalds 	if (sk_unhashed(sk)) {
319e32ea7e7SCraig Gallek 		if (sk->sk_reuseport &&
320fe38d2a1SJosef Bacik 		    udp_reuseport_add_sock(sk, hslot)) {
321e32ea7e7SCraig Gallek 			inet_sk(sk)->inet_num = 0;
322e32ea7e7SCraig Gallek 			udp_sk(sk)->udp_port_hash = 0;
323e32ea7e7SCraig Gallek 			udp_sk(sk)->udp_portaddr_hash ^= snum;
324e32ea7e7SCraig Gallek 			goto fail_unlock;
325e32ea7e7SCraig Gallek 		}
326e32ea7e7SCraig Gallek 
327ca065d0cSEric Dumazet 		sk_add_node_rcu(sk, &hslot->head);
328fdcc8aa9SEric Dumazet 		hslot->count++;
329c29a0bc4SPavel Emelyanov 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
330512615b6SEric Dumazet 
331512615b6SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
332512615b6SEric Dumazet 		spin_lock(&hslot2->lock);
333d894ba18SCraig Gallek 		if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
334d894ba18SCraig Gallek 		    sk->sk_family == AF_INET6)
3351602f49bSDavid S. Miller 			hlist_add_tail_rcu(&udp_sk(sk)->udp_portaddr_node,
336d894ba18SCraig Gallek 					   &hslot2->head);
337d894ba18SCraig Gallek 		else
338ca065d0cSEric Dumazet 			hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
339512615b6SEric Dumazet 					   &hslot2->head);
340512615b6SEric Dumazet 		hslot2->count++;
341512615b6SEric Dumazet 		spin_unlock(&hslot2->lock);
3421da177e4SLinus Torvalds 	}
343ca065d0cSEric Dumazet 	sock_set_flag(sk, SOCK_RCU_FREE);
34425030a7fSGerrit Renker 	error = 0;
345645ca708SEric Dumazet fail_unlock:
346645ca708SEric Dumazet 	spin_unlock_bh(&hslot->lock);
3471da177e4SLinus Torvalds fail:
34825030a7fSGerrit Renker 	return error;
3491da177e4SLinus Torvalds }
350c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_get_port);
3511da177e4SLinus Torvalds 
3526ba5a3c5SPavel Emelyanov int udp_v4_get_port(struct sock *sk, unsigned short snum)
353db8dac20SDavid S. Miller {
35430fff923SEric Dumazet 	unsigned int hash2_nulladdr =
355f0b1e64cSMartin KaFai Lau 		ipv4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
35630fff923SEric Dumazet 	unsigned int hash2_partial =
357f0b1e64cSMartin KaFai Lau 		ipv4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
35830fff923SEric Dumazet 
359d4cada4aSEric Dumazet 	/* precompute partial secondary hash */
36030fff923SEric Dumazet 	udp_sk(sk)->udp_portaddr_hash = hash2_partial;
361fe38d2a1SJosef Bacik 	return udp_lib_get_port(sk, snum, hash2_nulladdr);
362db8dac20SDavid S. Miller }
363db8dac20SDavid S. Miller 
364d1e37288SSu, Xuemin static int compute_score(struct sock *sk, struct net *net,
365d1e37288SSu, Xuemin 			 __be32 saddr, __be16 sport,
366fb74c277SDavid Ahern 			 __be32 daddr, unsigned short hnum,
36773545373STim Beale 			 int dif, int sdif)
368645ca708SEric Dumazet {
36960c04aecSJoe Perches 	int score;
37060c04aecSJoe Perches 	struct inet_sock *inet;
3716da5b0f0SMike Manning 	bool dev_match;
372645ca708SEric Dumazet 
37360c04aecSJoe Perches 	if (!net_eq(sock_net(sk), net) ||
37460c04aecSJoe Perches 	    udp_sk(sk)->udp_port_hash != hnum ||
37560c04aecSJoe Perches 	    ipv6_only_sock(sk))
37660c04aecSJoe Perches 		return -1;
377645ca708SEric Dumazet 
3784cdeeee9SPeter Oskolkov 	if (sk->sk_rcv_saddr != daddr)
379645ca708SEric Dumazet 		return -1;
38060c04aecSJoe Perches 
3814cdeeee9SPeter Oskolkov 	score = (sk->sk_family == PF_INET) ? 2 : 1;
3824cdeeee9SPeter Oskolkov 
3834cdeeee9SPeter Oskolkov 	inet = inet_sk(sk);
384c720c7e8SEric Dumazet 	if (inet->inet_daddr) {
385c720c7e8SEric Dumazet 		if (inet->inet_daddr != saddr)
386645ca708SEric Dumazet 			return -1;
387ba418fa3STom Herbert 		score += 4;
388645ca708SEric Dumazet 	}
38960c04aecSJoe Perches 
390c720c7e8SEric Dumazet 	if (inet->inet_dport) {
391c720c7e8SEric Dumazet 		if (inet->inet_dport != sport)
392645ca708SEric Dumazet 			return -1;
393ba418fa3STom Herbert 		score += 4;
394645ca708SEric Dumazet 	}
39560c04aecSJoe Perches 
3966da5b0f0SMike Manning 	dev_match = udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if,
3976da5b0f0SMike Manning 					dif, sdif);
39869678bcdSPaolo Abeni 	if (!dev_match)
399645ca708SEric Dumazet 		return -1;
4008d6c414cSMike Manning 	if (sk->sk_bound_dev_if)
401ba418fa3STom Herbert 		score += 4;
402fb74c277SDavid Ahern 
4037170a977SEric Dumazet 	if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
40470da268bSEric Dumazet 		score++;
405645ca708SEric Dumazet 	return score;
406645ca708SEric Dumazet }
407645ca708SEric Dumazet 
4086eada011SEric Dumazet static u32 udp_ehashfn(const struct net *net, const __be32 laddr,
40965cd8033SHannes Frederic Sowa 		       const __u16 lport, const __be32 faddr,
41065cd8033SHannes Frederic Sowa 		       const __be16 fport)
41165cd8033SHannes Frederic Sowa {
4121bbdceefSHannes Frederic Sowa 	static u32 udp_ehash_secret __read_mostly;
4131bbdceefSHannes Frederic Sowa 
4141bbdceefSHannes Frederic Sowa 	net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret));
4151bbdceefSHannes Frederic Sowa 
41665cd8033SHannes Frederic Sowa 	return __inet_ehashfn(laddr, lport, faddr, fport,
4171bbdceefSHannes Frederic Sowa 			      udp_ehash_secret + net_hash_mix(net));
41865cd8033SHannes Frederic Sowa }
41965cd8033SHannes Frederic Sowa 
420a57066b1SDavid S. Miller static struct sock *lookup_reuseport(struct net *net, struct sock *sk,
4217629c73aSJakub Sitnicki 				     struct sk_buff *skb,
4227629c73aSJakub Sitnicki 				     __be32 saddr, __be16 sport,
4237629c73aSJakub Sitnicki 				     __be32 daddr, unsigned short hnum)
4247629c73aSJakub Sitnicki {
4257629c73aSJakub Sitnicki 	struct sock *reuse_sk = NULL;
4267629c73aSJakub Sitnicki 	u32 hash;
4277629c73aSJakub Sitnicki 
4287629c73aSJakub Sitnicki 	if (sk->sk_reuseport && sk->sk_state != TCP_ESTABLISHED) {
4297629c73aSJakub Sitnicki 		hash = udp_ehashfn(net, daddr, hnum, saddr, sport);
4307629c73aSJakub Sitnicki 		reuse_sk = reuseport_select_sock(sk, hash, skb,
4317629c73aSJakub Sitnicki 						 sizeof(struct udphdr));
4327629c73aSJakub Sitnicki 	}
4337629c73aSJakub Sitnicki 	return reuse_sk;
4347629c73aSJakub Sitnicki }
4357629c73aSJakub Sitnicki 
436d1e37288SSu, Xuemin /* called with rcu_read_lock() */
4375051ebd2SEric Dumazet static struct sock *udp4_lib_lookup2(struct net *net,
4385051ebd2SEric Dumazet 				     __be32 saddr, __be16 sport,
439fb74c277SDavid Ahern 				     __be32 daddr, unsigned int hnum,
44073545373STim Beale 				     int dif, int sdif,
441d1e37288SSu, Xuemin 				     struct udp_hslot *hslot2,
4421134158bSCraig Gallek 				     struct sk_buff *skb)
4435051ebd2SEric Dumazet {
4445051ebd2SEric Dumazet 	struct sock *sk, *result;
445e94a62f5SPaolo Abeni 	int score, badness;
4465051ebd2SEric Dumazet 
4475051ebd2SEric Dumazet 	result = NULL;
448ba418fa3STom Herbert 	badness = 0;
449ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
450d1e37288SSu, Xuemin 		score = compute_score(sk, net, saddr, sport,
45173545373STim Beale 				      daddr, hnum, dif, sdif);
4525051ebd2SEric Dumazet 		if (score > badness) {
4537629c73aSJakub Sitnicki 			result = lookup_reuseport(net, sk, skb,
4547629c73aSJakub Sitnicki 						  saddr, sport, daddr, hnum);
455a57066b1SDavid S. Miller 			/* Fall back to scoring if group has connections */
45669421bf9SKuniyuki Iwashima 			if (result && !reuseport_has_conns(sk))
457ca065d0cSEric Dumazet 				return result;
4587629c73aSJakub Sitnicki 
459a57066b1SDavid S. Miller 			result = result ? : sk;
460ca065d0cSEric Dumazet 			badness = score;
4615051ebd2SEric Dumazet 		}
4625051ebd2SEric Dumazet 	}
4635051ebd2SEric Dumazet 	return result;
4645051ebd2SEric Dumazet }
4655051ebd2SEric Dumazet 
466a57066b1SDavid S. Miller static struct sock *udp4_lookup_run_bpf(struct net *net,
46772f7e944SJakub Sitnicki 					struct udp_table *udptable,
46872f7e944SJakub Sitnicki 					struct sk_buff *skb,
46972f7e944SJakub Sitnicki 					__be32 saddr, __be16 sport,
470f8931565SMark Pashmfouroush 					__be32 daddr, u16 hnum, const int dif)
47172f7e944SJakub Sitnicki {
47272f7e944SJakub Sitnicki 	struct sock *sk, *reuse_sk;
47372f7e944SJakub Sitnicki 	bool no_reuseport;
47472f7e944SJakub Sitnicki 
475ba6aac15SKuniyuki Iwashima 	if (udptable != net->ipv4.udp_table)
47672f7e944SJakub Sitnicki 		return NULL; /* only UDP is supported */
47772f7e944SJakub Sitnicki 
478f8931565SMark Pashmfouroush 	no_reuseport = bpf_sk_lookup_run_v4(net, IPPROTO_UDP, saddr, sport,
479f8931565SMark Pashmfouroush 					    daddr, hnum, dif, &sk);
48072f7e944SJakub Sitnicki 	if (no_reuseport || IS_ERR_OR_NULL(sk))
48172f7e944SJakub Sitnicki 		return sk;
48272f7e944SJakub Sitnicki 
48372f7e944SJakub Sitnicki 	reuse_sk = lookup_reuseport(net, sk, skb, saddr, sport, daddr, hnum);
484c64c9c28SJakub Sitnicki 	if (reuse_sk)
48572f7e944SJakub Sitnicki 		sk = reuse_sk;
48672f7e944SJakub Sitnicki 	return sk;
48772f7e944SJakub Sitnicki }
48872f7e944SJakub Sitnicki 
489db8dac20SDavid S. Miller /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
490db8dac20SDavid S. Miller  * harder than this. -DaveM
491db8dac20SDavid S. Miller  */
492fce82338SPavel Emelyanov struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
493fb74c277SDavid Ahern 		__be16 sport, __be32 daddr, __be16 dport, int dif,
494fb74c277SDavid Ahern 		int sdif, struct udp_table *udptable, struct sk_buff *skb)
495db8dac20SDavid S. Miller {
496db8dac20SDavid S. Miller 	unsigned short hnum = ntohs(dport);
4974cdeeee9SPeter Oskolkov 	unsigned int hash2, slot2;
4984cdeeee9SPeter Oskolkov 	struct udp_hslot *hslot2;
49972f7e944SJakub Sitnicki 	struct sock *result, *sk;
500db8dac20SDavid S. Miller 
501f0b1e64cSMartin KaFai Lau 	hash2 = ipv4_portaddr_hash(net, daddr, hnum);
5025051ebd2SEric Dumazet 	slot2 = hash2 & udptable->mask;
5035051ebd2SEric Dumazet 	hslot2 = &udptable->hash2[slot2];
5045051ebd2SEric Dumazet 
50572f7e944SJakub Sitnicki 	/* Lookup connected or non-wildcard socket */
5065051ebd2SEric Dumazet 	result = udp4_lib_lookup2(net, saddr, sport,
507fb74c277SDavid Ahern 				  daddr, hnum, dif, sdif,
50873545373STim Beale 				  hslot2, skb);
50972f7e944SJakub Sitnicki 	if (!IS_ERR_OR_NULL(result) && result->sk_state == TCP_ESTABLISHED)
51072f7e944SJakub Sitnicki 		goto done;
51172f7e944SJakub Sitnicki 
51272f7e944SJakub Sitnicki 	/* Lookup redirect from BPF */
51372f7e944SJakub Sitnicki 	if (static_branch_unlikely(&bpf_sk_lookup_enabled)) {
51472f7e944SJakub Sitnicki 		sk = udp4_lookup_run_bpf(net, udptable, skb,
515f8931565SMark Pashmfouroush 					 saddr, sport, daddr, hnum, dif);
51672f7e944SJakub Sitnicki 		if (sk) {
51772f7e944SJakub Sitnicki 			result = sk;
51872f7e944SJakub Sitnicki 			goto done;
51972f7e944SJakub Sitnicki 		}
52072f7e944SJakub Sitnicki 	}
52172f7e944SJakub Sitnicki 
52272f7e944SJakub Sitnicki 	/* Got non-wildcard socket or error on first lookup */
52372f7e944SJakub Sitnicki 	if (result)
52472f7e944SJakub Sitnicki 		goto done;
52572f7e944SJakub Sitnicki 
52672f7e944SJakub Sitnicki 	/* Lookup wildcard sockets */
527f0b1e64cSMartin KaFai Lau 	hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
5285051ebd2SEric Dumazet 	slot2 = hash2 & udptable->mask;
5295051ebd2SEric Dumazet 	hslot2 = &udptable->hash2[slot2];
5305051ebd2SEric Dumazet 
5311223c67cSJorge Boncompte [DTI2] 	result = udp4_lib_lookup2(net, saddr, sport,
5324cdeeee9SPeter Oskolkov 				  htonl(INADDR_ANY), hnum, dif, sdif,
53373545373STim Beale 				  hslot2, skb);
53472f7e944SJakub Sitnicki done:
53588e235b8SEnrico Weigelt 	if (IS_ERR(result))
5368217ca65SMartin KaFai Lau 		return NULL;
5375051ebd2SEric Dumazet 	return result;
5385051ebd2SEric Dumazet }
539fce82338SPavel Emelyanov EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
540db8dac20SDavid S. Miller 
541607c4aafSKOVACS Krisztian static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
542607c4aafSKOVACS Krisztian 						 __be16 sport, __be16 dport,
543645ca708SEric Dumazet 						 struct udp_table *udptable)
544607c4aafSKOVACS Krisztian {
545607c4aafSKOVACS Krisztian 	const struct iphdr *iph = ip_hdr(skb);
546607c4aafSKOVACS Krisztian 
547ed7cbbceSAlexander Duyck 	return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
548607c4aafSKOVACS Krisztian 				 iph->daddr, dport, inet_iif(skb),
549fb74c277SDavid Ahern 				 inet_sdif(skb), udptable, skb);
550607c4aafSKOVACS Krisztian }
551607c4aafSKOVACS Krisztian 
5527b58e63eSEric Dumazet struct sock *udp4_lib_lookup_skb(const struct sk_buff *skb,
55363058308STom Herbert 				 __be16 sport, __be16 dport)
55463058308STom Herbert {
555257a525fSMartin KaFai Lau 	const struct iphdr *iph = ip_hdr(skb);
556ba6aac15SKuniyuki Iwashima 	struct net *net = dev_net(skb->dev);
557257a525fSMartin KaFai Lau 
558ba6aac15SKuniyuki Iwashima 	return __udp4_lib_lookup(net, iph->saddr, sport,
559257a525fSMartin KaFai Lau 				 iph->daddr, dport, inet_iif(skb),
560ba6aac15SKuniyuki Iwashima 				 inet_sdif(skb), net->ipv4.udp_table, NULL);
56163058308STom Herbert }
56263058308STom Herbert 
563ca065d0cSEric Dumazet /* Must be called under rcu_read_lock().
564ca065d0cSEric Dumazet  * Does increment socket refcount.
565ca065d0cSEric Dumazet  */
5666e86000cSArnd Bergmann #if IS_ENABLED(CONFIG_NF_TPROXY_IPV4) || IS_ENABLED(CONFIG_NF_SOCKET_IPV4)
567bcd41303SKOVACS Krisztian struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
568bcd41303SKOVACS Krisztian 			     __be32 daddr, __be16 dport, int dif)
569bcd41303SKOVACS Krisztian {
570ca065d0cSEric Dumazet 	struct sock *sk;
571ca065d0cSEric Dumazet 
572ca065d0cSEric Dumazet 	sk = __udp4_lib_lookup(net, saddr, sport, daddr, dport,
573ba6aac15SKuniyuki Iwashima 			       dif, 0, net->ipv4.udp_table, NULL);
57441c6d650SReshetova, Elena 	if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
575ca065d0cSEric Dumazet 		sk = NULL;
576ca065d0cSEric Dumazet 	return sk;
577bcd41303SKOVACS Krisztian }
578bcd41303SKOVACS Krisztian EXPORT_SYMBOL_GPL(udp4_lib_lookup);
579ca065d0cSEric Dumazet #endif
580bcd41303SKOVACS Krisztian 
581421b3885SShawn Bohrer static inline bool __udp_is_mcast_sock(struct net *net, struct sock *sk,
582421b3885SShawn Bohrer 				       __be16 loc_port, __be32 loc_addr,
583421b3885SShawn Bohrer 				       __be16 rmt_port, __be32 rmt_addr,
584fb74c277SDavid Ahern 				       int dif, int sdif, unsigned short hnum)
585421b3885SShawn Bohrer {
586421b3885SShawn Bohrer 	struct inet_sock *inet = inet_sk(sk);
587421b3885SShawn Bohrer 
588421b3885SShawn Bohrer 	if (!net_eq(sock_net(sk), net) ||
589421b3885SShawn Bohrer 	    udp_sk(sk)->udp_port_hash != hnum ||
590421b3885SShawn Bohrer 	    (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
591421b3885SShawn Bohrer 	    (inet->inet_dport != rmt_port && inet->inet_dport) ||
592421b3885SShawn Bohrer 	    (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) ||
593421b3885SShawn Bohrer 	    ipv6_only_sock(sk) ||
59482ba25c6STim Beale 	    !udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif))
595421b3885SShawn Bohrer 		return false;
59660d9b031SDavid Ahern 	if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif, sdif))
597421b3885SShawn Bohrer 		return false;
598421b3885SShawn Bohrer 	return true;
599421b3885SShawn Bohrer }
600421b3885SShawn Bohrer 
601a36e185eSStefano Brivio DEFINE_STATIC_KEY_FALSE(udp_encap_needed_key);
602a36e185eSStefano Brivio void udp_encap_enable(void)
603a36e185eSStefano Brivio {
6049c480601SPaolo Abeni 	static_branch_inc(&udp_encap_needed_key);
605a36e185eSStefano Brivio }
606a36e185eSStefano Brivio EXPORT_SYMBOL(udp_encap_enable);
607a36e185eSStefano Brivio 
608a4a600ddSXin Long void udp_encap_disable(void)
609a4a600ddSXin Long {
610a4a600ddSXin Long 	static_branch_dec(&udp_encap_needed_key);
611a4a600ddSXin Long }
612a4a600ddSXin Long EXPORT_SYMBOL(udp_encap_disable);
613a4a600ddSXin Long 
614e7cc0824SStefano Brivio /* Handler for tunnels with arbitrary destination ports: no socket lookup, go
615e7cc0824SStefano Brivio  * through error handlers in encapsulations looking for a match.
616e7cc0824SStefano Brivio  */
617e7cc0824SStefano Brivio static int __udp4_lib_err_encap_no_sk(struct sk_buff *skb, u32 info)
618e7cc0824SStefano Brivio {
619e7cc0824SStefano Brivio 	int i;
620e7cc0824SStefano Brivio 
621e7cc0824SStefano Brivio 	for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) {
622e7cc0824SStefano Brivio 		int (*handler)(struct sk_buff *skb, u32 info);
62392b95364SPaolo Abeni 		const struct ip_tunnel_encap_ops *encap;
624e7cc0824SStefano Brivio 
62592b95364SPaolo Abeni 		encap = rcu_dereference(iptun_encaps[i]);
62692b95364SPaolo Abeni 		if (!encap)
627e7cc0824SStefano Brivio 			continue;
62892b95364SPaolo Abeni 		handler = encap->err_handler;
629e7cc0824SStefano Brivio 		if (handler && !handler(skb, info))
630e7cc0824SStefano Brivio 			return 0;
631e7cc0824SStefano Brivio 	}
632e7cc0824SStefano Brivio 
633e7cc0824SStefano Brivio 	return -ENOENT;
634e7cc0824SStefano Brivio }
635e7cc0824SStefano Brivio 
636a36e185eSStefano Brivio /* Try to match ICMP errors to UDP tunnels by looking up a socket without
637a36e185eSStefano Brivio  * reversing source and destination port: this will match tunnels that force the
638a36e185eSStefano Brivio  * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that
639a36e185eSStefano Brivio  * lwtunnels might actually break this assumption by being configured with
640a36e185eSStefano Brivio  * different destination ports on endpoints, in this case we won't be able to
641a36e185eSStefano Brivio  * trace ICMP messages back to them.
642a36e185eSStefano Brivio  *
643e7cc0824SStefano Brivio  * If this doesn't match any socket, probe tunnels with arbitrary destination
644e7cc0824SStefano Brivio  * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port
645e7cc0824SStefano Brivio  * we've sent packets to won't necessarily match the local destination port.
646e7cc0824SStefano Brivio  *
647a36e185eSStefano Brivio  * Then ask the tunnel implementation to match the error against a valid
648a36e185eSStefano Brivio  * association.
649a36e185eSStefano Brivio  *
650e7cc0824SStefano Brivio  * Return an error if we can't find a match, the socket if we need further
651e7cc0824SStefano Brivio  * processing, zero otherwise.
652a36e185eSStefano Brivio  */
653a36e185eSStefano Brivio static struct sock *__udp4_lib_err_encap(struct net *net,
654a36e185eSStefano Brivio 					 const struct iphdr *iph,
655a36e185eSStefano Brivio 					 struct udphdr *uh,
656a36e185eSStefano Brivio 					 struct udp_table *udptable,
6579bfce73cSVadim Fedorenko 					 struct sock *sk,
658e7cc0824SStefano Brivio 					 struct sk_buff *skb, u32 info)
659a36e185eSStefano Brivio {
6609bfce73cSVadim Fedorenko 	int (*lookup)(struct sock *sk, struct sk_buff *skb);
661a36e185eSStefano Brivio 	int network_offset, transport_offset;
6629bfce73cSVadim Fedorenko 	struct udp_sock *up;
663a36e185eSStefano Brivio 
664a36e185eSStefano Brivio 	network_offset = skb_network_offset(skb);
665a36e185eSStefano Brivio 	transport_offset = skb_transport_offset(skb);
666a36e185eSStefano Brivio 
667a36e185eSStefano Brivio 	/* Network header needs to point to the outer IPv4 header inside ICMP */
668a36e185eSStefano Brivio 	skb_reset_network_header(skb);
669a36e185eSStefano Brivio 
670a36e185eSStefano Brivio 	/* Transport header needs to point to the UDP header */
671a36e185eSStefano Brivio 	skb_set_transport_header(skb, iph->ihl << 2);
672a36e185eSStefano Brivio 
6739bfce73cSVadim Fedorenko 	if (sk) {
6749bfce73cSVadim Fedorenko 		up = udp_sk(sk);
6759bfce73cSVadim Fedorenko 
6769bfce73cSVadim Fedorenko 		lookup = READ_ONCE(up->encap_err_lookup);
6779bfce73cSVadim Fedorenko 		if (lookup && lookup(sk, skb))
6789bfce73cSVadim Fedorenko 			sk = NULL;
6799bfce73cSVadim Fedorenko 
6809bfce73cSVadim Fedorenko 		goto out;
6819bfce73cSVadim Fedorenko 	}
6829bfce73cSVadim Fedorenko 
683e7cc0824SStefano Brivio 	sk = __udp4_lib_lookup(net, iph->daddr, uh->source,
684e7cc0824SStefano Brivio 			       iph->saddr, uh->dest, skb->dev->ifindex, 0,
685e7cc0824SStefano Brivio 			       udptable, NULL);
686e7cc0824SStefano Brivio 	if (sk) {
6879bfce73cSVadim Fedorenko 		up = udp_sk(sk);
688e7cc0824SStefano Brivio 
689a36e185eSStefano Brivio 		lookup = READ_ONCE(up->encap_err_lookup);
690a36e185eSStefano Brivio 		if (!lookup || lookup(sk, skb))
691a36e185eSStefano Brivio 			sk = NULL;
692e7cc0824SStefano Brivio 	}
693e7cc0824SStefano Brivio 
6949bfce73cSVadim Fedorenko out:
695e7cc0824SStefano Brivio 	if (!sk)
696e7cc0824SStefano Brivio 		sk = ERR_PTR(__udp4_lib_err_encap_no_sk(skb, info));
697a36e185eSStefano Brivio 
698a36e185eSStefano Brivio 	skb_set_transport_header(skb, transport_offset);
699a36e185eSStefano Brivio 	skb_set_network_header(skb, network_offset);
700a36e185eSStefano Brivio 
701a36e185eSStefano Brivio 	return sk;
702a36e185eSStefano Brivio }
703a36e185eSStefano Brivio 
704db8dac20SDavid S. Miller /*
705db8dac20SDavid S. Miller  * This routine is called by the ICMP module when it gets some
706db8dac20SDavid S. Miller  * sort of error condition.  If err < 0 then the socket should
707db8dac20SDavid S. Miller  * be closed and the error returned to the user.  If err > 0
708db8dac20SDavid S. Miller  * it's just the icmp type << 8 | icmp code.
709db8dac20SDavid S. Miller  * Header points to the ip header of the error packet. We move
710db8dac20SDavid S. Miller  * on past this. Then (as it used to claim before adjustment)
711db8dac20SDavid S. Miller  * header points to the first 8 bytes of the udp header.  We need
712db8dac20SDavid S. Miller  * to find the appropriate port.
713db8dac20SDavid S. Miller  */
714db8dac20SDavid S. Miller 
71532bbd879SStefano Brivio int __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
716db8dac20SDavid S. Miller {
717db8dac20SDavid S. Miller 	struct inet_sock *inet;
718b71d1d42SEric Dumazet 	const struct iphdr *iph = (const struct iphdr *)skb->data;
719db8dac20SDavid S. Miller 	struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
720db8dac20SDavid S. Miller 	const int type = icmp_hdr(skb)->type;
721db8dac20SDavid S. Miller 	const int code = icmp_hdr(skb)->code;
722a36e185eSStefano Brivio 	bool tunnel = false;
723db8dac20SDavid S. Miller 	struct sock *sk;
724db8dac20SDavid S. Miller 	int harderr;
725db8dac20SDavid S. Miller 	int err;
726fd54d716SPavel Emelyanov 	struct net *net = dev_net(skb->dev);
727db8dac20SDavid S. Miller 
728fd54d716SPavel Emelyanov 	sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
729f64bf6b8SMike Manning 			       iph->saddr, uh->source, skb->dev->ifindex,
730f64bf6b8SMike Manning 			       inet_sdif(skb), udptable, NULL);
7319bfce73cSVadim Fedorenko 
732d26796aeSXin Long 	if (!sk || udp_sk(sk)->encap_type) {
733a36e185eSStefano Brivio 		/* No socket for error: try tunnels before discarding */
734e7cc0824SStefano Brivio 		if (static_branch_unlikely(&udp_encap_needed_key)) {
7359bfce73cSVadim Fedorenko 			sk = __udp4_lib_err_encap(net, iph, uh, udptable, sk, skb,
736e7cc0824SStefano Brivio 						  info);
737e7cc0824SStefano Brivio 			if (!sk)
738e7cc0824SStefano Brivio 				return 0;
7399bfce73cSVadim Fedorenko 		} else
7409bfce73cSVadim Fedorenko 			sk = ERR_PTR(-ENOENT);
741e7cc0824SStefano Brivio 
742e7cc0824SStefano Brivio 		if (IS_ERR(sk)) {
743e7cc0824SStefano Brivio 			__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
744e7cc0824SStefano Brivio 			return PTR_ERR(sk);
745e7cc0824SStefano Brivio 		}
746e7cc0824SStefano Brivio 
747a36e185eSStefano Brivio 		tunnel = true;
748db8dac20SDavid S. Miller 	}
749db8dac20SDavid S. Miller 
750db8dac20SDavid S. Miller 	err = 0;
751db8dac20SDavid S. Miller 	harderr = 0;
752db8dac20SDavid S. Miller 	inet = inet_sk(sk);
753db8dac20SDavid S. Miller 
754db8dac20SDavid S. Miller 	switch (type) {
755db8dac20SDavid S. Miller 	default:
756db8dac20SDavid S. Miller 	case ICMP_TIME_EXCEEDED:
757db8dac20SDavid S. Miller 		err = EHOSTUNREACH;
758db8dac20SDavid S. Miller 		break;
759db8dac20SDavid S. Miller 	case ICMP_SOURCE_QUENCH:
760db8dac20SDavid S. Miller 		goto out;
761db8dac20SDavid S. Miller 	case ICMP_PARAMETERPROB:
762db8dac20SDavid S. Miller 		err = EPROTO;
763db8dac20SDavid S. Miller 		harderr = 1;
764db8dac20SDavid S. Miller 		break;
765db8dac20SDavid S. Miller 	case ICMP_DEST_UNREACH:
766db8dac20SDavid S. Miller 		if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
76736393395SDavid S. Miller 			ipv4_sk_update_pmtu(skb, sk, info);
768db8dac20SDavid S. Miller 			if (inet->pmtudisc != IP_PMTUDISC_DONT) {
769db8dac20SDavid S. Miller 				err = EMSGSIZE;
770db8dac20SDavid S. Miller 				harderr = 1;
771db8dac20SDavid S. Miller 				break;
772db8dac20SDavid S. Miller 			}
773db8dac20SDavid S. Miller 			goto out;
774db8dac20SDavid S. Miller 		}
775db8dac20SDavid S. Miller 		err = EHOSTUNREACH;
776db8dac20SDavid S. Miller 		if (code <= NR_ICMP_UNREACH) {
777db8dac20SDavid S. Miller 			harderr = icmp_err_convert[code].fatal;
778db8dac20SDavid S. Miller 			err = icmp_err_convert[code].errno;
779db8dac20SDavid S. Miller 		}
780db8dac20SDavid S. Miller 		break;
78155be7a9cSDavid S. Miller 	case ICMP_REDIRECT:
78255be7a9cSDavid S. Miller 		ipv4_sk_redirect(skb, sk);
7831a462d18SDuan Jiong 		goto out;
784db8dac20SDavid S. Miller 	}
785db8dac20SDavid S. Miller 
786db8dac20SDavid S. Miller 	/*
787db8dac20SDavid S. Miller 	 *      RFC1122: OK.  Passes ICMP errors back to application, as per
788db8dac20SDavid S. Miller 	 *	4.1.3.3.
789db8dac20SDavid S. Miller 	 */
790a36e185eSStefano Brivio 	if (tunnel) {
791a36e185eSStefano Brivio 		/* ...not for tunnels though: we don't have a sending socket */
792ac56a0b4SDavid Howells 		if (udp_sk(sk)->encap_err_rcv)
79342fb06b3SDavid Howells 			udp_sk(sk)->encap_err_rcv(sk, skb, err, uh->dest, info,
79442fb06b3SDavid Howells 						  (u8 *)(uh+1));
795a36e185eSStefano Brivio 		goto out;
796a36e185eSStefano Brivio 	}
797db8dac20SDavid S. Miller 	if (!inet->recverr) {
798db8dac20SDavid S. Miller 		if (!harderr || sk->sk_state != TCP_ESTABLISHED)
799db8dac20SDavid S. Miller 			goto out;
800b1faf566SEric Dumazet 	} else
801db8dac20SDavid S. Miller 		ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
802b1faf566SEric Dumazet 
803db8dac20SDavid S. Miller 	sk->sk_err = err;
804e3ae2365SAlexander Aring 	sk_error_report(sk);
805db8dac20SDavid S. Miller out:
80632bbd879SStefano Brivio 	return 0;
807db8dac20SDavid S. Miller }
808db8dac20SDavid S. Miller 
80932bbd879SStefano Brivio int udp_err(struct sk_buff *skb, u32 info)
810db8dac20SDavid S. Miller {
811ba6aac15SKuniyuki Iwashima 	return __udp4_lib_err(skb, info, dev_net(skb->dev)->ipv4.udp_table);
812db8dac20SDavid S. Miller }
813db8dac20SDavid S. Miller 
814db8dac20SDavid S. Miller /*
815db8dac20SDavid S. Miller  * Throw away all pending data and cancel the corking. Socket is locked.
816db8dac20SDavid S. Miller  */
81736d926b9SDenis V. Lunev void udp_flush_pending_frames(struct sock *sk)
818db8dac20SDavid S. Miller {
819db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
820db8dac20SDavid S. Miller 
821db8dac20SDavid S. Miller 	if (up->pending) {
822db8dac20SDavid S. Miller 		up->len = 0;
823db8dac20SDavid S. Miller 		up->pending = 0;
824db8dac20SDavid S. Miller 		ip_flush_pending_frames(sk);
825db8dac20SDavid S. Miller 	}
826db8dac20SDavid S. Miller }
82736d926b9SDenis V. Lunev EXPORT_SYMBOL(udp_flush_pending_frames);
828db8dac20SDavid S. Miller 
829db8dac20SDavid S. Miller /**
830f6b9664fSHerbert Xu  * 	udp4_hwcsum  -  handle outgoing HW checksumming
831db8dac20SDavid S. Miller  * 	@skb: 	sk_buff containing the filled-in UDP header
832db8dac20SDavid S. Miller  * 	        (checksum field must be zeroed out)
833f6b9664fSHerbert Xu  *	@src:	source IP address
834f6b9664fSHerbert Xu  *	@dst:	destination IP address
835db8dac20SDavid S. Miller  */
836c26bf4a5SThomas Graf void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
837db8dac20SDavid S. Miller {
838db8dac20SDavid S. Miller 	struct udphdr *uh = udp_hdr(skb);
839f6b9664fSHerbert Xu 	int offset = skb_transport_offset(skb);
840f6b9664fSHerbert Xu 	int len = skb->len - offset;
841f6b9664fSHerbert Xu 	int hlen = len;
842db8dac20SDavid S. Miller 	__wsum csum = 0;
843db8dac20SDavid S. Miller 
844ebbe495fSWANG Cong 	if (!skb_has_frag_list(skb)) {
845db8dac20SDavid S. Miller 		/*
846db8dac20SDavid S. Miller 		 * Only one fragment on the socket.
847db8dac20SDavid S. Miller 		 */
848db8dac20SDavid S. Miller 		skb->csum_start = skb_transport_header(skb) - skb->head;
849db8dac20SDavid S. Miller 		skb->csum_offset = offsetof(struct udphdr, check);
850f6b9664fSHerbert Xu 		uh->check = ~csum_tcpudp_magic(src, dst, len,
851f6b9664fSHerbert Xu 					       IPPROTO_UDP, 0);
852db8dac20SDavid S. Miller 	} else {
853ebbe495fSWANG Cong 		struct sk_buff *frags;
854ebbe495fSWANG Cong 
855db8dac20SDavid S. Miller 		/*
856db8dac20SDavid S. Miller 		 * HW-checksum won't work as there are two or more
857db8dac20SDavid S. Miller 		 * fragments on the socket so that all csums of sk_buffs
858db8dac20SDavid S. Miller 		 * should be together
859db8dac20SDavid S. Miller 		 */
860ebbe495fSWANG Cong 		skb_walk_frags(skb, frags) {
861f6b9664fSHerbert Xu 			csum = csum_add(csum, frags->csum);
862f6b9664fSHerbert Xu 			hlen -= frags->len;
863ebbe495fSWANG Cong 		}
864db8dac20SDavid S. Miller 
865f6b9664fSHerbert Xu 		csum = skb_checksum(skb, offset, hlen, csum);
866db8dac20SDavid S. Miller 		skb->ip_summed = CHECKSUM_NONE;
867db8dac20SDavid S. Miller 
868db8dac20SDavid S. Miller 		uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
869db8dac20SDavid S. Miller 		if (uh->check == 0)
870db8dac20SDavid S. Miller 			uh->check = CSUM_MANGLED_0;
871db8dac20SDavid S. Miller 	}
872db8dac20SDavid S. Miller }
873c26bf4a5SThomas Graf EXPORT_SYMBOL_GPL(udp4_hwcsum);
874db8dac20SDavid S. Miller 
875af5fcba7STom Herbert /* Function to set UDP checksum for an IPv4 UDP packet. This is intended
876af5fcba7STom Herbert  * for the simple case like when setting the checksum for a UDP tunnel.
877af5fcba7STom Herbert  */
878af5fcba7STom Herbert void udp_set_csum(bool nocheck, struct sk_buff *skb,
879af5fcba7STom Herbert 		  __be32 saddr, __be32 daddr, int len)
880af5fcba7STom Herbert {
881af5fcba7STom Herbert 	struct udphdr *uh = udp_hdr(skb);
882af5fcba7STom Herbert 
883179bc67fSEdward Cree 	if (nocheck) {
884af5fcba7STom Herbert 		uh->check = 0;
885179bc67fSEdward Cree 	} else if (skb_is_gso(skb)) {
886af5fcba7STom Herbert 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
887179bc67fSEdward Cree 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) {
888179bc67fSEdward Cree 		uh->check = 0;
889179bc67fSEdward Cree 		uh->check = udp_v4_check(len, saddr, daddr, lco_csum(skb));
890179bc67fSEdward Cree 		if (uh->check == 0)
891179bc67fSEdward Cree 			uh->check = CSUM_MANGLED_0;
892d75f1306SEdward Cree 	} else {
893af5fcba7STom Herbert 		skb->ip_summed = CHECKSUM_PARTIAL;
894af5fcba7STom Herbert 		skb->csum_start = skb_transport_header(skb) - skb->head;
895af5fcba7STom Herbert 		skb->csum_offset = offsetof(struct udphdr, check);
896af5fcba7STom Herbert 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
897af5fcba7STom Herbert 	}
898af5fcba7STom Herbert }
899af5fcba7STom Herbert EXPORT_SYMBOL(udp_set_csum);
900af5fcba7STom Herbert 
901bec1f6f6SWillem de Bruijn static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4,
902bec1f6f6SWillem de Bruijn 			struct inet_cork *cork)
903f6b9664fSHerbert Xu {
904f6b9664fSHerbert Xu 	struct sock *sk = skb->sk;
905f6b9664fSHerbert Xu 	struct inet_sock *inet = inet_sk(sk);
906f6b9664fSHerbert Xu 	struct udphdr *uh;
907cffb8f61SMenglong Dong 	int err;
908f6b9664fSHerbert Xu 	int is_udplite = IS_UDPLITE(sk);
909f6b9664fSHerbert Xu 	int offset = skb_transport_offset(skb);
910f6b9664fSHerbert Xu 	int len = skb->len - offset;
9114094871dSJosh Hunt 	int datalen = len - sizeof(*uh);
912f6b9664fSHerbert Xu 	__wsum csum = 0;
913f6b9664fSHerbert Xu 
914f6b9664fSHerbert Xu 	/*
915f6b9664fSHerbert Xu 	 * Create a UDP header
916f6b9664fSHerbert Xu 	 */
917f6b9664fSHerbert Xu 	uh = udp_hdr(skb);
918f6b9664fSHerbert Xu 	uh->source = inet->inet_sport;
91979ab0531SDavid S. Miller 	uh->dest = fl4->fl4_dport;
920f6b9664fSHerbert Xu 	uh->len = htons(len);
921f6b9664fSHerbert Xu 	uh->check = 0;
922f6b9664fSHerbert Xu 
923bec1f6f6SWillem de Bruijn 	if (cork->gso_size) {
924bec1f6f6SWillem de Bruijn 		const int hlen = skb_network_header_len(skb) +
925bec1f6f6SWillem de Bruijn 				 sizeof(struct udphdr);
926bec1f6f6SWillem de Bruijn 
9270f149c9fSWillem de Bruijn 		if (hlen + cork->gso_size > cork->fragsize) {
9280f149c9fSWillem de Bruijn 			kfree_skb(skb);
929bec1f6f6SWillem de Bruijn 			return -EINVAL;
9300f149c9fSWillem de Bruijn 		}
931158390e4SJianguo Wu 		if (datalen > cork->gso_size * UDP_MAX_SEGMENTS) {
9320f149c9fSWillem de Bruijn 			kfree_skb(skb);
933bec1f6f6SWillem de Bruijn 			return -EINVAL;
9340f149c9fSWillem de Bruijn 		}
9350f149c9fSWillem de Bruijn 		if (sk->sk_no_check_tx) {
9360f149c9fSWillem de Bruijn 			kfree_skb(skb);
937a8c744a8SWillem de Bruijn 			return -EINVAL;
9380f149c9fSWillem de Bruijn 		}
939ff06342cSWillem de Bruijn 		if (skb->ip_summed != CHECKSUM_PARTIAL || is_udplite ||
9400f149c9fSWillem de Bruijn 		    dst_xfrm(skb_dst(skb))) {
9410f149c9fSWillem de Bruijn 			kfree_skb(skb);
942bec1f6f6SWillem de Bruijn 			return -EIO;
9430f149c9fSWillem de Bruijn 		}
944bec1f6f6SWillem de Bruijn 
9454094871dSJosh Hunt 		if (datalen > cork->gso_size) {
946bec1f6f6SWillem de Bruijn 			skb_shinfo(skb)->gso_size = cork->gso_size;
947bec1f6f6SWillem de Bruijn 			skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4;
9484094871dSJosh Hunt 			skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(datalen,
949dfec0ee2SAlexander Duyck 								 cork->gso_size);
9504094871dSJosh Hunt 		}
951a8c744a8SWillem de Bruijn 		goto csum_partial;
952bec1f6f6SWillem de Bruijn 	}
953bec1f6f6SWillem de Bruijn 
954f6b9664fSHerbert Xu 	if (is_udplite)  				 /*     UDP-Lite      */
955f6b9664fSHerbert Xu 		csum = udplite_csum(skb);
956f6b9664fSHerbert Xu 
957ab2fb7e3SWillem de Bruijn 	else if (sk->sk_no_check_tx) {			 /* UDP csum off */
958f6b9664fSHerbert Xu 
959f6b9664fSHerbert Xu 		skb->ip_summed = CHECKSUM_NONE;
960f6b9664fSHerbert Xu 		goto send;
961f6b9664fSHerbert Xu 
962f6b9664fSHerbert Xu 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
963a8c744a8SWillem de Bruijn csum_partial:
964f6b9664fSHerbert Xu 
96579ab0531SDavid S. Miller 		udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
966f6b9664fSHerbert Xu 		goto send;
967f6b9664fSHerbert Xu 
968f6b9664fSHerbert Xu 	} else
969f6b9664fSHerbert Xu 		csum = udp_csum(skb);
970f6b9664fSHerbert Xu 
971f6b9664fSHerbert Xu 	/* add protocol-dependent pseudo-header */
97279ab0531SDavid S. Miller 	uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
973f6b9664fSHerbert Xu 				      sk->sk_protocol, csum);
974f6b9664fSHerbert Xu 	if (uh->check == 0)
975f6b9664fSHerbert Xu 		uh->check = CSUM_MANGLED_0;
976f6b9664fSHerbert Xu 
977f6b9664fSHerbert Xu send:
978b5ec8eeaSEric Dumazet 	err = ip_send_skb(sock_net(sk), skb);
979f6b9664fSHerbert Xu 	if (err) {
980f6b9664fSHerbert Xu 		if (err == -ENOBUFS && !inet->recverr) {
9816aef70a8SEric Dumazet 			UDP_INC_STATS(sock_net(sk),
982f6b9664fSHerbert Xu 				      UDP_MIB_SNDBUFERRORS, is_udplite);
983f6b9664fSHerbert Xu 			err = 0;
984f6b9664fSHerbert Xu 		}
985f6b9664fSHerbert Xu 	} else
9866aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
987f6b9664fSHerbert Xu 			      UDP_MIB_OUTDATAGRAMS, is_udplite);
988f6b9664fSHerbert Xu 	return err;
989f6b9664fSHerbert Xu }
990f6b9664fSHerbert Xu 
991db8dac20SDavid S. Miller /*
992db8dac20SDavid S. Miller  * Push out all pending data as one UDP datagram. Socket is locked.
993db8dac20SDavid S. Miller  */
9948822b64aSHannes Frederic Sowa int udp_push_pending_frames(struct sock *sk)
995db8dac20SDavid S. Miller {
996db8dac20SDavid S. Miller 	struct udp_sock  *up = udp_sk(sk);
997db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
998b6f21b26SDavid S. Miller 	struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
999db8dac20SDavid S. Miller 	struct sk_buff *skb;
1000db8dac20SDavid S. Miller 	int err = 0;
1001db8dac20SDavid S. Miller 
100277968b78SDavid S. Miller 	skb = ip_finish_skb(sk, fl4);
1003f6b9664fSHerbert Xu 	if (!skb)
1004db8dac20SDavid S. Miller 		goto out;
1005db8dac20SDavid S. Miller 
1006bec1f6f6SWillem de Bruijn 	err = udp_send_skb(skb, fl4, &inet->cork.base);
1007db8dac20SDavid S. Miller 
1008db8dac20SDavid S. Miller out:
1009db8dac20SDavid S. Miller 	up->len = 0;
1010db8dac20SDavid S. Miller 	up->pending = 0;
1011db8dac20SDavid S. Miller 	return err;
1012db8dac20SDavid S. Miller }
10138822b64aSHannes Frederic Sowa EXPORT_SYMBOL(udp_push_pending_frames);
1014db8dac20SDavid S. Miller 
10152e8de857SWillem de Bruijn static int __udp_cmsg_send(struct cmsghdr *cmsg, u16 *gso_size)
10162e8de857SWillem de Bruijn {
10172e8de857SWillem de Bruijn 	switch (cmsg->cmsg_type) {
10182e8de857SWillem de Bruijn 	case UDP_SEGMENT:
10192e8de857SWillem de Bruijn 		if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u16)))
10202e8de857SWillem de Bruijn 			return -EINVAL;
10212e8de857SWillem de Bruijn 		*gso_size = *(__u16 *)CMSG_DATA(cmsg);
10222e8de857SWillem de Bruijn 		return 0;
10232e8de857SWillem de Bruijn 	default:
10242e8de857SWillem de Bruijn 		return -EINVAL;
10252e8de857SWillem de Bruijn 	}
10262e8de857SWillem de Bruijn }
10272e8de857SWillem de Bruijn 
10282e8de857SWillem de Bruijn int udp_cmsg_send(struct sock *sk, struct msghdr *msg, u16 *gso_size)
10292e8de857SWillem de Bruijn {
10302e8de857SWillem de Bruijn 	struct cmsghdr *cmsg;
10312e8de857SWillem de Bruijn 	bool need_ip = false;
10322e8de857SWillem de Bruijn 	int err;
10332e8de857SWillem de Bruijn 
10342e8de857SWillem de Bruijn 	for_each_cmsghdr(cmsg, msg) {
10352e8de857SWillem de Bruijn 		if (!CMSG_OK(msg, cmsg))
10362e8de857SWillem de Bruijn 			return -EINVAL;
10372e8de857SWillem de Bruijn 
10382e8de857SWillem de Bruijn 		if (cmsg->cmsg_level != SOL_UDP) {
10392e8de857SWillem de Bruijn 			need_ip = true;
10402e8de857SWillem de Bruijn 			continue;
10412e8de857SWillem de Bruijn 		}
10422e8de857SWillem de Bruijn 
10432e8de857SWillem de Bruijn 		err = __udp_cmsg_send(cmsg, gso_size);
10442e8de857SWillem de Bruijn 		if (err)
10452e8de857SWillem de Bruijn 			return err;
10462e8de857SWillem de Bruijn 	}
10472e8de857SWillem de Bruijn 
10482e8de857SWillem de Bruijn 	return need_ip;
10492e8de857SWillem de Bruijn }
10502e8de857SWillem de Bruijn EXPORT_SYMBOL_GPL(udp_cmsg_send);
10512e8de857SWillem de Bruijn 
10521b784140SYing Xue int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1053db8dac20SDavid S. Miller {
1054db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1055db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
10561cedee13SAndrey Ignatov 	DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
1057e474995fSDavid S. Miller 	struct flowi4 fl4_stack;
1058b6f21b26SDavid S. Miller 	struct flowi4 *fl4;
1059db8dac20SDavid S. Miller 	int ulen = len;
1060db8dac20SDavid S. Miller 	struct ipcm_cookie ipc;
1061db8dac20SDavid S. Miller 	struct rtable *rt = NULL;
1062db8dac20SDavid S. Miller 	int free = 0;
1063db8dac20SDavid S. Miller 	int connected = 0;
1064db8dac20SDavid S. Miller 	__be32 daddr, faddr, saddr;
1065db8dac20SDavid S. Miller 	__be16 dport;
1066db8dac20SDavid S. Miller 	u8  tos;
1067db8dac20SDavid S. Miller 	int err, is_udplite = IS_UDPLITE(sk);
1068a9f59707SEric Dumazet 	int corkreq = READ_ONCE(up->corkflag) || msg->msg_flags&MSG_MORE;
1069db8dac20SDavid S. Miller 	int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
1070903ab86dSHerbert Xu 	struct sk_buff *skb;
1071f6d8bd05SEric Dumazet 	struct ip_options_data opt_copy;
1072db8dac20SDavid S. Miller 
1073db8dac20SDavid S. Miller 	if (len > 0xFFFF)
1074db8dac20SDavid S. Miller 		return -EMSGSIZE;
1075db8dac20SDavid S. Miller 
1076db8dac20SDavid S. Miller 	/*
1077db8dac20SDavid S. Miller 	 *	Check the flags.
1078db8dac20SDavid S. Miller 	 */
1079db8dac20SDavid S. Miller 
1080db8dac20SDavid S. Miller 	if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
1081db8dac20SDavid S. Miller 		return -EOPNOTSUPP;
1082db8dac20SDavid S. Miller 
1083903ab86dSHerbert Xu 	getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
1084903ab86dSHerbert Xu 
1085f5fca608SDavid S. Miller 	fl4 = &inet->cork.fl.u.ip4;
1086db8dac20SDavid S. Miller 	if (up->pending) {
1087db8dac20SDavid S. Miller 		/*
1088db8dac20SDavid S. Miller 		 * There are pending frames.
1089db8dac20SDavid S. Miller 		 * The socket lock must be held while it's corked.
1090db8dac20SDavid S. Miller 		 */
1091db8dac20SDavid S. Miller 		lock_sock(sk);
1092db8dac20SDavid S. Miller 		if (likely(up->pending)) {
1093db8dac20SDavid S. Miller 			if (unlikely(up->pending != AF_INET)) {
1094db8dac20SDavid S. Miller 				release_sock(sk);
1095db8dac20SDavid S. Miller 				return -EINVAL;
1096db8dac20SDavid S. Miller 			}
1097db8dac20SDavid S. Miller 			goto do_append_data;
1098db8dac20SDavid S. Miller 		}
1099db8dac20SDavid S. Miller 		release_sock(sk);
1100db8dac20SDavid S. Miller 	}
1101db8dac20SDavid S. Miller 	ulen += sizeof(struct udphdr);
1102db8dac20SDavid S. Miller 
1103db8dac20SDavid S. Miller 	/*
1104db8dac20SDavid S. Miller 	 *	Get and verify the address.
1105db8dac20SDavid S. Miller 	 */
11061cedee13SAndrey Ignatov 	if (usin) {
1107db8dac20SDavid S. Miller 		if (msg->msg_namelen < sizeof(*usin))
1108db8dac20SDavid S. Miller 			return -EINVAL;
1109db8dac20SDavid S. Miller 		if (usin->sin_family != AF_INET) {
1110db8dac20SDavid S. Miller 			if (usin->sin_family != AF_UNSPEC)
1111db8dac20SDavid S. Miller 				return -EAFNOSUPPORT;
1112db8dac20SDavid S. Miller 		}
1113db8dac20SDavid S. Miller 
1114db8dac20SDavid S. Miller 		daddr = usin->sin_addr.s_addr;
1115db8dac20SDavid S. Miller 		dport = usin->sin_port;
1116db8dac20SDavid S. Miller 		if (dport == 0)
1117db8dac20SDavid S. Miller 			return -EINVAL;
1118db8dac20SDavid S. Miller 	} else {
1119db8dac20SDavid S. Miller 		if (sk->sk_state != TCP_ESTABLISHED)
1120db8dac20SDavid S. Miller 			return -EDESTADDRREQ;
1121c720c7e8SEric Dumazet 		daddr = inet->inet_daddr;
1122c720c7e8SEric Dumazet 		dport = inet->inet_dport;
1123db8dac20SDavid S. Miller 		/* Open fast path for connected socket.
1124db8dac20SDavid S. Miller 		   Route will not be used, if at least one option is set.
1125db8dac20SDavid S. Miller 		 */
1126db8dac20SDavid S. Miller 		connected = 1;
1127db8dac20SDavid S. Miller 	}
1128c14ac945SSoheil Hassas Yeganeh 
112935178206SWillem de Bruijn 	ipcm_init_sk(&ipc, inet);
113018a419baSEric Dumazet 	ipc.gso_size = READ_ONCE(up->gso_size);
1131bf84a010SDaniel Borkmann 
1132db8dac20SDavid S. Miller 	if (msg->msg_controllen) {
11332e8de857SWillem de Bruijn 		err = udp_cmsg_send(sk, msg, &ipc.gso_size);
11342e8de857SWillem de Bruijn 		if (err > 0)
11352e8de857SWillem de Bruijn 			err = ip_cmsg_send(sk, msg, &ipc,
11362e8de857SWillem de Bruijn 					   sk->sk_family == AF_INET6);
11372e8de857SWillem de Bruijn 		if (unlikely(err < 0)) {
113891948309SEric Dumazet 			kfree(ipc.opt);
1139db8dac20SDavid S. Miller 			return err;
114091948309SEric Dumazet 		}
1141db8dac20SDavid S. Miller 		if (ipc.opt)
1142db8dac20SDavid S. Miller 			free = 1;
1143db8dac20SDavid S. Miller 		connected = 0;
1144db8dac20SDavid S. Miller 	}
1145f6d8bd05SEric Dumazet 	if (!ipc.opt) {
1146f6d8bd05SEric Dumazet 		struct ip_options_rcu *inet_opt;
1147f6d8bd05SEric Dumazet 
1148f6d8bd05SEric Dumazet 		rcu_read_lock();
1149f6d8bd05SEric Dumazet 		inet_opt = rcu_dereference(inet->inet_opt);
1150f6d8bd05SEric Dumazet 		if (inet_opt) {
1151f6d8bd05SEric Dumazet 			memcpy(&opt_copy, inet_opt,
1152f6d8bd05SEric Dumazet 			       sizeof(*inet_opt) + inet_opt->opt.optlen);
1153f6d8bd05SEric Dumazet 			ipc.opt = &opt_copy.opt;
1154f6d8bd05SEric Dumazet 		}
1155f6d8bd05SEric Dumazet 		rcu_read_unlock();
1156f6d8bd05SEric Dumazet 	}
1157db8dac20SDavid S. Miller 
11586fc88c35SDave Marchevsky 	if (cgroup_bpf_enabled(CGROUP_UDP4_SENDMSG) && !connected) {
11591cedee13SAndrey Ignatov 		err = BPF_CGROUP_RUN_PROG_UDP4_SENDMSG_LOCK(sk,
11601cedee13SAndrey Ignatov 					    (struct sockaddr *)usin, &ipc.addr);
11611cedee13SAndrey Ignatov 		if (err)
11621cedee13SAndrey Ignatov 			goto out_free;
11631cedee13SAndrey Ignatov 		if (usin) {
11641cedee13SAndrey Ignatov 			if (usin->sin_port == 0) {
11651cedee13SAndrey Ignatov 				/* BPF program set invalid port. Reject it. */
11661cedee13SAndrey Ignatov 				err = -EINVAL;
11671cedee13SAndrey Ignatov 				goto out_free;
11681cedee13SAndrey Ignatov 			}
11691cedee13SAndrey Ignatov 			daddr = usin->sin_addr.s_addr;
11701cedee13SAndrey Ignatov 			dport = usin->sin_port;
11711cedee13SAndrey Ignatov 		}
11721cedee13SAndrey Ignatov 	}
11731cedee13SAndrey Ignatov 
1174db8dac20SDavid S. Miller 	saddr = ipc.addr;
1175db8dac20SDavid S. Miller 	ipc.addr = faddr = daddr;
1176db8dac20SDavid S. Miller 
1177f6d8bd05SEric Dumazet 	if (ipc.opt && ipc.opt->opt.srr) {
11781b97013bSAndrey Ignatov 		if (!daddr) {
11791b97013bSAndrey Ignatov 			err = -EINVAL;
11801b97013bSAndrey Ignatov 			goto out_free;
11811b97013bSAndrey Ignatov 		}
1182f6d8bd05SEric Dumazet 		faddr = ipc.opt->opt.faddr;
1183db8dac20SDavid S. Miller 		connected = 0;
1184db8dac20SDavid S. Miller 	}
1185aa661581SFrancesco Fusco 	tos = get_rttos(&ipc, inet);
1186db8dac20SDavid S. Miller 	if (sock_flag(sk, SOCK_LOCALROUTE) ||
1187db8dac20SDavid S. Miller 	    (msg->msg_flags & MSG_DONTROUTE) ||
1188f6d8bd05SEric Dumazet 	    (ipc.opt && ipc.opt->opt.is_strictroute)) {
1189db8dac20SDavid S. Miller 		tos |= RTO_ONLINK;
1190db8dac20SDavid S. Miller 		connected = 0;
1191db8dac20SDavid S. Miller 	}
1192db8dac20SDavid S. Miller 
1193db8dac20SDavid S. Miller 	if (ipv4_is_multicast(daddr)) {
1194854da991SRobert Shearman 		if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif))
1195db8dac20SDavid S. Miller 			ipc.oif = inet->mc_index;
1196db8dac20SDavid S. Miller 		if (!saddr)
1197db8dac20SDavid S. Miller 			saddr = inet->mc_addr;
1198db8dac20SDavid S. Miller 		connected = 0;
11999515a2e0SDavid Ahern 	} else if (!ipc.oif) {
120076e21053SErich E. Hoover 		ipc.oif = inet->uc_index;
12019515a2e0SDavid Ahern 	} else if (ipv4_is_lbcast(daddr) && inet->uc_index) {
12029515a2e0SDavid Ahern 		/* oif is set, packet is to local broadcast and
12032bdcc73cSRandy Dunlap 		 * uc_index is set. oif is most likely set
12049515a2e0SDavid Ahern 		 * by sk_bound_dev_if. If uc_index != oif check if the
12059515a2e0SDavid Ahern 		 * oif is an L3 master and uc_index is an L3 slave.
12069515a2e0SDavid Ahern 		 * If so, we want to allow the send using the uc_index.
12079515a2e0SDavid Ahern 		 */
12089515a2e0SDavid Ahern 		if (ipc.oif != inet->uc_index &&
12099515a2e0SDavid Ahern 		    ipc.oif == l3mdev_master_ifindex_by_index(sock_net(sk),
12109515a2e0SDavid Ahern 							      inet->uc_index)) {
12119515a2e0SDavid Ahern 			ipc.oif = inet->uc_index;
12129515a2e0SDavid Ahern 		}
12139515a2e0SDavid Ahern 	}
1214db8dac20SDavid S. Miller 
1215db8dac20SDavid S. Miller 	if (connected)
1216db8dac20SDavid S. Miller 		rt = (struct rtable *)sk_dst_check(sk, 0);
1217db8dac20SDavid S. Miller 
121851456b29SIan Morris 	if (!rt) {
121984a3aa00SPavel Emelyanov 		struct net *net = sock_net(sk);
12209a24abfaSDavid Ahern 		__u8 flow_flags = inet_sk_flowi_flags(sk);
122184a3aa00SPavel Emelyanov 
1222e474995fSDavid S. Miller 		fl4 = &fl4_stack;
12239a24abfaSDavid Ahern 
1224c6af0c22SWillem de Bruijn 		flowi4_init_output(fl4, ipc.oif, ipc.sockc.mark, tos,
12259a24abfaSDavid Ahern 				   RT_SCOPE_UNIVERSE, sk->sk_protocol,
12269a24abfaSDavid Ahern 				   flow_flags,
1227e2d118a1SLorenzo Colitti 				   faddr, saddr, dport, inet->inet_sport,
1228e2d118a1SLorenzo Colitti 				   sk->sk_uid);
1229c0951cbcSDavid S. Miller 
12303df98d79SPaul Moore 		security_sk_classify_flow(sk, flowi4_to_flowi_common(fl4));
1231e474995fSDavid S. Miller 		rt = ip_route_output_flow(net, fl4, sk);
1232b23dd4feSDavid S. Miller 		if (IS_ERR(rt)) {
1233b23dd4feSDavid S. Miller 			err = PTR_ERR(rt);
123406dc94b1SDavid S. Miller 			rt = NULL;
1235db8dac20SDavid S. Miller 			if (err == -ENETUNREACH)
1236f1d8cba6SEric Dumazet 				IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
1237db8dac20SDavid S. Miller 			goto out;
1238db8dac20SDavid S. Miller 		}
1239db8dac20SDavid S. Miller 
1240db8dac20SDavid S. Miller 		err = -EACCES;
1241db8dac20SDavid S. Miller 		if ((rt->rt_flags & RTCF_BROADCAST) &&
1242db8dac20SDavid S. Miller 		    !sock_flag(sk, SOCK_BROADCAST))
1243db8dac20SDavid S. Miller 			goto out;
1244db8dac20SDavid S. Miller 		if (connected)
1245d8d1f30bSChangli Gao 			sk_dst_set(sk, dst_clone(&rt->dst));
1246db8dac20SDavid S. Miller 	}
1247db8dac20SDavid S. Miller 
1248db8dac20SDavid S. Miller 	if (msg->msg_flags&MSG_CONFIRM)
1249db8dac20SDavid S. Miller 		goto do_confirm;
1250db8dac20SDavid S. Miller back_from_confirm:
1251db8dac20SDavid S. Miller 
1252e474995fSDavid S. Miller 	saddr = fl4->saddr;
1253db8dac20SDavid S. Miller 	if (!ipc.addr)
1254e474995fSDavid S. Miller 		daddr = ipc.addr = fl4->daddr;
1255db8dac20SDavid S. Miller 
1256903ab86dSHerbert Xu 	/* Lockless fast path for the non-corking case. */
1257903ab86dSHerbert Xu 	if (!corkreq) {
12581cd7884dSWillem de Bruijn 		struct inet_cork cork;
12591cd7884dSWillem de Bruijn 
1260f69e6d13SAl Viro 		skb = ip_make_skb(sk, fl4, getfrag, msg, ulen,
1261903ab86dSHerbert Xu 				  sizeof(struct udphdr), &ipc, &rt,
12621cd7884dSWillem de Bruijn 				  &cork, msg->msg_flags);
1263903ab86dSHerbert Xu 		err = PTR_ERR(skb);
126450c3a487SYOSHIFUJI Hideaki / 吉藤英明 		if (!IS_ERR_OR_NULL(skb))
1265bec1f6f6SWillem de Bruijn 			err = udp_send_skb(skb, fl4, &cork);
1266903ab86dSHerbert Xu 		goto out;
1267903ab86dSHerbert Xu 	}
1268903ab86dSHerbert Xu 
1269db8dac20SDavid S. Miller 	lock_sock(sk);
1270db8dac20SDavid S. Miller 	if (unlikely(up->pending)) {
1271db8dac20SDavid S. Miller 		/* The socket is already corked while preparing it. */
1272db8dac20SDavid S. Miller 		/* ... which is an evident application bug. --ANK */
1273db8dac20SDavid S. Miller 		release_sock(sk);
1274db8dac20SDavid S. Miller 
1275197df02cSMatteo Croce 		net_dbg_ratelimited("socket already corked\n");
1276db8dac20SDavid S. Miller 		err = -EINVAL;
1277db8dac20SDavid S. Miller 		goto out;
1278db8dac20SDavid S. Miller 	}
1279db8dac20SDavid S. Miller 	/*
1280db8dac20SDavid S. Miller 	 *	Now cork the socket to pend data.
1281db8dac20SDavid S. Miller 	 */
1282b6f21b26SDavid S. Miller 	fl4 = &inet->cork.fl.u.ip4;
1283b6f21b26SDavid S. Miller 	fl4->daddr = daddr;
1284b6f21b26SDavid S. Miller 	fl4->saddr = saddr;
12859cce96dfSDavid S. Miller 	fl4->fl4_dport = dport;
12869cce96dfSDavid S. Miller 	fl4->fl4_sport = inet->inet_sport;
1287db8dac20SDavid S. Miller 	up->pending = AF_INET;
1288db8dac20SDavid S. Miller 
1289db8dac20SDavid S. Miller do_append_data:
1290db8dac20SDavid S. Miller 	up->len += ulen;
1291f69e6d13SAl Viro 	err = ip_append_data(sk, fl4, getfrag, msg, ulen,
12922e77d89bSEric Dumazet 			     sizeof(struct udphdr), &ipc, &rt,
1293db8dac20SDavid S. Miller 			     corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
1294db8dac20SDavid S. Miller 	if (err)
1295db8dac20SDavid S. Miller 		udp_flush_pending_frames(sk);
1296db8dac20SDavid S. Miller 	else if (!corkreq)
1297db8dac20SDavid S. Miller 		err = udp_push_pending_frames(sk);
1298db8dac20SDavid S. Miller 	else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
1299db8dac20SDavid S. Miller 		up->pending = 0;
1300db8dac20SDavid S. Miller 	release_sock(sk);
1301db8dac20SDavid S. Miller 
1302db8dac20SDavid S. Miller out:
1303db8dac20SDavid S. Miller 	ip_rt_put(rt);
13041b97013bSAndrey Ignatov out_free:
1305db8dac20SDavid S. Miller 	if (free)
1306db8dac20SDavid S. Miller 		kfree(ipc.opt);
1307db8dac20SDavid S. Miller 	if (!err)
1308db8dac20SDavid S. Miller 		return len;
1309db8dac20SDavid S. Miller 	/*
1310db8dac20SDavid S. Miller 	 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space.  Reporting
1311db8dac20SDavid S. Miller 	 * ENOBUFS might not be good (it's not tunable per se), but otherwise
1312db8dac20SDavid S. Miller 	 * we don't have a good statistic (IpOutDiscards but it can be too many
1313db8dac20SDavid S. Miller 	 * things).  We could add another new stat but at least for now that
1314db8dac20SDavid S. Miller 	 * seems like overkill.
1315db8dac20SDavid S. Miller 	 */
1316db8dac20SDavid S. Miller 	if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
13176aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
1318629ca23cSPavel Emelyanov 			      UDP_MIB_SNDBUFERRORS, is_udplite);
1319db8dac20SDavid S. Miller 	}
1320db8dac20SDavid S. Miller 	return err;
1321db8dac20SDavid S. Miller 
1322db8dac20SDavid S. Miller do_confirm:
13230dec879fSJulian Anastasov 	if (msg->msg_flags & MSG_PROBE)
13240dec879fSJulian Anastasov 		dst_confirm_neigh(&rt->dst, &fl4->daddr);
1325db8dac20SDavid S. Miller 	if (!(msg->msg_flags&MSG_PROBE) || len)
1326db8dac20SDavid S. Miller 		goto back_from_confirm;
1327db8dac20SDavid S. Miller 	err = 0;
1328db8dac20SDavid S. Miller 	goto out;
1329db8dac20SDavid S. Miller }
1330c482c568SEric Dumazet EXPORT_SYMBOL(udp_sendmsg);
1331db8dac20SDavid S. Miller 
1332db8dac20SDavid S. Miller int udp_sendpage(struct sock *sk, struct page *page, int offset,
1333db8dac20SDavid S. Miller 		 size_t size, int flags)
1334db8dac20SDavid S. Miller {
1335f5fca608SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1336db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
1337db8dac20SDavid S. Miller 	int ret;
1338db8dac20SDavid S. Miller 
1339d3f7d56aSShawn Landden 	if (flags & MSG_SENDPAGE_NOTLAST)
1340d3f7d56aSShawn Landden 		flags |= MSG_MORE;
1341d3f7d56aSShawn Landden 
1342db8dac20SDavid S. Miller 	if (!up->pending) {
1343db8dac20SDavid S. Miller 		struct msghdr msg = {	.msg_flags = flags|MSG_MORE };
1344db8dac20SDavid S. Miller 
1345db8dac20SDavid S. Miller 		/* Call udp_sendmsg to specify destination address which
1346db8dac20SDavid S. Miller 		 * sendpage interface can't pass.
1347db8dac20SDavid S. Miller 		 * This will succeed only when the socket is connected.
1348db8dac20SDavid S. Miller 		 */
13491b784140SYing Xue 		ret = udp_sendmsg(sk, &msg, 0);
1350db8dac20SDavid S. Miller 		if (ret < 0)
1351db8dac20SDavid S. Miller 			return ret;
1352db8dac20SDavid S. Miller 	}
1353db8dac20SDavid S. Miller 
1354db8dac20SDavid S. Miller 	lock_sock(sk);
1355db8dac20SDavid S. Miller 
1356db8dac20SDavid S. Miller 	if (unlikely(!up->pending)) {
1357db8dac20SDavid S. Miller 		release_sock(sk);
1358db8dac20SDavid S. Miller 
1359197df02cSMatteo Croce 		net_dbg_ratelimited("cork failed\n");
1360db8dac20SDavid S. Miller 		return -EINVAL;
1361db8dac20SDavid S. Miller 	}
1362db8dac20SDavid S. Miller 
1363f5fca608SDavid S. Miller 	ret = ip_append_page(sk, &inet->cork.fl.u.ip4,
1364f5fca608SDavid S. Miller 			     page, offset, size, flags);
1365db8dac20SDavid S. Miller 	if (ret == -EOPNOTSUPP) {
1366db8dac20SDavid S. Miller 		release_sock(sk);
1367db8dac20SDavid S. Miller 		return sock_no_sendpage(sk->sk_socket, page, offset,
1368db8dac20SDavid S. Miller 					size, flags);
1369db8dac20SDavid S. Miller 	}
1370db8dac20SDavid S. Miller 	if (ret < 0) {
1371db8dac20SDavid S. Miller 		udp_flush_pending_frames(sk);
1372db8dac20SDavid S. Miller 		goto out;
1373db8dac20SDavid S. Miller 	}
1374db8dac20SDavid S. Miller 
1375db8dac20SDavid S. Miller 	up->len += size;
1376a9f59707SEric Dumazet 	if (!(READ_ONCE(up->corkflag) || (flags&MSG_MORE)))
1377db8dac20SDavid S. Miller 		ret = udp_push_pending_frames(sk);
1378db8dac20SDavid S. Miller 	if (!ret)
1379db8dac20SDavid S. Miller 		ret = size;
1380db8dac20SDavid S. Miller out:
1381db8dac20SDavid S. Miller 	release_sock(sk);
1382db8dac20SDavid S. Miller 	return ret;
1383db8dac20SDavid S. Miller }
1384db8dac20SDavid S. Miller 
1385dce4551cSPaolo Abeni #define UDP_SKB_IS_STATELESS 0x80000000
1386dce4551cSPaolo Abeni 
1387677bf08cSFlorian Westphal /* all head states (dst, sk, nf conntrack) except skb extensions are
1388677bf08cSFlorian Westphal  * cleared by udp_rcv().
1389677bf08cSFlorian Westphal  *
1390677bf08cSFlorian Westphal  * We need to preserve secpath, if present, to eventually process
1391677bf08cSFlorian Westphal  * IP_CMSG_PASSSEC at recvmsg() time.
1392677bf08cSFlorian Westphal  *
1393677bf08cSFlorian Westphal  * Other extensions can be cleared.
1394677bf08cSFlorian Westphal  */
1395677bf08cSFlorian Westphal static bool udp_try_make_stateless(struct sk_buff *skb)
1396677bf08cSFlorian Westphal {
1397677bf08cSFlorian Westphal 	if (!skb_has_extensions(skb))
1398677bf08cSFlorian Westphal 		return true;
1399677bf08cSFlorian Westphal 
1400677bf08cSFlorian Westphal 	if (!secpath_exists(skb)) {
1401677bf08cSFlorian Westphal 		skb_ext_reset(skb);
1402677bf08cSFlorian Westphal 		return true;
1403677bf08cSFlorian Westphal 	}
1404677bf08cSFlorian Westphal 
1405677bf08cSFlorian Westphal 	return false;
1406677bf08cSFlorian Westphal }
1407677bf08cSFlorian Westphal 
1408b65ac446SPaolo Abeni static void udp_set_dev_scratch(struct sk_buff *skb)
1409b65ac446SPaolo Abeni {
1410dce4551cSPaolo Abeni 	struct udp_dev_scratch *scratch = udp_skb_scratch(skb);
1411b65ac446SPaolo Abeni 
1412b65ac446SPaolo Abeni 	BUILD_BUG_ON(sizeof(struct udp_dev_scratch) > sizeof(long));
1413dce4551cSPaolo Abeni 	scratch->_tsize_state = skb->truesize;
1414dce4551cSPaolo Abeni #if BITS_PER_LONG == 64
1415b65ac446SPaolo Abeni 	scratch->len = skb->len;
1416b65ac446SPaolo Abeni 	scratch->csum_unnecessary = !!skb_csum_unnecessary(skb);
1417b65ac446SPaolo Abeni 	scratch->is_linear = !skb_is_nonlinear(skb);
1418b65ac446SPaolo Abeni #endif
1419677bf08cSFlorian Westphal 	if (udp_try_make_stateless(skb))
1420dce4551cSPaolo Abeni 		scratch->_tsize_state |= UDP_SKB_IS_STATELESS;
1421dce4551cSPaolo Abeni }
1422dce4551cSPaolo Abeni 
1423a793183cSEric Dumazet static void udp_skb_csum_unnecessary_set(struct sk_buff *skb)
1424a793183cSEric Dumazet {
1425a793183cSEric Dumazet 	/* We come here after udp_lib_checksum_complete() returned 0.
1426a793183cSEric Dumazet 	 * This means that __skb_checksum_complete() might have
1427a793183cSEric Dumazet 	 * set skb->csum_valid to 1.
1428a793183cSEric Dumazet 	 * On 64bit platforms, we can set csum_unnecessary
1429a793183cSEric Dumazet 	 * to true, but only if the skb is not shared.
1430a793183cSEric Dumazet 	 */
1431a793183cSEric Dumazet #if BITS_PER_LONG == 64
1432a793183cSEric Dumazet 	if (!skb_shared(skb))
1433a793183cSEric Dumazet 		udp_skb_scratch(skb)->csum_unnecessary = true;
1434a793183cSEric Dumazet #endif
1435a793183cSEric Dumazet }
1436a793183cSEric Dumazet 
1437dce4551cSPaolo Abeni static int udp_skb_truesize(struct sk_buff *skb)
1438dce4551cSPaolo Abeni {
1439dce4551cSPaolo Abeni 	return udp_skb_scratch(skb)->_tsize_state & ~UDP_SKB_IS_STATELESS;
1440dce4551cSPaolo Abeni }
1441dce4551cSPaolo Abeni 
1442dce4551cSPaolo Abeni static bool udp_skb_has_head_state(struct sk_buff *skb)
1443dce4551cSPaolo Abeni {
1444dce4551cSPaolo Abeni 	return !(udp_skb_scratch(skb)->_tsize_state & UDP_SKB_IS_STATELESS);
1445dce4551cSPaolo Abeni }
1446b65ac446SPaolo Abeni 
14477c13f97fSPaolo Abeni /* fully reclaim rmem/fwd memory allocated for skb */
14486dfb4367SPaolo Abeni static void udp_rmem_release(struct sock *sk, int size, int partial,
14496dfb4367SPaolo Abeni 			     bool rx_queue_lock_held)
1450f970bd9eSPaolo Abeni {
14516b229cf7SEric Dumazet 	struct udp_sock *up = udp_sk(sk);
14522276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue;
1453f970bd9eSPaolo Abeni 	int amt;
1454f970bd9eSPaolo Abeni 
14556b229cf7SEric Dumazet 	if (likely(partial)) {
14566b229cf7SEric Dumazet 		up->forward_deficit += size;
14576b229cf7SEric Dumazet 		size = up->forward_deficit;
14588a3854c7SPaolo Abeni 		if (size < READ_ONCE(up->forward_threshold) &&
1459d39ca259SPaolo Abeni 		    !skb_queue_empty(&up->reader_queue))
14606b229cf7SEric Dumazet 			return;
14616b229cf7SEric Dumazet 	} else {
14626b229cf7SEric Dumazet 		size += up->forward_deficit;
14636b229cf7SEric Dumazet 	}
14646b229cf7SEric Dumazet 	up->forward_deficit = 0;
14656b229cf7SEric Dumazet 
14666dfb4367SPaolo Abeni 	/* acquire the sk_receive_queue for fwd allocated memory scheduling,
14676dfb4367SPaolo Abeni 	 * if the called don't held it already
14686dfb4367SPaolo Abeni 	 */
14692276f58aSPaolo Abeni 	sk_queue = &sk->sk_receive_queue;
14706dfb4367SPaolo Abeni 	if (!rx_queue_lock_held)
14712276f58aSPaolo Abeni 		spin_lock(&sk_queue->lock);
14722276f58aSPaolo Abeni 
14736dfb4367SPaolo Abeni 
1474f970bd9eSPaolo Abeni 	sk->sk_forward_alloc += size;
1475100fdd1fSEric Dumazet 	amt = (sk->sk_forward_alloc - partial) & ~(PAGE_SIZE - 1);
1476f970bd9eSPaolo Abeni 	sk->sk_forward_alloc -= amt;
1477f970bd9eSPaolo Abeni 
1478f970bd9eSPaolo Abeni 	if (amt)
1479100fdd1fSEric Dumazet 		__sk_mem_reduce_allocated(sk, amt >> PAGE_SHIFT);
148002ab0d13SEric Dumazet 
148102ab0d13SEric Dumazet 	atomic_sub(size, &sk->sk_rmem_alloc);
14822276f58aSPaolo Abeni 
14832276f58aSPaolo Abeni 	/* this can save us from acquiring the rx queue lock on next receive */
14842276f58aSPaolo Abeni 	skb_queue_splice_tail_init(sk_queue, &up->reader_queue);
14852276f58aSPaolo Abeni 
14866dfb4367SPaolo Abeni 	if (!rx_queue_lock_held)
14872276f58aSPaolo Abeni 		spin_unlock(&sk_queue->lock);
1488f970bd9eSPaolo Abeni }
1489f970bd9eSPaolo Abeni 
14902276f58aSPaolo Abeni /* Note: called with reader_queue.lock held.
1491c84d9490SEric Dumazet  * Instead of using skb->truesize here, find a copy of it in skb->dev_scratch
1492c84d9490SEric Dumazet  * This avoids a cache line miss while receive_queue lock is held.
1493c84d9490SEric Dumazet  * Look at __udp_enqueue_schedule_skb() to find where this copy is done.
1494c84d9490SEric Dumazet  */
14957c13f97fSPaolo Abeni void udp_skb_destructor(struct sock *sk, struct sk_buff *skb)
1496f970bd9eSPaolo Abeni {
1497b65ac446SPaolo Abeni 	prefetch(&skb->data);
1498b65ac446SPaolo Abeni 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, false);
1499f970bd9eSPaolo Abeni }
15007c13f97fSPaolo Abeni EXPORT_SYMBOL(udp_skb_destructor);
1501f970bd9eSPaolo Abeni 
15026dfb4367SPaolo Abeni /* as above, but the caller held the rx queue lock, too */
150364f5102dSColin Ian King static void udp_skb_dtor_locked(struct sock *sk, struct sk_buff *skb)
15046dfb4367SPaolo Abeni {
1505b65ac446SPaolo Abeni 	prefetch(&skb->data);
1506b65ac446SPaolo Abeni 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, true);
15076dfb4367SPaolo Abeni }
15086dfb4367SPaolo Abeni 
15094b272750SEric Dumazet /* Idea of busylocks is to let producers grab an extra spinlock
15104b272750SEric Dumazet  * to relieve pressure on the receive_queue spinlock shared by consumer.
15114b272750SEric Dumazet  * Under flood, this means that only one producer can be in line
15124b272750SEric Dumazet  * trying to acquire the receive_queue spinlock.
15134b272750SEric Dumazet  * These busylock can be allocated on a per cpu manner, instead of a
15144b272750SEric Dumazet  * per socket one (that would consume a cache line per socket)
15154b272750SEric Dumazet  */
15164b272750SEric Dumazet static int udp_busylocks_log __read_mostly;
15174b272750SEric Dumazet static spinlock_t *udp_busylocks __read_mostly;
15184b272750SEric Dumazet 
15194b272750SEric Dumazet static spinlock_t *busylock_acquire(void *ptr)
15204b272750SEric Dumazet {
15214b272750SEric Dumazet 	spinlock_t *busy;
15224b272750SEric Dumazet 
15234b272750SEric Dumazet 	busy = udp_busylocks + hash_ptr(ptr, udp_busylocks_log);
15244b272750SEric Dumazet 	spin_lock(busy);
15254b272750SEric Dumazet 	return busy;
15264b272750SEric Dumazet }
15274b272750SEric Dumazet 
15284b272750SEric Dumazet static void busylock_release(spinlock_t *busy)
15294b272750SEric Dumazet {
15304b272750SEric Dumazet 	if (busy)
15314b272750SEric Dumazet 		spin_unlock(busy);
15324b272750SEric Dumazet }
15334b272750SEric Dumazet 
1534*fd9c31f8SJason Xing static int udp_rmem_schedule(struct sock *sk, int size)
1535*fd9c31f8SJason Xing {
1536*fd9c31f8SJason Xing 	int delta;
1537*fd9c31f8SJason Xing 
1538*fd9c31f8SJason Xing 	delta = size - sk->sk_forward_alloc;
1539*fd9c31f8SJason Xing 	if (delta > 0 && !__sk_mem_schedule(sk, delta, SK_MEM_RECV))
1540*fd9c31f8SJason Xing 		return -ENOBUFS;
1541*fd9c31f8SJason Xing 
1542*fd9c31f8SJason Xing 	return 0;
1543*fd9c31f8SJason Xing }
1544*fd9c31f8SJason Xing 
1545f970bd9eSPaolo Abeni int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb)
1546f970bd9eSPaolo Abeni {
1547f970bd9eSPaolo Abeni 	struct sk_buff_head *list = &sk->sk_receive_queue;
1548*fd9c31f8SJason Xing 	int rmem, err = -ENOMEM;
15494b272750SEric Dumazet 	spinlock_t *busy = NULL;
1550c8c8b127SEric Dumazet 	int size;
1551f970bd9eSPaolo Abeni 
1552f970bd9eSPaolo Abeni 	/* try to avoid the costly atomic add/sub pair when the receive
1553f970bd9eSPaolo Abeni 	 * queue is full; always allow at least a packet
1554f970bd9eSPaolo Abeni 	 */
1555f970bd9eSPaolo Abeni 	rmem = atomic_read(&sk->sk_rmem_alloc);
1556363dc73aSPaolo Abeni 	if (rmem > sk->sk_rcvbuf)
1557f970bd9eSPaolo Abeni 		goto drop;
1558f970bd9eSPaolo Abeni 
1559c8c8b127SEric Dumazet 	/* Under mem pressure, it might be helpful to help udp_recvmsg()
1560c8c8b127SEric Dumazet 	 * having linear skbs :
1561c8c8b127SEric Dumazet 	 * - Reduce memory overhead and thus increase receive queue capacity
1562c8c8b127SEric Dumazet 	 * - Less cache line misses at copyout() time
1563c8c8b127SEric Dumazet 	 * - Less work at consume_skb() (less alien page frag freeing)
1564c8c8b127SEric Dumazet 	 */
15654b272750SEric Dumazet 	if (rmem > (sk->sk_rcvbuf >> 1)) {
1566c8c8b127SEric Dumazet 		skb_condense(skb);
15674b272750SEric Dumazet 
15684b272750SEric Dumazet 		busy = busylock_acquire(sk);
15694b272750SEric Dumazet 	}
1570c8c8b127SEric Dumazet 	size = skb->truesize;
1571b65ac446SPaolo Abeni 	udp_set_dev_scratch(skb);
1572c8c8b127SEric Dumazet 
1573f970bd9eSPaolo Abeni 	/* we drop only if the receive buf is full and the receive
1574f970bd9eSPaolo Abeni 	 * queue contains some other skb
1575f970bd9eSPaolo Abeni 	 */
1576f970bd9eSPaolo Abeni 	rmem = atomic_add_return(size, &sk->sk_rmem_alloc);
1577feed8a4fSAntonio Messina 	if (rmem > (size + (unsigned int)sk->sk_rcvbuf))
1578f970bd9eSPaolo Abeni 		goto uncharge_drop;
1579f970bd9eSPaolo Abeni 
1580f970bd9eSPaolo Abeni 	spin_lock(&list->lock);
1581*fd9c31f8SJason Xing 	err = udp_rmem_schedule(sk, size);
1582*fd9c31f8SJason Xing 	if (err) {
1583f970bd9eSPaolo Abeni 		spin_unlock(&list->lock);
1584f970bd9eSPaolo Abeni 		goto uncharge_drop;
1585f970bd9eSPaolo Abeni 	}
1586f970bd9eSPaolo Abeni 
1587f970bd9eSPaolo Abeni 	sk->sk_forward_alloc -= size;
1588f970bd9eSPaolo Abeni 
15897c13f97fSPaolo Abeni 	/* no need to setup a destructor, we will explicitly release the
15907c13f97fSPaolo Abeni 	 * forward allocated memory on dequeue
15917c13f97fSPaolo Abeni 	 */
1592f970bd9eSPaolo Abeni 	sock_skb_set_dropcount(sk, skb);
1593f970bd9eSPaolo Abeni 
1594f970bd9eSPaolo Abeni 	__skb_queue_tail(list, skb);
1595f970bd9eSPaolo Abeni 	spin_unlock(&list->lock);
1596f970bd9eSPaolo Abeni 
1597f970bd9eSPaolo Abeni 	if (!sock_flag(sk, SOCK_DEAD))
1598f970bd9eSPaolo Abeni 		sk->sk_data_ready(sk);
1599f970bd9eSPaolo Abeni 
16004b272750SEric Dumazet 	busylock_release(busy);
1601f970bd9eSPaolo Abeni 	return 0;
1602f970bd9eSPaolo Abeni 
1603f970bd9eSPaolo Abeni uncharge_drop:
1604f970bd9eSPaolo Abeni 	atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
1605f970bd9eSPaolo Abeni 
1606f970bd9eSPaolo Abeni drop:
1607f970bd9eSPaolo Abeni 	atomic_inc(&sk->sk_drops);
16084b272750SEric Dumazet 	busylock_release(busy);
1609f970bd9eSPaolo Abeni 	return err;
1610f970bd9eSPaolo Abeni }
1611f970bd9eSPaolo Abeni EXPORT_SYMBOL_GPL(__udp_enqueue_schedule_skb);
1612f970bd9eSPaolo Abeni 
1613d38afeecSKuniyuki Iwashima void udp_destruct_common(struct sock *sk)
1614f970bd9eSPaolo Abeni {
1615f970bd9eSPaolo Abeni 	/* reclaim completely the forward allocated memory */
16162276f58aSPaolo Abeni 	struct udp_sock *up = udp_sk(sk);
16177c13f97fSPaolo Abeni 	unsigned int total = 0;
16187c13f97fSPaolo Abeni 	struct sk_buff *skb;
16197c13f97fSPaolo Abeni 
16202276f58aSPaolo Abeni 	skb_queue_splice_tail_init(&sk->sk_receive_queue, &up->reader_queue);
16212276f58aSPaolo Abeni 	while ((skb = __skb_dequeue(&up->reader_queue)) != NULL) {
16227c13f97fSPaolo Abeni 		total += skb->truesize;
16237c13f97fSPaolo Abeni 		kfree_skb(skb);
16247c13f97fSPaolo Abeni 	}
16256dfb4367SPaolo Abeni 	udp_rmem_release(sk, total, 0, true);
1626d38afeecSKuniyuki Iwashima }
1627d38afeecSKuniyuki Iwashima EXPORT_SYMBOL_GPL(udp_destruct_common);
16287c13f97fSPaolo Abeni 
1629d38afeecSKuniyuki Iwashima static void udp_destruct_sock(struct sock *sk)
1630d38afeecSKuniyuki Iwashima {
1631d38afeecSKuniyuki Iwashima 	udp_destruct_common(sk);
1632f970bd9eSPaolo Abeni 	inet_sock_destruct(sk);
1633f970bd9eSPaolo Abeni }
1634f970bd9eSPaolo Abeni 
1635f970bd9eSPaolo Abeni int udp_init_sock(struct sock *sk)
1636f970bd9eSPaolo Abeni {
16378a3854c7SPaolo Abeni 	udp_lib_init_sock(sk);
1638f970bd9eSPaolo Abeni 	sk->sk_destruct = udp_destruct_sock;
1639e993ffe3SPavel Begunkov 	set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
1640f970bd9eSPaolo Abeni 	return 0;
1641f970bd9eSPaolo Abeni }
1642f970bd9eSPaolo Abeni 
1643f970bd9eSPaolo Abeni void skb_consume_udp(struct sock *sk, struct sk_buff *skb, int len)
1644f970bd9eSPaolo Abeni {
1645f970bd9eSPaolo Abeni 	if (unlikely(READ_ONCE(sk->sk_peek_off) >= 0)) {
1646f970bd9eSPaolo Abeni 		bool slow = lock_sock_fast(sk);
1647f970bd9eSPaolo Abeni 
1648f970bd9eSPaolo Abeni 		sk_peek_offset_bwd(sk, len);
1649f970bd9eSPaolo Abeni 		unlock_sock_fast(sk, slow);
1650f970bd9eSPaolo Abeni 	}
16510a463c78SPaolo Abeni 
1652ca2c1418SPaolo Abeni 	if (!skb_unref(skb))
1653ca2c1418SPaolo Abeni 		return;
1654ca2c1418SPaolo Abeni 
1655dce4551cSPaolo Abeni 	/* In the more common cases we cleared the head states previously,
1656dce4551cSPaolo Abeni 	 * see __udp_queue_rcv_skb().
16570ddf3fb2SPaolo Abeni 	 */
1658dce4551cSPaolo Abeni 	if (unlikely(udp_skb_has_head_state(skb)))
16590ddf3fb2SPaolo Abeni 		skb_release_head_state(skb);
1660ca2c1418SPaolo Abeni 	__consume_stateless_skb(skb);
1661f970bd9eSPaolo Abeni }
1662f970bd9eSPaolo Abeni EXPORT_SYMBOL_GPL(skb_consume_udp);
1663f970bd9eSPaolo Abeni 
16642276f58aSPaolo Abeni static struct sk_buff *__first_packet_length(struct sock *sk,
16652276f58aSPaolo Abeni 					     struct sk_buff_head *rcvq,
16662276f58aSPaolo Abeni 					     int *total)
16672276f58aSPaolo Abeni {
16682276f58aSPaolo Abeni 	struct sk_buff *skb;
16692276f58aSPaolo Abeni 
16709bd780f5SPaolo Abeni 	while ((skb = skb_peek(rcvq)) != NULL) {
16719bd780f5SPaolo Abeni 		if (udp_lib_checksum_complete(skb)) {
16722276f58aSPaolo Abeni 			__UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS,
16732276f58aSPaolo Abeni 					IS_UDPLITE(sk));
16742276f58aSPaolo Abeni 			__UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS,
16752276f58aSPaolo Abeni 					IS_UDPLITE(sk));
16762276f58aSPaolo Abeni 			atomic_inc(&sk->sk_drops);
16772276f58aSPaolo Abeni 			__skb_unlink(skb, rcvq);
16782276f58aSPaolo Abeni 			*total += skb->truesize;
16792276f58aSPaolo Abeni 			kfree_skb(skb);
16809bd780f5SPaolo Abeni 		} else {
1681a793183cSEric Dumazet 			udp_skb_csum_unnecessary_set(skb);
16829bd780f5SPaolo Abeni 			break;
16839bd780f5SPaolo Abeni 		}
16842276f58aSPaolo Abeni 	}
16852276f58aSPaolo Abeni 	return skb;
16862276f58aSPaolo Abeni }
16872276f58aSPaolo Abeni 
168885584672SEric Dumazet /**
168985584672SEric Dumazet  *	first_packet_length	- return length of first packet in receive queue
169085584672SEric Dumazet  *	@sk: socket
169185584672SEric Dumazet  *
169285584672SEric Dumazet  *	Drops all bad checksum frames, until a valid one is found.
1693e83c6744SEric Dumazet  *	Returns the length of found skb, or -1 if none is found.
169485584672SEric Dumazet  */
1695e83c6744SEric Dumazet static int first_packet_length(struct sock *sk)
169685584672SEric Dumazet {
16972276f58aSPaolo Abeni 	struct sk_buff_head *rcvq = &udp_sk(sk)->reader_queue;
16982276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
169985584672SEric Dumazet 	struct sk_buff *skb;
17007c13f97fSPaolo Abeni 	int total = 0;
1701e83c6744SEric Dumazet 	int res;
170285584672SEric Dumazet 
170385584672SEric Dumazet 	spin_lock_bh(&rcvq->lock);
17042276f58aSPaolo Abeni 	skb = __first_packet_length(sk, rcvq, &total);
1705137a0dbeSEric Dumazet 	if (!skb && !skb_queue_empty_lockless(sk_queue)) {
17062276f58aSPaolo Abeni 		spin_lock(&sk_queue->lock);
17072276f58aSPaolo Abeni 		skb_queue_splice_tail_init(sk_queue, rcvq);
17082276f58aSPaolo Abeni 		spin_unlock(&sk_queue->lock);
17092276f58aSPaolo Abeni 
17102276f58aSPaolo Abeni 		skb = __first_packet_length(sk, rcvq, &total);
171185584672SEric Dumazet 	}
1712e83c6744SEric Dumazet 	res = skb ? skb->len : -1;
17137c13f97fSPaolo Abeni 	if (total)
17146dfb4367SPaolo Abeni 		udp_rmem_release(sk, total, 1, false);
171585584672SEric Dumazet 	spin_unlock_bh(&rcvq->lock);
171685584672SEric Dumazet 	return res;
171785584672SEric Dumazet }
171885584672SEric Dumazet 
17191da177e4SLinus Torvalds /*
17201da177e4SLinus Torvalds  *	IOCTL requests applicable to the UDP protocol
17211da177e4SLinus Torvalds  */
17221da177e4SLinus Torvalds 
17231da177e4SLinus Torvalds int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
17241da177e4SLinus Torvalds {
17256516c655SStephen Hemminger 	switch (cmd) {
17261da177e4SLinus Torvalds 	case SIOCOUTQ:
17271da177e4SLinus Torvalds 	{
172831e6d363SEric Dumazet 		int amount = sk_wmem_alloc_get(sk);
172931e6d363SEric Dumazet 
17301da177e4SLinus Torvalds 		return put_user(amount, (int __user *)arg);
17311da177e4SLinus Torvalds 	}
17321da177e4SLinus Torvalds 
17331da177e4SLinus Torvalds 	case SIOCINQ:
17341da177e4SLinus Torvalds 	{
1735e83c6744SEric Dumazet 		int amount = max_t(int, 0, first_packet_length(sk));
17361da177e4SLinus Torvalds 
17371da177e4SLinus Torvalds 		return put_user(amount, (int __user *)arg);
17381da177e4SLinus Torvalds 	}
17391da177e4SLinus Torvalds 
17401da177e4SLinus Torvalds 	default:
17411da177e4SLinus Torvalds 		return -ENOIOCTLCMD;
17421da177e4SLinus Torvalds 	}
17436516c655SStephen Hemminger 
17446516c655SStephen Hemminger 	return 0;
17451da177e4SLinus Torvalds }
1746c482c568SEric Dumazet EXPORT_SYMBOL(udp_ioctl);
17471da177e4SLinus Torvalds 
17482276f58aSPaolo Abeni struct sk_buff *__skb_recv_udp(struct sock *sk, unsigned int flags,
1749ec095263SOliver Hartkopp 			       int *off, int *err)
17502276f58aSPaolo Abeni {
17512276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
17522276f58aSPaolo Abeni 	struct sk_buff_head *queue;
17532276f58aSPaolo Abeni 	struct sk_buff *last;
17542276f58aSPaolo Abeni 	long timeo;
17552276f58aSPaolo Abeni 	int error;
17562276f58aSPaolo Abeni 
17572276f58aSPaolo Abeni 	queue = &udp_sk(sk)->reader_queue;
17582276f58aSPaolo Abeni 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
17592276f58aSPaolo Abeni 	do {
17602276f58aSPaolo Abeni 		struct sk_buff *skb;
17612276f58aSPaolo Abeni 
17622276f58aSPaolo Abeni 		error = sock_error(sk);
17632276f58aSPaolo Abeni 		if (error)
17642276f58aSPaolo Abeni 			break;
17652276f58aSPaolo Abeni 
17662276f58aSPaolo Abeni 		error = -EAGAIN;
17672276f58aSPaolo Abeni 		do {
17682276f58aSPaolo Abeni 			spin_lock_bh(&queue->lock);
1769e427cad6SPaolo Abeni 			skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1770e427cad6SPaolo Abeni 							err, &last);
17712276f58aSPaolo Abeni 			if (skb) {
1772e427cad6SPaolo Abeni 				if (!(flags & MSG_PEEK))
1773e427cad6SPaolo Abeni 					udp_skb_destructor(sk, skb);
17742276f58aSPaolo Abeni 				spin_unlock_bh(&queue->lock);
17752276f58aSPaolo Abeni 				return skb;
17762276f58aSPaolo Abeni 			}
17772276f58aSPaolo Abeni 
1778137a0dbeSEric Dumazet 			if (skb_queue_empty_lockless(sk_queue)) {
17792276f58aSPaolo Abeni 				spin_unlock_bh(&queue->lock);
17802276f58aSPaolo Abeni 				goto busy_check;
17812276f58aSPaolo Abeni 			}
17822276f58aSPaolo Abeni 
17836dfb4367SPaolo Abeni 			/* refill the reader queue and walk it again
17846dfb4367SPaolo Abeni 			 * keep both queues locked to avoid re-acquiring
17856dfb4367SPaolo Abeni 			 * the sk_receive_queue lock if fwd memory scheduling
17866dfb4367SPaolo Abeni 			 * is needed.
17876dfb4367SPaolo Abeni 			 */
17882276f58aSPaolo Abeni 			spin_lock(&sk_queue->lock);
17892276f58aSPaolo Abeni 			skb_queue_splice_tail_init(sk_queue, queue);
17902276f58aSPaolo Abeni 
1791e427cad6SPaolo Abeni 			skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1792e427cad6SPaolo Abeni 							err, &last);
1793e427cad6SPaolo Abeni 			if (skb && !(flags & MSG_PEEK))
1794e427cad6SPaolo Abeni 				udp_skb_dtor_locked(sk, skb);
17956dfb4367SPaolo Abeni 			spin_unlock(&sk_queue->lock);
17962276f58aSPaolo Abeni 			spin_unlock_bh(&queue->lock);
1797de321ed3SAndrey Vagin 			if (skb)
17982276f58aSPaolo Abeni 				return skb;
17992276f58aSPaolo Abeni 
18002276f58aSPaolo Abeni busy_check:
18012276f58aSPaolo Abeni 			if (!sk_can_busy_loop(sk))
18022276f58aSPaolo Abeni 				break;
18032276f58aSPaolo Abeni 
18042276f58aSPaolo Abeni 			sk_busy_loop(sk, flags & MSG_DONTWAIT);
1805137a0dbeSEric Dumazet 		} while (!skb_queue_empty_lockless(sk_queue));
18062276f58aSPaolo Abeni 
18072276f58aSPaolo Abeni 		/* sk_queue is empty, reader_queue may contain peeked packets */
18082276f58aSPaolo Abeni 	} while (timeo &&
1809b50b0580SSabrina Dubroca 		 !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,
1810b50b0580SSabrina Dubroca 					      &error, &timeo,
18112276f58aSPaolo Abeni 					      (struct sk_buff *)sk_queue));
18122276f58aSPaolo Abeni 
18132276f58aSPaolo Abeni 	*err = error;
18142276f58aSPaolo Abeni 	return NULL;
18152276f58aSPaolo Abeni }
18167e823644SJiri Kosina EXPORT_SYMBOL(__skb_recv_udp);
18172276f58aSPaolo Abeni 
1818965b57b4SCong Wang int udp_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
1819d7f57118SCong Wang {
1820d7f57118SCong Wang 	struct sk_buff *skb;
182131f1fbcbSPeilin Ye 	int err, copied;
1822d7f57118SCong Wang 
182331f1fbcbSPeilin Ye try_again:
1824ec095263SOliver Hartkopp 	skb = skb_recv_udp(sk, MSG_DONTWAIT, &err);
1825d7f57118SCong Wang 	if (!skb)
1826d7f57118SCong Wang 		return err;
1827099f896fSCong Wang 
1828099f896fSCong Wang 	if (udp_lib_checksum_complete(skb)) {
182931f1fbcbSPeilin Ye 		int is_udplite = IS_UDPLITE(sk);
183031f1fbcbSPeilin Ye 		struct net *net = sock_net(sk);
183131f1fbcbSPeilin Ye 
183231f1fbcbSPeilin Ye 		__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, is_udplite);
183331f1fbcbSPeilin Ye 		__UDP_INC_STATS(net, UDP_MIB_INERRORS, is_udplite);
1834099f896fSCong Wang 		atomic_inc(&sk->sk_drops);
1835099f896fSCong Wang 		kfree_skb(skb);
183631f1fbcbSPeilin Ye 		goto try_again;
1837099f896fSCong Wang 	}
1838099f896fSCong Wang 
1839db39dfdcSPeilin Ye 	WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk));
184031f1fbcbSPeilin Ye 	copied = recv_actor(sk, skb);
1841e00a5c33SCong Wang 	kfree_skb(skb);
1842d7f57118SCong Wang 
1843d7f57118SCong Wang 	return copied;
1844d7f57118SCong Wang }
1845965b57b4SCong Wang EXPORT_SYMBOL(udp_read_skb);
1846d7f57118SCong Wang 
1847db8dac20SDavid S. Miller /*
1848db8dac20SDavid S. Miller  * 	This should be easy, if there is something there we
1849db8dac20SDavid S. Miller  * 	return it, otherwise we block.
1850db8dac20SDavid S. Miller  */
1851db8dac20SDavid S. Miller 
1852ec095263SOliver Hartkopp int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags,
1853ec095263SOliver Hartkopp 		int *addr_len)
1854db8dac20SDavid S. Miller {
1855db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1856342dfc30SSteffen Hurrle 	DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
1857db8dac20SDavid S. Miller 	struct sk_buff *skb;
185859c2cdaeSDavid S. Miller 	unsigned int ulen, copied;
1859fd69c399SPaolo Abeni 	int off, err, peeking = flags & MSG_PEEK;
1860db8dac20SDavid S. Miller 	int is_udplite = IS_UDPLITE(sk);
1861197c949eSEric Dumazet 	bool checksum_valid = false;
1862db8dac20SDavid S. Miller 
1863db8dac20SDavid S. Miller 	if (flags & MSG_ERRQUEUE)
186485fbaa75SHannes Frederic Sowa 		return ip_recv_error(sk, msg, len, addr_len);
1865db8dac20SDavid S. Miller 
1866db8dac20SDavid S. Miller try_again:
1867a0917e0bSMatthew Dawson 	off = sk_peek_offset(sk, flags);
1868ec095263SOliver Hartkopp 	skb = __skb_recv_udp(sk, flags, &off, &err);
1869db8dac20SDavid S. Miller 	if (!skb)
1870627d2d6bSsamanthakumar 		return err;
1871db8dac20SDavid S. Miller 
1872b65ac446SPaolo Abeni 	ulen = udp_skb_len(skb);
187359c2cdaeSDavid S. Miller 	copied = len;
1874627d2d6bSsamanthakumar 	if (copied > ulen - off)
1875627d2d6bSsamanthakumar 		copied = ulen - off;
187659c2cdaeSDavid S. Miller 	else if (copied < ulen)
1877db8dac20SDavid S. Miller 		msg->msg_flags |= MSG_TRUNC;
1878db8dac20SDavid S. Miller 
1879db8dac20SDavid S. Miller 	/*
1880db8dac20SDavid S. Miller 	 * If checksum is needed at all, try to do it while copying the
1881db8dac20SDavid S. Miller 	 * data.  If the data is truncated, or if we only want a partial
1882db8dac20SDavid S. Miller 	 * coverage checksum (UDP-Lite), do it before the copy.
1883db8dac20SDavid S. Miller 	 */
1884db8dac20SDavid S. Miller 
1885d21dbdfeSEric Dumazet 	if (copied < ulen || peeking ||
1886d21dbdfeSEric Dumazet 	    (is_udplite && UDP_SKB_CB(skb)->partial_cov)) {
1887b65ac446SPaolo Abeni 		checksum_valid = udp_skb_csum_unnecessary(skb) ||
1888b65ac446SPaolo Abeni 				!__udp_lib_checksum_complete(skb);
1889197c949eSEric Dumazet 		if (!checksum_valid)
1890db8dac20SDavid S. Miller 			goto csum_copy_err;
1891db8dac20SDavid S. Miller 	}
1892db8dac20SDavid S. Miller 
1893b65ac446SPaolo Abeni 	if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
1894b65ac446SPaolo Abeni 		if (udp_skb_is_linear(skb))
1895b65ac446SPaolo Abeni 			err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
1896b65ac446SPaolo Abeni 		else
1897627d2d6bSsamanthakumar 			err = skb_copy_datagram_msg(skb, off, msg, copied);
1898b65ac446SPaolo Abeni 	} else {
1899627d2d6bSsamanthakumar 		err = skb_copy_and_csum_datagram_msg(skb, off, msg);
1900db8dac20SDavid S. Miller 
1901db8dac20SDavid S. Miller 		if (err == -EINVAL)
1902db8dac20SDavid S. Miller 			goto csum_copy_err;
1903db8dac20SDavid S. Miller 	}
1904db8dac20SDavid S. Miller 
190522911fc5SEric Dumazet 	if (unlikely(err)) {
1906fd69c399SPaolo Abeni 		if (!peeking) {
1907979402b1SEric Dumazet 			atomic_inc(&sk->sk_drops);
19086aef70a8SEric Dumazet 			UDP_INC_STATS(sock_net(sk),
1909979402b1SEric Dumazet 				      UDP_MIB_INERRORS, is_udplite);
1910979402b1SEric Dumazet 		}
1911850cbaddSPaolo Abeni 		kfree_skb(skb);
1912627d2d6bSsamanthakumar 		return err;
191322911fc5SEric Dumazet 	}
1914db8dac20SDavid S. Miller 
1915fd69c399SPaolo Abeni 	if (!peeking)
19166aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
1917629ca23cSPavel Emelyanov 			      UDP_MIB_INDATAGRAMS, is_udplite);
1918db8dac20SDavid S. Miller 
19196fd1d51cSErin MacNeil 	sock_recv_cmsgs(msg, sk, skb);
1920db8dac20SDavid S. Miller 
1921db8dac20SDavid S. Miller 	/* Copy the address. */
1922c482c568SEric Dumazet 	if (sin) {
1923db8dac20SDavid S. Miller 		sin->sin_family = AF_INET;
1924db8dac20SDavid S. Miller 		sin->sin_port = udp_hdr(skb)->source;
1925db8dac20SDavid S. Miller 		sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
1926db8dac20SDavid S. Miller 		memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
1927bceaa902SHannes Frederic Sowa 		*addr_len = sizeof(*sin);
1928983695faSDaniel Borkmann 
1929983695faSDaniel Borkmann 		BPF_CGROUP_RUN_PROG_UDP4_RECVMSG_LOCK(sk,
1930983695faSDaniel Borkmann 						      (struct sockaddr *)sin);
1931db8dac20SDavid S. Miller 	}
1932bcd1665eSPaolo Abeni 
1933bcd1665eSPaolo Abeni 	if (udp_sk(sk)->gro_enabled)
1934bcd1665eSPaolo Abeni 		udp_cmsg_recv(msg, sk, skb);
1935bcd1665eSPaolo Abeni 
1936db8dac20SDavid S. Miller 	if (inet->cmsg_flags)
1937ad959036SPaolo Abeni 		ip_cmsg_recv_offset(msg, sk, skb, sizeof(struct udphdr), off);
1938db8dac20SDavid S. Miller 
193959c2cdaeSDavid S. Miller 	err = copied;
1940db8dac20SDavid S. Miller 	if (flags & MSG_TRUNC)
1941db8dac20SDavid S. Miller 		err = ulen;
1942db8dac20SDavid S. Miller 
1943850cbaddSPaolo Abeni 	skb_consume_udp(sk, skb, peeking ? -err : err);
1944db8dac20SDavid S. Miller 	return err;
1945db8dac20SDavid S. Miller 
1946db8dac20SDavid S. Miller csum_copy_err:
19472276f58aSPaolo Abeni 	if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags,
19482276f58aSPaolo Abeni 				 udp_skb_destructor)) {
19496aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
19506aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
19516a5dc9e5SEric Dumazet 	}
1952850cbaddSPaolo Abeni 	kfree_skb(skb);
1953db8dac20SDavid S. Miller 
1954beb39db5SEric Dumazet 	/* starting over for a new packet, but check if we need to yield */
1955beb39db5SEric Dumazet 	cond_resched();
19569cfaa8deSXufeng Zhang 	msg->msg_flags &= ~MSG_TRUNC;
1957db8dac20SDavid S. Miller 	goto try_again;
1958db8dac20SDavid S. Miller }
1959db8dac20SDavid S. Miller 
1960d74bad4eSAndrey Ignatov int udp_pre_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
1961d74bad4eSAndrey Ignatov {
1962d74bad4eSAndrey Ignatov 	/* This check is replicated from __ip4_datagram_connect() and
1963d74bad4eSAndrey Ignatov 	 * intended to prevent BPF program called below from accessing bytes
1964d74bad4eSAndrey Ignatov 	 * that are out of the bound specified by user in addr_len.
1965d74bad4eSAndrey Ignatov 	 */
1966d74bad4eSAndrey Ignatov 	if (addr_len < sizeof(struct sockaddr_in))
1967d74bad4eSAndrey Ignatov 		return -EINVAL;
1968d74bad4eSAndrey Ignatov 
1969d74bad4eSAndrey Ignatov 	return BPF_CGROUP_RUN_PROG_INET4_CONNECT_LOCK(sk, uaddr);
1970d74bad4eSAndrey Ignatov }
1971d74bad4eSAndrey Ignatov EXPORT_SYMBOL(udp_pre_connect);
1972d74bad4eSAndrey Ignatov 
1973286c72deSEric Dumazet int __udp_disconnect(struct sock *sk, int flags)
19741da177e4SLinus Torvalds {
19751da177e4SLinus Torvalds 	struct inet_sock *inet = inet_sk(sk);
19761da177e4SLinus Torvalds 	/*
19771da177e4SLinus Torvalds 	 *	1003.1g - break association.
19781da177e4SLinus Torvalds 	 */
19791da177e4SLinus Torvalds 
19801da177e4SLinus Torvalds 	sk->sk_state = TCP_CLOSE;
1981c720c7e8SEric Dumazet 	inet->inet_daddr = 0;
1982c720c7e8SEric Dumazet 	inet->inet_dport = 0;
1983bdeab991STom Herbert 	sock_rps_reset_rxhash(sk);
19841da177e4SLinus Torvalds 	sk->sk_bound_dev_if = 0;
1985303d0403SWillem de Bruijn 	if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) {
19861da177e4SLinus Torvalds 		inet_reset_saddr(sk);
1987303d0403SWillem de Bruijn 		if (sk->sk_prot->rehash &&
1988303d0403SWillem de Bruijn 		    (sk->sk_userlocks & SOCK_BINDPORT_LOCK))
1989303d0403SWillem de Bruijn 			sk->sk_prot->rehash(sk);
1990303d0403SWillem de Bruijn 	}
19911da177e4SLinus Torvalds 
19921da177e4SLinus Torvalds 	if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
19931da177e4SLinus Torvalds 		sk->sk_prot->unhash(sk);
1994c720c7e8SEric Dumazet 		inet->inet_sport = 0;
19951da177e4SLinus Torvalds 	}
19961da177e4SLinus Torvalds 	sk_dst_reset(sk);
19971da177e4SLinus Torvalds 	return 0;
19981da177e4SLinus Torvalds }
1999286c72deSEric Dumazet EXPORT_SYMBOL(__udp_disconnect);
2000286c72deSEric Dumazet 
2001286c72deSEric Dumazet int udp_disconnect(struct sock *sk, int flags)
2002286c72deSEric Dumazet {
2003286c72deSEric Dumazet 	lock_sock(sk);
2004286c72deSEric Dumazet 	__udp_disconnect(sk, flags);
2005286c72deSEric Dumazet 	release_sock(sk);
2006286c72deSEric Dumazet 	return 0;
2007286c72deSEric Dumazet }
2008c482c568SEric Dumazet EXPORT_SYMBOL(udp_disconnect);
20091da177e4SLinus Torvalds 
2010645ca708SEric Dumazet void udp_lib_unhash(struct sock *sk)
2011645ca708SEric Dumazet {
2012723b4610SEric Dumazet 	if (sk_hashed(sk)) {
201367fb4330SKuniyuki Iwashima 		struct udp_table *udptable = udp_get_table_prot(sk);
2014512615b6SEric Dumazet 		struct udp_hslot *hslot, *hslot2;
2015512615b6SEric Dumazet 
2016512615b6SEric Dumazet 		hslot  = udp_hashslot(udptable, sock_net(sk),
2017d4cada4aSEric Dumazet 				      udp_sk(sk)->udp_port_hash);
2018512615b6SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
2019645ca708SEric Dumazet 
2020c8db3fecSEric Dumazet 		spin_lock_bh(&hslot->lock);
2021e32ea7e7SCraig Gallek 		if (rcu_access_pointer(sk->sk_reuseport_cb))
2022e32ea7e7SCraig Gallek 			reuseport_detach_sock(sk);
2023ca065d0cSEric Dumazet 		if (sk_del_node_init_rcu(sk)) {
2024fdcc8aa9SEric Dumazet 			hslot->count--;
2025c720c7e8SEric Dumazet 			inet_sk(sk)->inet_num = 0;
2026645ca708SEric Dumazet 			sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
2027512615b6SEric Dumazet 
2028512615b6SEric Dumazet 			spin_lock(&hslot2->lock);
2029ca065d0cSEric Dumazet 			hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
2030512615b6SEric Dumazet 			hslot2->count--;
2031512615b6SEric Dumazet 			spin_unlock(&hslot2->lock);
2032645ca708SEric Dumazet 		}
2033c8db3fecSEric Dumazet 		spin_unlock_bh(&hslot->lock);
2034645ca708SEric Dumazet 	}
2035723b4610SEric Dumazet }
2036645ca708SEric Dumazet EXPORT_SYMBOL(udp_lib_unhash);
2037645ca708SEric Dumazet 
2038719f8358SEric Dumazet /*
2039719f8358SEric Dumazet  * inet_rcv_saddr was changed, we must rehash secondary hash
2040719f8358SEric Dumazet  */
2041719f8358SEric Dumazet void udp_lib_rehash(struct sock *sk, u16 newhash)
2042719f8358SEric Dumazet {
2043719f8358SEric Dumazet 	if (sk_hashed(sk)) {
204467fb4330SKuniyuki Iwashima 		struct udp_table *udptable = udp_get_table_prot(sk);
2045719f8358SEric Dumazet 		struct udp_hslot *hslot, *hslot2, *nhslot2;
2046719f8358SEric Dumazet 
2047719f8358SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
2048719f8358SEric Dumazet 		nhslot2 = udp_hashslot2(udptable, newhash);
2049719f8358SEric Dumazet 		udp_sk(sk)->udp_portaddr_hash = newhash;
2050e32ea7e7SCraig Gallek 
2051e32ea7e7SCraig Gallek 		if (hslot2 != nhslot2 ||
2052e32ea7e7SCraig Gallek 		    rcu_access_pointer(sk->sk_reuseport_cb)) {
2053719f8358SEric Dumazet 			hslot = udp_hashslot(udptable, sock_net(sk),
2054719f8358SEric Dumazet 					     udp_sk(sk)->udp_port_hash);
2055719f8358SEric Dumazet 			/* we must lock primary chain too */
2056719f8358SEric Dumazet 			spin_lock_bh(&hslot->lock);
2057e32ea7e7SCraig Gallek 			if (rcu_access_pointer(sk->sk_reuseport_cb))
2058e32ea7e7SCraig Gallek 				reuseport_detach_sock(sk);
2059719f8358SEric Dumazet 
2060e32ea7e7SCraig Gallek 			if (hslot2 != nhslot2) {
2061719f8358SEric Dumazet 				spin_lock(&hslot2->lock);
2062ca065d0cSEric Dumazet 				hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
2063719f8358SEric Dumazet 				hslot2->count--;
2064719f8358SEric Dumazet 				spin_unlock(&hslot2->lock);
2065719f8358SEric Dumazet 
2066719f8358SEric Dumazet 				spin_lock(&nhslot2->lock);
2067ca065d0cSEric Dumazet 				hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
2068719f8358SEric Dumazet 							 &nhslot2->head);
2069719f8358SEric Dumazet 				nhslot2->count++;
2070719f8358SEric Dumazet 				spin_unlock(&nhslot2->lock);
2071e32ea7e7SCraig Gallek 			}
2072719f8358SEric Dumazet 
2073719f8358SEric Dumazet 			spin_unlock_bh(&hslot->lock);
2074719f8358SEric Dumazet 		}
2075719f8358SEric Dumazet 	}
2076719f8358SEric Dumazet }
2077719f8358SEric Dumazet EXPORT_SYMBOL(udp_lib_rehash);
2078719f8358SEric Dumazet 
20798f6b5392SAlexey Kodanev void udp_v4_rehash(struct sock *sk)
2080719f8358SEric Dumazet {
2081f0b1e64cSMartin KaFai Lau 	u16 new_hash = ipv4_portaddr_hash(sock_net(sk),
2082719f8358SEric Dumazet 					  inet_sk(sk)->inet_rcv_saddr,
2083719f8358SEric Dumazet 					  inet_sk(sk)->inet_num);
2084719f8358SEric Dumazet 	udp_lib_rehash(sk, new_hash);
2085719f8358SEric Dumazet }
2086719f8358SEric Dumazet 
2087a3f96c47SPaolo Abeni static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
208893821778SHerbert Xu {
2089fec5e652STom Herbert 	int rc;
209093821778SHerbert Xu 
2091005ec974SShawn Bohrer 	if (inet_sk(sk)->inet_daddr) {
2092bdeab991STom Herbert 		sock_rps_save_rxhash(sk, skb);
2093005ec974SShawn Bohrer 		sk_mark_napi_id(sk, skb);
20942c8c56e1SEric Dumazet 		sk_incoming_cpu_update(sk);
2095e68b6e50SEric Dumazet 	} else {
2096e68b6e50SEric Dumazet 		sk_mark_napi_id_once(sk, skb);
2097005ec974SShawn Bohrer 	}
2098fec5e652STom Herbert 
2099850cbaddSPaolo Abeni 	rc = __udp_enqueue_schedule_skb(sk, skb);
2100766e9037SEric Dumazet 	if (rc < 0) {
2101766e9037SEric Dumazet 		int is_udplite = IS_UDPLITE(sk);
210208d4c037SMenglong Dong 		int drop_reason;
2103766e9037SEric Dumazet 
210493821778SHerbert Xu 		/* Note that an ENOMEM error is charged twice */
210508d4c037SMenglong Dong 		if (rc == -ENOMEM) {
2106e61da9e2SEric Dumazet 			UDP_INC_STATS(sock_net(sk), UDP_MIB_RCVBUFERRORS,
210793821778SHerbert Xu 					is_udplite);
210808d4c037SMenglong Dong 			drop_reason = SKB_DROP_REASON_SOCKET_RCVBUFF;
210908d4c037SMenglong Dong 		} else {
2110a3ce2b10SMenglong Dong 			UDP_INC_STATS(sock_net(sk), UDP_MIB_MEMERRORS,
2111a3ce2b10SMenglong Dong 				      is_udplite);
211208d4c037SMenglong Dong 			drop_reason = SKB_DROP_REASON_PROTO_MEM;
211308d4c037SMenglong Dong 		}
2114e61da9e2SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
211508d4c037SMenglong Dong 		kfree_skb_reason(skb, drop_reason);
2116296f7ea7SSatoru Moriya 		trace_udp_fail_queue_rcv_skb(rc, sk);
2117766e9037SEric Dumazet 		return -1;
211893821778SHerbert Xu 	}
211993821778SHerbert Xu 
212093821778SHerbert Xu 	return 0;
212193821778SHerbert Xu }
212293821778SHerbert Xu 
2123db8dac20SDavid S. Miller /* returns:
2124db8dac20SDavid S. Miller  *  -1: error
2125db8dac20SDavid S. Miller  *   0: success
2126db8dac20SDavid S. Miller  *  >0: "udp encap" protocol resubmission
2127db8dac20SDavid S. Miller  *
2128db8dac20SDavid S. Miller  * Note that in the success and error cases, the skb is assumed to
2129db8dac20SDavid S. Miller  * have either been requeued or freed.
2130db8dac20SDavid S. Miller  */
2131cf329aa4SPaolo Abeni static int udp_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
2132db8dac20SDavid S. Miller {
21331379a92dSMenglong Dong 	int drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2134db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
2135db8dac20SDavid S. Miller 	int is_udplite = IS_UDPLITE(sk);
2136db8dac20SDavid S. Miller 
2137db8dac20SDavid S. Miller 	/*
2138db8dac20SDavid S. Miller 	 *	Charge it to the socket, dropping if the queue is full.
2139db8dac20SDavid S. Miller 	 */
21401379a92dSMenglong Dong 	if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
21411379a92dSMenglong Dong 		drop_reason = SKB_DROP_REASON_XFRM_POLICY;
2142db8dac20SDavid S. Miller 		goto drop;
21431379a92dSMenglong Dong 	}
2144895b5c9fSFlorian Westphal 	nf_reset_ct(skb);
2145db8dac20SDavid S. Miller 
214688ab3108SDavidlohr Bueso 	if (static_branch_unlikely(&udp_encap_needed_key) && up->encap_type) {
21470ad92ad0SEric Dumazet 		int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
21480ad92ad0SEric Dumazet 
2149db8dac20SDavid S. Miller 		/*
2150db8dac20SDavid S. Miller 		 * This is an encapsulation socket so pass the skb to
2151db8dac20SDavid S. Miller 		 * the socket's udp_encap_rcv() hook. Otherwise, just
2152db8dac20SDavid S. Miller 		 * fall through and pass this up the UDP socket.
2153db8dac20SDavid S. Miller 		 * up->encap_rcv() returns the following value:
2154db8dac20SDavid S. Miller 		 * =0 if skb was successfully passed to the encap
2155db8dac20SDavid S. Miller 		 *    handler or was discarded by it.
2156db8dac20SDavid S. Miller 		 * >0 if skb should be passed on to UDP.
2157db8dac20SDavid S. Miller 		 * <0 if skb should be resubmitted as proto -N
2158db8dac20SDavid S. Miller 		 */
2159db8dac20SDavid S. Miller 
2160db8dac20SDavid S. Miller 		/* if we're overly short, let UDP handle it */
21616aa7de05SMark Rutland 		encap_rcv = READ_ONCE(up->encap_rcv);
2162e5aed006SHannes Frederic Sowa 		if (encap_rcv) {
2163db8dac20SDavid S. Miller 			int ret;
2164db8dac20SDavid S. Miller 
21650a80966bSTom Herbert 			/* Verify checksum before giving to encap */
21660a80966bSTom Herbert 			if (udp_lib_checksum_complete(skb))
21670a80966bSTom Herbert 				goto csum_error;
21680a80966bSTom Herbert 
21690ad92ad0SEric Dumazet 			ret = encap_rcv(sk, skb);
2170db8dac20SDavid S. Miller 			if (ret <= 0) {
217102c22347SEric Dumazet 				__UDP_INC_STATS(sock_net(sk),
21720283328eSPavel Emelyanov 						UDP_MIB_INDATAGRAMS,
2173db8dac20SDavid S. Miller 						is_udplite);
2174db8dac20SDavid S. Miller 				return -ret;
2175db8dac20SDavid S. Miller 			}
2176db8dac20SDavid S. Miller 		}
2177db8dac20SDavid S. Miller 
2178db8dac20SDavid S. Miller 		/* FALLTHROUGH -- it's a UDP Packet */
2179db8dac20SDavid S. Miller 	}
2180db8dac20SDavid S. Miller 
2181db8dac20SDavid S. Miller 	/*
2182db8dac20SDavid S. Miller 	 * 	UDP-Lite specific tests, ignored on UDP sockets
2183db8dac20SDavid S. Miller 	 */
2184b0a42277SMiaohe Lin 	if ((up->pcflag & UDPLITE_RECV_CC)  &&  UDP_SKB_CB(skb)->partial_cov) {
2185db8dac20SDavid S. Miller 
2186db8dac20SDavid S. Miller 		/*
2187db8dac20SDavid S. Miller 		 * MIB statistics other than incrementing the error count are
2188db8dac20SDavid S. Miller 		 * disabled for the following two types of errors: these depend
2189db8dac20SDavid S. Miller 		 * on the application settings, not on the functioning of the
2190db8dac20SDavid S. Miller 		 * protocol stack as such.
2191db8dac20SDavid S. Miller 		 *
2192db8dac20SDavid S. Miller 		 * RFC 3828 here recommends (sec 3.3): "There should also be a
2193db8dac20SDavid S. Miller 		 * way ... to ... at least let the receiving application block
2194db8dac20SDavid S. Miller 		 * delivery of packets with coverage values less than a value
2195db8dac20SDavid S. Miller 		 * provided by the application."
2196db8dac20SDavid S. Miller 		 */
2197db8dac20SDavid S. Miller 		if (up->pcrlen == 0) {          /* full coverage was set  */
2198ba7a46f1SJoe Perches 			net_dbg_ratelimited("UDPLite: partial coverage %d while full coverage %d requested\n",
2199db8dac20SDavid S. Miller 					    UDP_SKB_CB(skb)->cscov, skb->len);
2200db8dac20SDavid S. Miller 			goto drop;
2201db8dac20SDavid S. Miller 		}
2202db8dac20SDavid S. Miller 		/* The next case involves violating the min. coverage requested
2203db8dac20SDavid S. Miller 		 * by the receiver. This is subtle: if receiver wants x and x is
2204db8dac20SDavid S. Miller 		 * greater than the buffersize/MTU then receiver will complain
2205db8dac20SDavid S. Miller 		 * that it wants x while sender emits packets of smaller size y.
2206db8dac20SDavid S. Miller 		 * Therefore the above ...()->partial_cov statement is essential.
2207db8dac20SDavid S. Miller 		 */
2208db8dac20SDavid S. Miller 		if (UDP_SKB_CB(skb)->cscov  <  up->pcrlen) {
2209ba7a46f1SJoe Perches 			net_dbg_ratelimited("UDPLite: coverage %d too small, need min %d\n",
2210db8dac20SDavid S. Miller 					    UDP_SKB_CB(skb)->cscov, up->pcrlen);
2211db8dac20SDavid S. Miller 			goto drop;
2212db8dac20SDavid S. Miller 		}
2213db8dac20SDavid S. Miller 	}
2214db8dac20SDavid S. Miller 
2215dd99e425SPaolo Abeni 	prefetch(&sk->sk_rmem_alloc);
2216ce25d66aSEric Dumazet 	if (rcu_access_pointer(sk->sk_filter) &&
2217ce25d66aSEric Dumazet 	    udp_lib_checksum_complete(skb))
22186a5dc9e5SEric Dumazet 			goto csum_error;
2219ce25d66aSEric Dumazet 
22201379a92dSMenglong Dong 	if (sk_filter_trim_cap(sk, skb, sizeof(struct udphdr))) {
22211379a92dSMenglong Dong 		drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
2222a6127697SMichal Kubeček 		goto drop;
22231379a92dSMenglong Dong 	}
2224db8dac20SDavid S. Miller 
2225e6afc8acSsamanthakumar 	udp_csum_pull_header(skb);
2226db8dac20SDavid S. Miller 
2227fbf8866dSShawn Bohrer 	ipv4_pktinfo_prepare(sk, skb);
2228850cbaddSPaolo Abeni 	return __udp_queue_rcv_skb(sk, skb);
2229db8dac20SDavid S. Miller 
22306a5dc9e5SEric Dumazet csum_error:
22311379a92dSMenglong Dong 	drop_reason = SKB_DROP_REASON_UDP_CSUM;
223202c22347SEric Dumazet 	__UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
2233db8dac20SDavid S. Miller drop:
223402c22347SEric Dumazet 	__UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
22358edf19c2SEric Dumazet 	atomic_inc(&sk->sk_drops);
22361379a92dSMenglong Dong 	kfree_skb_reason(skb, drop_reason);
2237db8dac20SDavid S. Miller 	return -1;
2238db8dac20SDavid S. Miller }
2239db8dac20SDavid S. Miller 
2240cf329aa4SPaolo Abeni static int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2241cf329aa4SPaolo Abeni {
2242cf329aa4SPaolo Abeni 	struct sk_buff *next, *segs;
2243cf329aa4SPaolo Abeni 	int ret;
2244cf329aa4SPaolo Abeni 
2245cf329aa4SPaolo Abeni 	if (likely(!udp_unexpected_gso(sk, skb)))
2246cf329aa4SPaolo Abeni 		return udp_queue_rcv_one_skb(sk, skb);
2247cf329aa4SPaolo Abeni 
2248a08e7fd9SCambda Zhu 	BUILD_BUG_ON(sizeof(struct udp_skb_cb) > SKB_GSO_CB_OFFSET);
2249cf329aa4SPaolo Abeni 	__skb_push(skb, -skb_mac_offset(skb));
2250cf329aa4SPaolo Abeni 	segs = udp_rcv_segment(sk, skb, true);
22511a186c14SJason A. Donenfeld 	skb_list_walk_safe(segs, skb, next) {
2252cf329aa4SPaolo Abeni 		__skb_pull(skb, skb_transport_offset(skb));
2253000ac44dSPaolo Abeni 
2254000ac44dSPaolo Abeni 		udp_post_segment_fix_csum(skb);
2255cf329aa4SPaolo Abeni 		ret = udp_queue_rcv_one_skb(sk, skb);
2256cf329aa4SPaolo Abeni 		if (ret > 0)
225710c678bdSXin Long 			ip_protocol_deliver_rcu(dev_net(skb->dev), skb, ret);
2258cf329aa4SPaolo Abeni 	}
2259cf329aa4SPaolo Abeni 	return 0;
2260cf329aa4SPaolo Abeni }
2261cf329aa4SPaolo Abeni 
226297502231SEric Dumazet /* For TCP sockets, sk_rx_dst is protected by socket lock
2263e47eb5dfSEric Dumazet  * For UDP, we use xchg() to guard against concurrent changes.
226497502231SEric Dumazet  */
226564f0f5d1SPaolo Abeni bool udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
2266421b3885SShawn Bohrer {
226797502231SEric Dumazet 	struct dst_entry *old;
2268421b3885SShawn Bohrer 
2269d24406c8SWei Wang 	if (dst_hold_safe(dst)) {
22708f905c0eSEric Dumazet 		old = xchg((__force struct dst_entry **)&sk->sk_rx_dst, dst);
227197502231SEric Dumazet 		dst_release(old);
227264f0f5d1SPaolo Abeni 		return old != dst;
227397502231SEric Dumazet 	}
227464f0f5d1SPaolo Abeni 	return false;
2275d24406c8SWei Wang }
2276c9f2c1aeSPaolo Abeni EXPORT_SYMBOL(udp_sk_rx_dst_set);
2277421b3885SShawn Bohrer 
2278db8dac20SDavid S. Miller /*
2279db8dac20SDavid S. Miller  *	Multicasts and broadcasts go to each listener.
2280db8dac20SDavid S. Miller  *
22811240d137SEric Dumazet  *	Note: called only from the BH handler context.
2282db8dac20SDavid S. Miller  */
2283e3163493SPavel Emelyanov static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
2284db8dac20SDavid S. Miller 				    struct udphdr  *uh,
2285db8dac20SDavid S. Miller 				    __be32 saddr, __be32 daddr,
228636cbb245SRick Jones 				    struct udp_table *udptable,
228736cbb245SRick Jones 				    int proto)
2288db8dac20SDavid S. Miller {
2289ca065d0cSEric Dumazet 	struct sock *sk, *first = NULL;
22905cf3d461SDavid Held 	unsigned short hnum = ntohs(uh->dest);
22915cf3d461SDavid Held 	struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum);
22922dc41cffSDavid Held 	unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10);
2293ca065d0cSEric Dumazet 	unsigned int offset = offsetof(typeof(*sk), sk_node);
2294ca065d0cSEric Dumazet 	int dif = skb->dev->ifindex;
2295fb74c277SDavid Ahern 	int sdif = inet_sdif(skb);
2296ca065d0cSEric Dumazet 	struct hlist_node *node;
2297ca065d0cSEric Dumazet 	struct sk_buff *nskb;
22982dc41cffSDavid Held 
22992dc41cffSDavid Held 	if (use_hash2) {
2300f0b1e64cSMartin KaFai Lau 		hash2_any = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum) &
230173e2d5e3SPablo Neira 			    udptable->mask;
2302f0b1e64cSMartin KaFai Lau 		hash2 = ipv4_portaddr_hash(net, daddr, hnum) & udptable->mask;
23032dc41cffSDavid Held start_lookup:
230473e2d5e3SPablo Neira 		hslot = &udptable->hash2[hash2];
23052dc41cffSDavid Held 		offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
23062dc41cffSDavid Held 	}
2307db8dac20SDavid S. Miller 
2308ca065d0cSEric Dumazet 	sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
2309ca065d0cSEric Dumazet 		if (!__udp_is_mcast_sock(net, sk, uh->dest, daddr,
2310fb74c277SDavid Ahern 					 uh->source, saddr, dif, sdif, hnum))
2311ca065d0cSEric Dumazet 			continue;
23121240d137SEric Dumazet 
2313ca065d0cSEric Dumazet 		if (!first) {
2314ca065d0cSEric Dumazet 			first = sk;
2315ca065d0cSEric Dumazet 			continue;
2316ca065d0cSEric Dumazet 		}
2317ca065d0cSEric Dumazet 		nskb = skb_clone(skb, GFP_ATOMIC);
2318ca065d0cSEric Dumazet 
2319ca065d0cSEric Dumazet 		if (unlikely(!nskb)) {
2320ca065d0cSEric Dumazet 			atomic_inc(&sk->sk_drops);
232102c22347SEric Dumazet 			__UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS,
2322ca065d0cSEric Dumazet 					IS_UDPLITE(sk));
232302c22347SEric Dumazet 			__UDP_INC_STATS(net, UDP_MIB_INERRORS,
2324ca065d0cSEric Dumazet 					IS_UDPLITE(sk));
2325ca065d0cSEric Dumazet 			continue;
2326ca065d0cSEric Dumazet 		}
2327ca065d0cSEric Dumazet 		if (udp_queue_rcv_skb(sk, nskb) > 0)
2328ca065d0cSEric Dumazet 			consume_skb(nskb);
2329ca065d0cSEric Dumazet 	}
23301240d137SEric Dumazet 
23312dc41cffSDavid Held 	/* Also lookup *:port if we are using hash2 and haven't done so yet. */
23322dc41cffSDavid Held 	if (use_hash2 && hash2 != hash2_any) {
23332dc41cffSDavid Held 		hash2 = hash2_any;
23342dc41cffSDavid Held 		goto start_lookup;
23352dc41cffSDavid Held 	}
23362dc41cffSDavid Held 
2337ca065d0cSEric Dumazet 	if (first) {
2338ca065d0cSEric Dumazet 		if (udp_queue_rcv_skb(first, skb) > 0)
2339ca065d0cSEric Dumazet 			consume_skb(skb);
23401240d137SEric Dumazet 	} else {
2341ca065d0cSEric Dumazet 		kfree_skb(skb);
234202c22347SEric Dumazet 		__UDP_INC_STATS(net, UDP_MIB_IGNOREDMULTI,
234336cbb245SRick Jones 				proto == IPPROTO_UDPLITE);
23441240d137SEric Dumazet 	}
2345db8dac20SDavid S. Miller 	return 0;
2346db8dac20SDavid S. Miller }
2347db8dac20SDavid S. Miller 
2348db8dac20SDavid S. Miller /* Initialize UDP checksum. If exited with zero value (success),
2349db8dac20SDavid S. Miller  * CHECKSUM_UNNECESSARY means, that no more checks are required.
2350666a3d6eSSu Yanjun  * Otherwise, csum completion requires checksumming packet body,
2351db8dac20SDavid S. Miller  * including udp header and folding it to skb->csum.
2352db8dac20SDavid S. Miller  */
2353db8dac20SDavid S. Miller static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
2354db8dac20SDavid S. Miller 				 int proto)
2355db8dac20SDavid S. Miller {
2356db8dac20SDavid S. Miller 	int err;
2357db8dac20SDavid S. Miller 
2358db8dac20SDavid S. Miller 	UDP_SKB_CB(skb)->partial_cov = 0;
2359db8dac20SDavid S. Miller 	UDP_SKB_CB(skb)->cscov = skb->len;
2360db8dac20SDavid S. Miller 
2361db8dac20SDavid S. Miller 	if (proto == IPPROTO_UDPLITE) {
2362db8dac20SDavid S. Miller 		err = udplite_checksum_init(skb, uh);
2363db8dac20SDavid S. Miller 		if (err)
2364db8dac20SDavid S. Miller 			return err;
236515f35d49SAlexey Kodanev 
236615f35d49SAlexey Kodanev 		if (UDP_SKB_CB(skb)->partial_cov) {
236715f35d49SAlexey Kodanev 			skb->csum = inet_compute_pseudo(skb, proto);
236815f35d49SAlexey Kodanev 			return 0;
236915f35d49SAlexey Kodanev 		}
2370db8dac20SDavid S. Miller 	}
2371db8dac20SDavid S. Miller 
2372b46d9f62SHannes Frederic Sowa 	/* Note, we are only interested in != 0 or == 0, thus the
2373b46d9f62SHannes Frederic Sowa 	 * force to int.
2374b46d9f62SHannes Frederic Sowa 	 */
2375db4f1be3SSean Tranchetti 	err = (__force int)skb_checksum_init_zero_check(skb, proto, uh->check,
2376ed70fcfcSTom Herbert 							inet_compute_pseudo);
2377db4f1be3SSean Tranchetti 	if (err)
2378db4f1be3SSean Tranchetti 		return err;
2379db4f1be3SSean Tranchetti 
2380db4f1be3SSean Tranchetti 	if (skb->ip_summed == CHECKSUM_COMPLETE && !skb->csum_valid) {
2381db4f1be3SSean Tranchetti 		/* If SW calculated the value, we know it's bad */
2382db4f1be3SSean Tranchetti 		if (skb->csum_complete_sw)
2383db4f1be3SSean Tranchetti 			return 1;
2384db4f1be3SSean Tranchetti 
2385db4f1be3SSean Tranchetti 		/* HW says the value is bad. Let's validate that.
2386db4f1be3SSean Tranchetti 		 * skb->csum is no longer the full packet checksum,
2387db4f1be3SSean Tranchetti 		 * so don't treat it as such.
2388db4f1be3SSean Tranchetti 		 */
2389db4f1be3SSean Tranchetti 		skb_checksum_complete_unset(skb);
2390db4f1be3SSean Tranchetti 	}
2391db4f1be3SSean Tranchetti 
2392db4f1be3SSean Tranchetti 	return 0;
2393db8dac20SDavid S. Miller }
2394db8dac20SDavid S. Miller 
23952b5a9217SPaolo Abeni /* wrapper for udp_queue_rcv_skb tacking care of csum conversion and
23962b5a9217SPaolo Abeni  * return code conversion for ip layer consumption
23972b5a9217SPaolo Abeni  */
23982b5a9217SPaolo Abeni static int udp_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb,
23992b5a9217SPaolo Abeni 			       struct udphdr *uh)
24002b5a9217SPaolo Abeni {
24012b5a9217SPaolo Abeni 	int ret;
24022b5a9217SPaolo Abeni 
24032b5a9217SPaolo Abeni 	if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk))
2404e4aa33adSLi RongQing 		skb_checksum_try_convert(skb, IPPROTO_UDP, inet_compute_pseudo);
24052b5a9217SPaolo Abeni 
24062b5a9217SPaolo Abeni 	ret = udp_queue_rcv_skb(sk, skb);
24072b5a9217SPaolo Abeni 
24082b5a9217SPaolo Abeni 	/* a return value > 0 means to resubmit the input, but
24092b5a9217SPaolo Abeni 	 * it wants the return to be -protocol, or 0
24102b5a9217SPaolo Abeni 	 */
24112b5a9217SPaolo Abeni 	if (ret > 0)
24122b5a9217SPaolo Abeni 		return -ret;
24132b5a9217SPaolo Abeni 	return 0;
24142b5a9217SPaolo Abeni }
24152b5a9217SPaolo Abeni 
2416db8dac20SDavid S. Miller /*
2417db8dac20SDavid S. Miller  *	All we need to do is get the socket, and then do a checksum.
2418db8dac20SDavid S. Miller  */
2419db8dac20SDavid S. Miller 
2420645ca708SEric Dumazet int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
2421db8dac20SDavid S. Miller 		   int proto)
2422db8dac20SDavid S. Miller {
2423db8dac20SDavid S. Miller 	struct sock *sk;
24247b5e56f9SJesper Dangaard Brouer 	struct udphdr *uh;
2425db8dac20SDavid S. Miller 	unsigned short ulen;
2426adf30907SEric Dumazet 	struct rtable *rt = skb_rtable(skb);
24272783ef23SJesper Dangaard Brouer 	__be32 saddr, daddr;
24280283328eSPavel Emelyanov 	struct net *net = dev_net(skb->dev);
242971489e21SJoe Stringer 	bool refcounted;
24301c7fab70SMenglong Dong 	int drop_reason;
24311c7fab70SMenglong Dong 
24321c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2433db8dac20SDavid S. Miller 
2434db8dac20SDavid S. Miller 	/*
2435db8dac20SDavid S. Miller 	 *  Validate the packet.
2436db8dac20SDavid S. Miller 	 */
2437db8dac20SDavid S. Miller 	if (!pskb_may_pull(skb, sizeof(struct udphdr)))
2438db8dac20SDavid S. Miller 		goto drop;		/* No space for header. */
2439db8dac20SDavid S. Miller 
24407b5e56f9SJesper Dangaard Brouer 	uh   = udp_hdr(skb);
2441db8dac20SDavid S. Miller 	ulen = ntohs(uh->len);
2442ccc2d97cSBjørn Mork 	saddr = ip_hdr(skb)->saddr;
2443ccc2d97cSBjørn Mork 	daddr = ip_hdr(skb)->daddr;
2444ccc2d97cSBjørn Mork 
2445db8dac20SDavid S. Miller 	if (ulen > skb->len)
2446db8dac20SDavid S. Miller 		goto short_packet;
2447db8dac20SDavid S. Miller 
2448db8dac20SDavid S. Miller 	if (proto == IPPROTO_UDP) {
2449db8dac20SDavid S. Miller 		/* UDP validates ulen. */
2450db8dac20SDavid S. Miller 		if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
2451db8dac20SDavid S. Miller 			goto short_packet;
2452db8dac20SDavid S. Miller 		uh = udp_hdr(skb);
2453db8dac20SDavid S. Miller 	}
2454db8dac20SDavid S. Miller 
2455db8dac20SDavid S. Miller 	if (udp4_csum_init(skb, uh, proto))
2456db8dac20SDavid S. Miller 		goto csum_error;
2457db8dac20SDavid S. Miller 
245871489e21SJoe Stringer 	sk = skb_steal_sock(skb, &refcounted);
24598afdd99aSEric Dumazet 	if (sk) {
246097502231SEric Dumazet 		struct dst_entry *dst = skb_dst(skb);
2461421b3885SShawn Bohrer 		int ret;
2462421b3885SShawn Bohrer 
24638f905c0eSEric Dumazet 		if (unlikely(rcu_dereference(sk->sk_rx_dst) != dst))
246497502231SEric Dumazet 			udp_sk_rx_dst_set(sk, dst);
2465421b3885SShawn Bohrer 
24662b5a9217SPaolo Abeni 		ret = udp_unicast_rcv_skb(sk, skb, uh);
246771489e21SJoe Stringer 		if (refcounted)
24688afdd99aSEric Dumazet 			sock_put(sk);
24692b5a9217SPaolo Abeni 		return ret;
2470c18450a5SFabian Frederick 	}
2471c18450a5SFabian Frederick 
2472db8dac20SDavid S. Miller 	if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
2473e3163493SPavel Emelyanov 		return __udp4_lib_mcast_deliver(net, skb, uh,
247436cbb245SRick Jones 						saddr, daddr, udptable, proto);
2475db8dac20SDavid S. Miller 
2476607c4aafSKOVACS Krisztian 	sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
24772b5a9217SPaolo Abeni 	if (sk)
24782b5a9217SPaolo Abeni 		return udp_unicast_rcv_skb(sk, skb, uh);
2479db8dac20SDavid S. Miller 
2480db8dac20SDavid S. Miller 	if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
2481db8dac20SDavid S. Miller 		goto drop;
2482895b5c9fSFlorian Westphal 	nf_reset_ct(skb);
2483db8dac20SDavid S. Miller 
2484db8dac20SDavid S. Miller 	/* No socket. Drop packet silently, if checksum is wrong */
2485db8dac20SDavid S. Miller 	if (udp_lib_checksum_complete(skb))
2486db8dac20SDavid S. Miller 		goto csum_error;
2487db8dac20SDavid S. Miller 
24881c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_NO_SOCKET;
248902c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
2490db8dac20SDavid S. Miller 	icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
2491db8dac20SDavid S. Miller 
2492db8dac20SDavid S. Miller 	/*
2493db8dac20SDavid S. Miller 	 * Hmm.  We got an UDP packet to a port to which we
2494db8dac20SDavid S. Miller 	 * don't wanna listen.  Ignore it.
2495db8dac20SDavid S. Miller 	 */
24961c7fab70SMenglong Dong 	kfree_skb_reason(skb, drop_reason);
2497db8dac20SDavid S. Miller 	return 0;
2498db8dac20SDavid S. Miller 
2499db8dac20SDavid S. Miller short_packet:
25001c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_PKT_TOO_SMALL;
2501ba7a46f1SJoe Perches 	net_dbg_ratelimited("UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
2502afd46503SJoe Perches 			    proto == IPPROTO_UDPLITE ? "Lite" : "",
2503afd46503SJoe Perches 			    &saddr, ntohs(uh->source),
2504afd46503SJoe Perches 			    ulen, skb->len,
2505afd46503SJoe Perches 			    &daddr, ntohs(uh->dest));
2506db8dac20SDavid S. Miller 	goto drop;
2507db8dac20SDavid S. Miller 
2508db8dac20SDavid S. Miller csum_error:
2509db8dac20SDavid S. Miller 	/*
2510db8dac20SDavid S. Miller 	 * RFC1122: OK.  Discards the bad packet silently (as far as
2511db8dac20SDavid S. Miller 	 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
2512db8dac20SDavid S. Miller 	 */
25131c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_UDP_CSUM;
2514ba7a46f1SJoe Perches 	net_dbg_ratelimited("UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
2515afd46503SJoe Perches 			    proto == IPPROTO_UDPLITE ? "Lite" : "",
2516afd46503SJoe Perches 			    &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
2517db8dac20SDavid S. Miller 			    ulen);
251802c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
2519db8dac20SDavid S. Miller drop:
252002c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
25211c7fab70SMenglong Dong 	kfree_skb_reason(skb, drop_reason);
2522db8dac20SDavid S. Miller 	return 0;
2523db8dac20SDavid S. Miller }
2524db8dac20SDavid S. Miller 
2525421b3885SShawn Bohrer /* We can only early demux multicast if there is a single matching socket.
2526421b3885SShawn Bohrer  * If more than one socket found returns NULL
2527421b3885SShawn Bohrer  */
2528421b3885SShawn Bohrer static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net,
2529421b3885SShawn Bohrer 						  __be16 loc_port, __be32 loc_addr,
2530421b3885SShawn Bohrer 						  __be16 rmt_port, __be32 rmt_addr,
2531fb74c277SDavid Ahern 						  int dif, int sdif)
2532421b3885SShawn Bohrer {
2533ba6aac15SKuniyuki Iwashima 	struct udp_table *udptable = net->ipv4.udp_table;
2534421b3885SShawn Bohrer 	unsigned short hnum = ntohs(loc_port);
2535919dfa0bSKuniyuki Iwashima 	struct sock *sk, *result;
2536919dfa0bSKuniyuki Iwashima 	struct udp_hslot *hslot;
2537919dfa0bSKuniyuki Iwashima 	unsigned int slot;
2538919dfa0bSKuniyuki Iwashima 
2539ba6aac15SKuniyuki Iwashima 	slot = udp_hashfn(net, hnum, udptable->mask);
2540ba6aac15SKuniyuki Iwashima 	hslot = &udptable->hash[slot];
2541421b3885SShawn Bohrer 
254263c6f81cSEric Dumazet 	/* Do not bother scanning a too big list */
254363c6f81cSEric Dumazet 	if (hslot->count > 10)
254463c6f81cSEric Dumazet 		return NULL;
254563c6f81cSEric Dumazet 
2546421b3885SShawn Bohrer 	result = NULL;
2547ca065d0cSEric Dumazet 	sk_for_each_rcu(sk, &hslot->head) {
2548ca065d0cSEric Dumazet 		if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr,
2549fb74c277SDavid Ahern 					rmt_port, rmt_addr, dif, sdif, hnum)) {
2550ca065d0cSEric Dumazet 			if (result)
2551ca065d0cSEric Dumazet 				return NULL;
2552421b3885SShawn Bohrer 			result = sk;
2553421b3885SShawn Bohrer 		}
2554421b3885SShawn Bohrer 	}
2555421b3885SShawn Bohrer 
2556421b3885SShawn Bohrer 	return result;
2557421b3885SShawn Bohrer }
2558421b3885SShawn Bohrer 
2559421b3885SShawn Bohrer /* For unicast we should only early demux connected sockets or we can
2560421b3885SShawn Bohrer  * break forwarding setups.  The chains here can be long so only check
2561421b3885SShawn Bohrer  * if the first socket is an exact match and if not move on.
2562421b3885SShawn Bohrer  */
2563421b3885SShawn Bohrer static struct sock *__udp4_lib_demux_lookup(struct net *net,
2564421b3885SShawn Bohrer 					    __be16 loc_port, __be32 loc_addr,
2565421b3885SShawn Bohrer 					    __be16 rmt_port, __be32 rmt_addr,
25663fa6f616SDavid Ahern 					    int dif, int sdif)
2567421b3885SShawn Bohrer {
2568ba6aac15SKuniyuki Iwashima 	struct udp_table *udptable = net->ipv4.udp_table;
2569c7228317SJoe Perches 	INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr);
2570919dfa0bSKuniyuki Iwashima 	unsigned short hnum = ntohs(loc_port);
2571919dfa0bSKuniyuki Iwashima 	unsigned int hash2, slot2;
2572919dfa0bSKuniyuki Iwashima 	struct udp_hslot *hslot2;
2573919dfa0bSKuniyuki Iwashima 	__portpair ports;
2574ca065d0cSEric Dumazet 	struct sock *sk;
2575421b3885SShawn Bohrer 
2576919dfa0bSKuniyuki Iwashima 	hash2 = ipv4_portaddr_hash(net, loc_addr, hnum);
2577ba6aac15SKuniyuki Iwashima 	slot2 = hash2 & udptable->mask;
2578ba6aac15SKuniyuki Iwashima 	hslot2 = &udptable->hash2[slot2];
2579919dfa0bSKuniyuki Iwashima 	ports = INET_COMBINED_PORTS(rmt_port, hnum);
2580919dfa0bSKuniyuki Iwashima 
2581ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
2582eda090c3SEric Dumazet 		if (inet_match(net, sk, acookie, ports, dif, sdif))
2583ca065d0cSEric Dumazet 			return sk;
2584421b3885SShawn Bohrer 		/* Only check first socket in chain */
2585421b3885SShawn Bohrer 		break;
2586421b3885SShawn Bohrer 	}
2587ca065d0cSEric Dumazet 	return NULL;
2588421b3885SShawn Bohrer }
2589421b3885SShawn Bohrer 
25907487449cSPaolo Abeni int udp_v4_early_demux(struct sk_buff *skb)
2591421b3885SShawn Bohrer {
2592610438b7SEric Dumazet 	struct net *net = dev_net(skb->dev);
2593bc044e8dSPaolo Abeni 	struct in_device *in_dev = NULL;
2594610438b7SEric Dumazet 	const struct iphdr *iph;
2595610438b7SEric Dumazet 	const struct udphdr *uh;
2596ca065d0cSEric Dumazet 	struct sock *sk = NULL;
2597421b3885SShawn Bohrer 	struct dst_entry *dst;
2598421b3885SShawn Bohrer 	int dif = skb->dev->ifindex;
2599fb74c277SDavid Ahern 	int sdif = inet_sdif(skb);
26006e540309SShawn Bohrer 	int ours;
2601421b3885SShawn Bohrer 
2602421b3885SShawn Bohrer 	/* validate the packet */
2603421b3885SShawn Bohrer 	if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)))
26047487449cSPaolo Abeni 		return 0;
2605421b3885SShawn Bohrer 
2606610438b7SEric Dumazet 	iph = ip_hdr(skb);
2607610438b7SEric Dumazet 	uh = udp_hdr(skb);
2608610438b7SEric Dumazet 
2609996b44fcSPaolo Abeni 	if (skb->pkt_type == PACKET_MULTICAST) {
2610bc044e8dSPaolo Abeni 		in_dev = __in_dev_get_rcu(skb->dev);
26116e540309SShawn Bohrer 
26126e540309SShawn Bohrer 		if (!in_dev)
26137487449cSPaolo Abeni 			return 0;
26146e540309SShawn Bohrer 
26156e540309SShawn Bohrer 		ours = ip_check_mc_rcu(in_dev, iph->daddr, iph->saddr,
26166e540309SShawn Bohrer 				       iph->protocol);
26176e540309SShawn Bohrer 		if (!ours)
26187487449cSPaolo Abeni 			return 0;
2619ad0ea198SPaolo Abeni 
2620421b3885SShawn Bohrer 		sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr,
2621fb74c277SDavid Ahern 						   uh->source, iph->saddr,
2622fb74c277SDavid Ahern 						   dif, sdif);
26236e540309SShawn Bohrer 	} else if (skb->pkt_type == PACKET_HOST) {
2624421b3885SShawn Bohrer 		sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr,
26253fa6f616SDavid Ahern 					     uh->source, iph->saddr, dif, sdif);
26266e540309SShawn Bohrer 	}
2627421b3885SShawn Bohrer 
262841c6d650SReshetova, Elena 	if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
26297487449cSPaolo Abeni 		return 0;
2630421b3885SShawn Bohrer 
2631421b3885SShawn Bohrer 	skb->sk = sk;
263282eabd9eSAlexander Duyck 	skb->destructor = sock_efree;
26338f905c0eSEric Dumazet 	dst = rcu_dereference(sk->sk_rx_dst);
2634421b3885SShawn Bohrer 
2635421b3885SShawn Bohrer 	if (dst)
2636421b3885SShawn Bohrer 		dst = dst_check(dst, 0);
263710e2eb87SEric Dumazet 	if (dst) {
2638bc044e8dSPaolo Abeni 		u32 itag = 0;
2639bc044e8dSPaolo Abeni 
2640d24406c8SWei Wang 		/* set noref for now.
2641d24406c8SWei Wang 		 * any place which wants to hold dst has to call
2642d24406c8SWei Wang 		 * dst_hold_safe()
2643d24406c8SWei Wang 		 */
2644421b3885SShawn Bohrer 		skb_dst_set_noref(skb, dst);
2645bc044e8dSPaolo Abeni 
2646bc044e8dSPaolo Abeni 		/* for unconnected multicast sockets we need to validate
2647bc044e8dSPaolo Abeni 		 * the source on each packet
2648bc044e8dSPaolo Abeni 		 */
2649bc044e8dSPaolo Abeni 		if (!inet_sk(sk)->inet_daddr && in_dev)
2650bc044e8dSPaolo Abeni 			return ip_mc_validate_source(skb, iph->daddr,
26518d2b51b0SGuillaume Nault 						     iph->saddr,
26528d2b51b0SGuillaume Nault 						     iph->tos & IPTOS_RT_MASK,
2653bc044e8dSPaolo Abeni 						     skb->dev, in_dev, &itag);
2654421b3885SShawn Bohrer 	}
26557487449cSPaolo Abeni 	return 0;
265610e2eb87SEric Dumazet }
2657421b3885SShawn Bohrer 
2658db8dac20SDavid S. Miller int udp_rcv(struct sk_buff *skb)
2659db8dac20SDavid S. Miller {
2660ba6aac15SKuniyuki Iwashima 	return __udp4_lib_rcv(skb, dev_net(skb->dev)->ipv4.udp_table, IPPROTO_UDP);
2661db8dac20SDavid S. Miller }
2662db8dac20SDavid S. Miller 
26637d06b2e0SBrian Haley void udp_destroy_sock(struct sock *sk)
2664db8dac20SDavid S. Miller {
266544046a59STom Parkin 	struct udp_sock *up = udp_sk(sk);
26668a74ad60SEric Dumazet 	bool slow = lock_sock_fast(sk);
2667a8b897c7SPaolo Abeni 
2668a8b897c7SPaolo Abeni 	/* protects from races with udp_abort() */
2669a8b897c7SPaolo Abeni 	sock_set_flag(sk, SOCK_DEAD);
2670db8dac20SDavid S. Miller 	udp_flush_pending_frames(sk);
26718a74ad60SEric Dumazet 	unlock_sock_fast(sk, slow);
267260fb9567SPaolo Abeni 	if (static_branch_unlikely(&udp_encap_needed_key)) {
267360fb9567SPaolo Abeni 		if (up->encap_type) {
267444046a59STom Parkin 			void (*encap_destroy)(struct sock *sk);
26756aa7de05SMark Rutland 			encap_destroy = READ_ONCE(up->encap_destroy);
267644046a59STom Parkin 			if (encap_destroy)
267744046a59STom Parkin 				encap_destroy(sk);
267844046a59STom Parkin 		}
267960fb9567SPaolo Abeni 		if (up->encap_enabled)
26809c480601SPaolo Abeni 			static_branch_dec(&udp_encap_needed_key);
268160fb9567SPaolo Abeni 	}
2682db8dac20SDavid S. Miller }
2683db8dac20SDavid S. Miller 
26841da177e4SLinus Torvalds /*
26851da177e4SLinus Torvalds  *	Socket option code for UDP
26861da177e4SLinus Torvalds  */
26874c0a6cb0SGerrit Renker int udp_lib_setsockopt(struct sock *sk, int level, int optname,
268891ac1ccaSChristoph Hellwig 		       sockptr_t optval, unsigned int optlen,
26894c0a6cb0SGerrit Renker 		       int (*push_pending_frames)(struct sock *))
26901da177e4SLinus Torvalds {
26911da177e4SLinus Torvalds 	struct udp_sock *up = udp_sk(sk);
26921c19448cSTom Herbert 	int val, valbool;
26931da177e4SLinus Torvalds 	int err = 0;
2694b2bf1e26SWang Chen 	int is_udplite = IS_UDPLITE(sk);
26951da177e4SLinus Torvalds 
26968a3854c7SPaolo Abeni 	if (level == SOL_SOCKET) {
26978a3854c7SPaolo Abeni 		err = sk_setsockopt(sk, level, optname, optval, optlen);
26988a3854c7SPaolo Abeni 
26998a3854c7SPaolo Abeni 		if (optname == SO_RCVBUF || optname == SO_RCVBUFFORCE) {
27008a3854c7SPaolo Abeni 			sockopt_lock_sock(sk);
27018a3854c7SPaolo Abeni 			/* paired with READ_ONCE in udp_rmem_release() */
27028a3854c7SPaolo Abeni 			WRITE_ONCE(up->forward_threshold, sk->sk_rcvbuf >> 2);
27038a3854c7SPaolo Abeni 			sockopt_release_sock(sk);
27048a3854c7SPaolo Abeni 		}
27058a3854c7SPaolo Abeni 		return err;
27068a3854c7SPaolo Abeni 	}
27078a3854c7SPaolo Abeni 
27081da177e4SLinus Torvalds 	if (optlen < sizeof(int))
27091da177e4SLinus Torvalds 		return -EINVAL;
27101da177e4SLinus Torvalds 
271191ac1ccaSChristoph Hellwig 	if (copy_from_sockptr(&val, optval, sizeof(val)))
27121da177e4SLinus Torvalds 		return -EFAULT;
27131da177e4SLinus Torvalds 
27141c19448cSTom Herbert 	valbool = val ? 1 : 0;
27151c19448cSTom Herbert 
27161da177e4SLinus Torvalds 	switch (optname) {
27171da177e4SLinus Torvalds 	case UDP_CORK:
27181da177e4SLinus Torvalds 		if (val != 0) {
2719a9f59707SEric Dumazet 			WRITE_ONCE(up->corkflag, 1);
27201da177e4SLinus Torvalds 		} else {
2721a9f59707SEric Dumazet 			WRITE_ONCE(up->corkflag, 0);
27221da177e4SLinus Torvalds 			lock_sock(sk);
27234243cdc2SJoe Perches 			push_pending_frames(sk);
27241da177e4SLinus Torvalds 			release_sock(sk);
27251da177e4SLinus Torvalds 		}
27261da177e4SLinus Torvalds 		break;
27271da177e4SLinus Torvalds 
27281da177e4SLinus Torvalds 	case UDP_ENCAP:
27291da177e4SLinus Torvalds 		switch (val) {
27301da177e4SLinus Torvalds 		case 0:
2731fd1ac07fSAlexey Dobriyan #ifdef CONFIG_XFRM
27321da177e4SLinus Torvalds 		case UDP_ENCAP_ESPINUDP:
27331da177e4SLinus Torvalds 		case UDP_ENCAP_ESPINUDP_NON_IKE:
27340146dca7SSabrina Dubroca #if IS_ENABLED(CONFIG_IPV6)
27350146dca7SSabrina Dubroca 			if (sk->sk_family == AF_INET6)
27360146dca7SSabrina Dubroca 				up->encap_rcv = ipv6_stub->xfrm6_udp_encap_rcv;
27370146dca7SSabrina Dubroca 			else
27380146dca7SSabrina Dubroca #endif
2739067b207bSJames Chapman 				up->encap_rcv = xfrm4_udp_encap_rcv;
2740fd1ac07fSAlexey Dobriyan #endif
2741a8eceea8SJoe Perches 			fallthrough;
2742342f0234SJames Chapman 		case UDP_ENCAP_L2TPINUDP:
27431da177e4SLinus Torvalds 			up->encap_type = val;
274460fb9567SPaolo Abeni 			lock_sock(sk);
274560fb9567SPaolo Abeni 			udp_tunnel_encap_enable(sk->sk_socket);
274660fb9567SPaolo Abeni 			release_sock(sk);
27471da177e4SLinus Torvalds 			break;
27481da177e4SLinus Torvalds 		default:
27491da177e4SLinus Torvalds 			err = -ENOPROTOOPT;
27501da177e4SLinus Torvalds 			break;
27511da177e4SLinus Torvalds 		}
27521da177e4SLinus Torvalds 		break;
27531da177e4SLinus Torvalds 
27541c19448cSTom Herbert 	case UDP_NO_CHECK6_TX:
27551c19448cSTom Herbert 		up->no_check6_tx = valbool;
27561c19448cSTom Herbert 		break;
27571c19448cSTom Herbert 
27581c19448cSTom Herbert 	case UDP_NO_CHECK6_RX:
27591c19448cSTom Herbert 		up->no_check6_rx = valbool;
27601c19448cSTom Herbert 		break;
27611c19448cSTom Herbert 
2762bec1f6f6SWillem de Bruijn 	case UDP_SEGMENT:
2763bec1f6f6SWillem de Bruijn 		if (val < 0 || val > USHRT_MAX)
2764bec1f6f6SWillem de Bruijn 			return -EINVAL;
276518a419baSEric Dumazet 		WRITE_ONCE(up->gso_size, val);
2766bec1f6f6SWillem de Bruijn 		break;
2767bec1f6f6SWillem de Bruijn 
2768e20cf8d3SPaolo Abeni 	case UDP_GRO:
2769e20cf8d3SPaolo Abeni 		lock_sock(sk);
277078352f73SPaolo Abeni 
277178352f73SPaolo Abeni 		/* when enabling GRO, accept the related GSO packet type */
2772e20cf8d3SPaolo Abeni 		if (valbool)
2773e20cf8d3SPaolo Abeni 			udp_tunnel_encap_enable(sk->sk_socket);
2774e20cf8d3SPaolo Abeni 		up->gro_enabled = valbool;
277578352f73SPaolo Abeni 		up->accept_udp_l4 = valbool;
2776e20cf8d3SPaolo Abeni 		release_sock(sk);
2777e20cf8d3SPaolo Abeni 		break;
2778e20cf8d3SPaolo Abeni 
2779ba4e58ecSGerrit Renker 	/*
2780ba4e58ecSGerrit Renker 	 * 	UDP-Lite's partial checksum coverage (RFC 3828).
2781ba4e58ecSGerrit Renker 	 */
2782ba4e58ecSGerrit Renker 	/* The sender sets actual checksum coverage length via this option.
2783ba4e58ecSGerrit Renker 	 * The case coverage > packet length is handled by send module. */
2784ba4e58ecSGerrit Renker 	case UDPLITE_SEND_CSCOV:
2785b2bf1e26SWang Chen 		if (!is_udplite)         /* Disable the option on UDP sockets */
2786ba4e58ecSGerrit Renker 			return -ENOPROTOOPT;
2787ba4e58ecSGerrit Renker 		if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
2788ba4e58ecSGerrit Renker 			val = 8;
27894be929beSAlexey Dobriyan 		else if (val > USHRT_MAX)
27904be929beSAlexey Dobriyan 			val = USHRT_MAX;
2791ba4e58ecSGerrit Renker 		up->pcslen = val;
2792ba4e58ecSGerrit Renker 		up->pcflag |= UDPLITE_SEND_CC;
2793ba4e58ecSGerrit Renker 		break;
2794ba4e58ecSGerrit Renker 
2795ba4e58ecSGerrit Renker 	/* The receiver specifies a minimum checksum coverage value. To make
2796ba4e58ecSGerrit Renker 	 * sense, this should be set to at least 8 (as done below). If zero is
2797ba4e58ecSGerrit Renker 	 * used, this again means full checksum coverage.                     */
2798ba4e58ecSGerrit Renker 	case UDPLITE_RECV_CSCOV:
2799b2bf1e26SWang Chen 		if (!is_udplite)         /* Disable the option on UDP sockets */
2800ba4e58ecSGerrit Renker 			return -ENOPROTOOPT;
2801ba4e58ecSGerrit Renker 		if (val != 0 && val < 8) /* Avoid silly minimal values.       */
2802ba4e58ecSGerrit Renker 			val = 8;
28034be929beSAlexey Dobriyan 		else if (val > USHRT_MAX)
28044be929beSAlexey Dobriyan 			val = USHRT_MAX;
2805ba4e58ecSGerrit Renker 		up->pcrlen = val;
2806ba4e58ecSGerrit Renker 		up->pcflag |= UDPLITE_RECV_CC;
2807ba4e58ecSGerrit Renker 		break;
2808ba4e58ecSGerrit Renker 
28091da177e4SLinus Torvalds 	default:
28101da177e4SLinus Torvalds 		err = -ENOPROTOOPT;
28111da177e4SLinus Torvalds 		break;
28126516c655SStephen Hemminger 	}
28131da177e4SLinus Torvalds 
28141da177e4SLinus Torvalds 	return err;
28151da177e4SLinus Torvalds }
2816c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_setsockopt);
28171da177e4SLinus Torvalds 
2818a7b75c5aSChristoph Hellwig int udp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
2819a7b75c5aSChristoph Hellwig 		   unsigned int optlen)
2820db8dac20SDavid S. Miller {
28218a3854c7SPaolo Abeni 	if (level == SOL_UDP  ||  level == SOL_UDPLITE || level == SOL_SOCKET)
282291ac1ccaSChristoph Hellwig 		return udp_lib_setsockopt(sk, level, optname,
2823a7b75c5aSChristoph Hellwig 					  optval, optlen,
2824db8dac20SDavid S. Miller 					  udp_push_pending_frames);
2825db8dac20SDavid S. Miller 	return ip_setsockopt(sk, level, optname, optval, optlen);
2826db8dac20SDavid S. Miller }
2827db8dac20SDavid S. Miller 
28284c0a6cb0SGerrit Renker int udp_lib_getsockopt(struct sock *sk, int level, int optname,
28291da177e4SLinus Torvalds 		       char __user *optval, int __user *optlen)
28301da177e4SLinus Torvalds {
28311da177e4SLinus Torvalds 	struct udp_sock *up = udp_sk(sk);
28321da177e4SLinus Torvalds 	int val, len;
28331da177e4SLinus Torvalds 
28341da177e4SLinus Torvalds 	if (get_user(len, optlen))
28351da177e4SLinus Torvalds 		return -EFAULT;
28361da177e4SLinus Torvalds 
28371da177e4SLinus Torvalds 	len = min_t(unsigned int, len, sizeof(int));
28381da177e4SLinus Torvalds 
28391da177e4SLinus Torvalds 	if (len < 0)
28401da177e4SLinus Torvalds 		return -EINVAL;
28411da177e4SLinus Torvalds 
28421da177e4SLinus Torvalds 	switch (optname) {
28431da177e4SLinus Torvalds 	case UDP_CORK:
2844a9f59707SEric Dumazet 		val = READ_ONCE(up->corkflag);
28451da177e4SLinus Torvalds 		break;
28461da177e4SLinus Torvalds 
28471da177e4SLinus Torvalds 	case UDP_ENCAP:
28481da177e4SLinus Torvalds 		val = up->encap_type;
28491da177e4SLinus Torvalds 		break;
28501da177e4SLinus Torvalds 
28511c19448cSTom Herbert 	case UDP_NO_CHECK6_TX:
28521c19448cSTom Herbert 		val = up->no_check6_tx;
28531c19448cSTom Herbert 		break;
28541c19448cSTom Herbert 
28551c19448cSTom Herbert 	case UDP_NO_CHECK6_RX:
28561c19448cSTom Herbert 		val = up->no_check6_rx;
28571c19448cSTom Herbert 		break;
28581c19448cSTom Herbert 
2859bec1f6f6SWillem de Bruijn 	case UDP_SEGMENT:
286018a419baSEric Dumazet 		val = READ_ONCE(up->gso_size);
2861bec1f6f6SWillem de Bruijn 		break;
2862bec1f6f6SWillem de Bruijn 
286398184612SNorman Maurer 	case UDP_GRO:
286498184612SNorman Maurer 		val = up->gro_enabled;
286598184612SNorman Maurer 		break;
286698184612SNorman Maurer 
2867ba4e58ecSGerrit Renker 	/* The following two cannot be changed on UDP sockets, the return is
2868ba4e58ecSGerrit Renker 	 * always 0 (which corresponds to the full checksum coverage of UDP). */
2869ba4e58ecSGerrit Renker 	case UDPLITE_SEND_CSCOV:
2870ba4e58ecSGerrit Renker 		val = up->pcslen;
2871ba4e58ecSGerrit Renker 		break;
2872ba4e58ecSGerrit Renker 
2873ba4e58ecSGerrit Renker 	case UDPLITE_RECV_CSCOV:
2874ba4e58ecSGerrit Renker 		val = up->pcrlen;
2875ba4e58ecSGerrit Renker 		break;
2876ba4e58ecSGerrit Renker 
28771da177e4SLinus Torvalds 	default:
28781da177e4SLinus Torvalds 		return -ENOPROTOOPT;
28796516c655SStephen Hemminger 	}
28801da177e4SLinus Torvalds 
28811da177e4SLinus Torvalds 	if (put_user(len, optlen))
28821da177e4SLinus Torvalds 		return -EFAULT;
28831da177e4SLinus Torvalds 	if (copy_to_user(optval, &val, len))
28841da177e4SLinus Torvalds 		return -EFAULT;
28851da177e4SLinus Torvalds 	return 0;
28861da177e4SLinus Torvalds }
2887c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_getsockopt);
28881da177e4SLinus Torvalds 
2889db8dac20SDavid S. Miller int udp_getsockopt(struct sock *sk, int level, int optname,
2890db8dac20SDavid S. Miller 		   char __user *optval, int __user *optlen)
2891db8dac20SDavid S. Miller {
2892db8dac20SDavid S. Miller 	if (level == SOL_UDP  ||  level == SOL_UDPLITE)
2893db8dac20SDavid S. Miller 		return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2894db8dac20SDavid S. Miller 	return ip_getsockopt(sk, level, optname, optval, optlen);
2895db8dac20SDavid S. Miller }
2896db8dac20SDavid S. Miller 
28971da177e4SLinus Torvalds /**
28981da177e4SLinus Torvalds  * 	udp_poll - wait for a UDP event.
28993628e3cbSAndrew Lunn  *	@file: - file struct
29003628e3cbSAndrew Lunn  *	@sock: - socket
29013628e3cbSAndrew Lunn  *	@wait: - poll table
29021da177e4SLinus Torvalds  *
29031da177e4SLinus Torvalds  *	This is same as datagram poll, except for the special case of
29041da177e4SLinus Torvalds  *	blocking sockets. If application is using a blocking fd
29051da177e4SLinus Torvalds  *	and a packet with checksum error is in the queue;
29061da177e4SLinus Torvalds  *	then it could get return from select indicating data available
29071da177e4SLinus Torvalds  *	but then block when reading it. Add special case code
29081da177e4SLinus Torvalds  *	to work around these arguably broken applications.
29091da177e4SLinus Torvalds  */
2910a11e1d43SLinus Torvalds __poll_t udp_poll(struct file *file, struct socket *sock, poll_table *wait)
29111da177e4SLinus Torvalds {
2912a11e1d43SLinus Torvalds 	__poll_t mask = datagram_poll(file, sock, wait);
29131da177e4SLinus Torvalds 	struct sock *sk = sock->sk;
29141da177e4SLinus Torvalds 
29153ef7cf57SEric Dumazet 	if (!skb_queue_empty_lockless(&udp_sk(sk)->reader_queue))
2916a9a08845SLinus Torvalds 		mask |= EPOLLIN | EPOLLRDNORM;
29172276f58aSPaolo Abeni 
29181da177e4SLinus Torvalds 	/* Check for false positives due to checksum errors */
2919a11e1d43SLinus Torvalds 	if ((mask & EPOLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
2920e83c6744SEric Dumazet 	    !(sk->sk_shutdown & RCV_SHUTDOWN) && first_packet_length(sk) == -1)
2921a9a08845SLinus Torvalds 		mask &= ~(EPOLLIN | EPOLLRDNORM);
29221da177e4SLinus Torvalds 
2923af493388SCong Wang 	/* psock ingress_msg queue should not contain any bad checksum frames */
2924af493388SCong Wang 	if (sk_is_readable(sk))
2925af493388SCong Wang 		mask |= EPOLLIN | EPOLLRDNORM;
29261da177e4SLinus Torvalds 	return mask;
29271da177e4SLinus Torvalds 
29281da177e4SLinus Torvalds }
2929a11e1d43SLinus Torvalds EXPORT_SYMBOL(udp_poll);
29301da177e4SLinus Torvalds 
29315d77dca8SDavid Ahern int udp_abort(struct sock *sk, int err)
29325d77dca8SDavid Ahern {
29335d77dca8SDavid Ahern 	lock_sock(sk);
29345d77dca8SDavid Ahern 
2935a8b897c7SPaolo Abeni 	/* udp{v6}_destroy_sock() sets it under the sk lock, avoid racing
2936a8b897c7SPaolo Abeni 	 * with close()
2937a8b897c7SPaolo Abeni 	 */
2938a8b897c7SPaolo Abeni 	if (sock_flag(sk, SOCK_DEAD))
2939a8b897c7SPaolo Abeni 		goto out;
2940a8b897c7SPaolo Abeni 
29415d77dca8SDavid Ahern 	sk->sk_err = err;
2942e3ae2365SAlexander Aring 	sk_error_report(sk);
2943286c72deSEric Dumazet 	__udp_disconnect(sk, 0);
29445d77dca8SDavid Ahern 
2945a8b897c7SPaolo Abeni out:
29465d77dca8SDavid Ahern 	release_sock(sk);
29475d77dca8SDavid Ahern 
29485d77dca8SDavid Ahern 	return 0;
29495d77dca8SDavid Ahern }
29505d77dca8SDavid Ahern EXPORT_SYMBOL_GPL(udp_abort);
29515d77dca8SDavid Ahern 
2952db8dac20SDavid S. Miller struct proto udp_prot = {
2953db8dac20SDavid S. Miller 	.name			= "UDP",
2954db8dac20SDavid S. Miller 	.owner			= THIS_MODULE,
2955db8dac20SDavid S. Miller 	.close			= udp_lib_close,
2956d74bad4eSAndrey Ignatov 	.pre_connect		= udp_pre_connect,
2957db8dac20SDavid S. Miller 	.connect		= ip4_datagram_connect,
2958db8dac20SDavid S. Miller 	.disconnect		= udp_disconnect,
2959db8dac20SDavid S. Miller 	.ioctl			= udp_ioctl,
2960850cbaddSPaolo Abeni 	.init			= udp_init_sock,
2961db8dac20SDavid S. Miller 	.destroy		= udp_destroy_sock,
2962db8dac20SDavid S. Miller 	.setsockopt		= udp_setsockopt,
2963db8dac20SDavid S. Miller 	.getsockopt		= udp_getsockopt,
2964db8dac20SDavid S. Miller 	.sendmsg		= udp_sendmsg,
2965db8dac20SDavid S. Miller 	.recvmsg		= udp_recvmsg,
2966db8dac20SDavid S. Miller 	.sendpage		= udp_sendpage,
29678141ed9fSSteffen Klassert 	.release_cb		= ip4_datagram_release_cb,
2968db8dac20SDavid S. Miller 	.hash			= udp_lib_hash,
2969db8dac20SDavid S. Miller 	.unhash			= udp_lib_unhash,
2970719f8358SEric Dumazet 	.rehash			= udp_v4_rehash,
2971db8dac20SDavid S. Miller 	.get_port		= udp_v4_get_port,
297291a760b2SMenglong Dong 	.put_port		= udp_lib_unhash,
29738a59f9d1SCong Wang #ifdef CONFIG_BPF_SYSCALL
29748a59f9d1SCong Wang 	.psock_update_sk_prot	= udp_bpf_update_proto,
29758a59f9d1SCong Wang #endif
2976db8dac20SDavid S. Miller 	.memory_allocated	= &udp_memory_allocated,
29770defbb0aSEric Dumazet 	.per_cpu_fw_alloc	= &udp_memory_per_cpu_fw_alloc,
29780defbb0aSEric Dumazet 
2979db8dac20SDavid S. Miller 	.sysctl_mem		= sysctl_udp_mem,
29801e802951STonghao Zhang 	.sysctl_wmem_offset	= offsetof(struct net, ipv4.sysctl_udp_wmem_min),
29811e802951STonghao Zhang 	.sysctl_rmem_offset	= offsetof(struct net, ipv4.sysctl_udp_rmem_min),
2982db8dac20SDavid S. Miller 	.obj_size		= sizeof(struct udp_sock),
298367fb4330SKuniyuki Iwashima 	.h.udp_table		= NULL,
29845d77dca8SDavid Ahern 	.diag_destroy		= udp_abort,
2985db8dac20SDavid S. Miller };
2986c482c568SEric Dumazet EXPORT_SYMBOL(udp_prot);
29871da177e4SLinus Torvalds 
29881da177e4SLinus Torvalds /* ------------------------------------------------------------------------ */
29891da177e4SLinus Torvalds #ifdef CONFIG_PROC_FS
29901da177e4SLinus Torvalds 
2991478aee5dSKuniyuki Iwashima static struct udp_table *udp_get_table_afinfo(struct udp_seq_afinfo *afinfo,
2992478aee5dSKuniyuki Iwashima 					      struct net *net)
2993478aee5dSKuniyuki Iwashima {
2994478aee5dSKuniyuki Iwashima 	return afinfo->udp_table ? : net->ipv4.udp_table;
2995478aee5dSKuniyuki Iwashima }
2996478aee5dSKuniyuki Iwashima 
2997645ca708SEric Dumazet static struct sock *udp_get_first(struct seq_file *seq, int start)
29981da177e4SLinus Torvalds {
29991da177e4SLinus Torvalds 	struct udp_iter_state *state = seq->private;
30006f191efeSDenis V. Lunev 	struct net *net = seq_file_net(seq);
3001919dfa0bSKuniyuki Iwashima 	struct udp_seq_afinfo *afinfo;
3002478aee5dSKuniyuki Iwashima 	struct udp_table *udptable;
3003919dfa0bSKuniyuki Iwashima 	struct sock *sk;
30041da177e4SLinus Torvalds 
30059e8ca27aSYonghong Song 	if (state->bpf_seq_afinfo)
30069e8ca27aSYonghong Song 		afinfo = state->bpf_seq_afinfo;
30079e8ca27aSYonghong Song 	else
3008359745d7SMuchun Song 		afinfo = pde_data(file_inode(seq->file));
30099e8ca27aSYonghong Song 
3010478aee5dSKuniyuki Iwashima 	udptable = udp_get_table_afinfo(afinfo, net);
3011478aee5dSKuniyuki Iwashima 
3012478aee5dSKuniyuki Iwashima 	for (state->bucket = start; state->bucket <= udptable->mask;
3013f86dcc5aSEric Dumazet 	     ++state->bucket) {
3014478aee5dSKuniyuki Iwashima 		struct udp_hslot *hslot = &udptable->hash[state->bucket];
3015f86dcc5aSEric Dumazet 
3016ca065d0cSEric Dumazet 		if (hlist_empty(&hslot->head))
3017f86dcc5aSEric Dumazet 			continue;
3018f86dcc5aSEric Dumazet 
3019645ca708SEric Dumazet 		spin_lock_bh(&hslot->lock);
3020ca065d0cSEric Dumazet 		sk_for_each(sk, &hslot->head) {
3021878628fbSYOSHIFUJI Hideaki 			if (!net_eq(sock_net(sk), net))
3022a91275efSDaniel Lezcano 				continue;
30239e8ca27aSYonghong Song 			if (afinfo->family == AF_UNSPEC ||
30249e8ca27aSYonghong Song 			    sk->sk_family == afinfo->family)
30251da177e4SLinus Torvalds 				goto found;
30261da177e4SLinus Torvalds 		}
3027645ca708SEric Dumazet 		spin_unlock_bh(&hslot->lock);
30281da177e4SLinus Torvalds 	}
30291da177e4SLinus Torvalds 	sk = NULL;
30301da177e4SLinus Torvalds found:
30311da177e4SLinus Torvalds 	return sk;
30321da177e4SLinus Torvalds }
30331da177e4SLinus Torvalds 
30341da177e4SLinus Torvalds static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
30351da177e4SLinus Torvalds {
30361da177e4SLinus Torvalds 	struct udp_iter_state *state = seq->private;
30376f191efeSDenis V. Lunev 	struct net *net = seq_file_net(seq);
3038919dfa0bSKuniyuki Iwashima 	struct udp_seq_afinfo *afinfo;
3039478aee5dSKuniyuki Iwashima 	struct udp_table *udptable;
30401da177e4SLinus Torvalds 
30419e8ca27aSYonghong Song 	if (state->bpf_seq_afinfo)
30429e8ca27aSYonghong Song 		afinfo = state->bpf_seq_afinfo;
30439e8ca27aSYonghong Song 	else
3044359745d7SMuchun Song 		afinfo = pde_data(file_inode(seq->file));
30459e8ca27aSYonghong Song 
30461da177e4SLinus Torvalds 	do {
3047ca065d0cSEric Dumazet 		sk = sk_next(sk);
30489e8ca27aSYonghong Song 	} while (sk && (!net_eq(sock_net(sk), net) ||
30499e8ca27aSYonghong Song 			(afinfo->family != AF_UNSPEC &&
30509e8ca27aSYonghong Song 			 sk->sk_family != afinfo->family)));
30511da177e4SLinus Torvalds 
3052645ca708SEric Dumazet 	if (!sk) {
3053478aee5dSKuniyuki Iwashima 		udptable = udp_get_table_afinfo(afinfo, net);
3054478aee5dSKuniyuki Iwashima 
3055478aee5dSKuniyuki Iwashima 		if (state->bucket <= udptable->mask)
3056478aee5dSKuniyuki Iwashima 			spin_unlock_bh(&udptable->hash[state->bucket].lock);
3057478aee5dSKuniyuki Iwashima 
3058645ca708SEric Dumazet 		return udp_get_first(seq, state->bucket + 1);
30591da177e4SLinus Torvalds 	}
30601da177e4SLinus Torvalds 	return sk;
30611da177e4SLinus Torvalds }
30621da177e4SLinus Torvalds 
30631da177e4SLinus Torvalds static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
30641da177e4SLinus Torvalds {
3065645ca708SEric Dumazet 	struct sock *sk = udp_get_first(seq, 0);
30661da177e4SLinus Torvalds 
30671da177e4SLinus Torvalds 	if (sk)
30681da177e4SLinus Torvalds 		while (pos && (sk = udp_get_next(seq, sk)) != NULL)
30691da177e4SLinus Torvalds 			--pos;
30701da177e4SLinus Torvalds 	return pos ? NULL : sk;
30711da177e4SLinus Torvalds }
30721da177e4SLinus Torvalds 
3073a3d2599bSChristoph Hellwig void *udp_seq_start(struct seq_file *seq, loff_t *pos)
30741da177e4SLinus Torvalds {
307530842f29SVitaly Mayatskikh 	struct udp_iter_state *state = seq->private;
3076f86dcc5aSEric Dumazet 	state->bucket = MAX_UDP_PORTS;
307730842f29SVitaly Mayatskikh 
3078b50660f1SYOSHIFUJI Hideaki 	return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
30791da177e4SLinus Torvalds }
3080a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_start);
30811da177e4SLinus Torvalds 
3082a3d2599bSChristoph Hellwig void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
30831da177e4SLinus Torvalds {
30841da177e4SLinus Torvalds 	struct sock *sk;
30851da177e4SLinus Torvalds 
3086b50660f1SYOSHIFUJI Hideaki 	if (v == SEQ_START_TOKEN)
30871da177e4SLinus Torvalds 		sk = udp_get_idx(seq, 0);
30881da177e4SLinus Torvalds 	else
30891da177e4SLinus Torvalds 		sk = udp_get_next(seq, v);
30901da177e4SLinus Torvalds 
30911da177e4SLinus Torvalds 	++*pos;
30921da177e4SLinus Torvalds 	return sk;
30931da177e4SLinus Torvalds }
3094a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_next);
30951da177e4SLinus Torvalds 
3096a3d2599bSChristoph Hellwig void udp_seq_stop(struct seq_file *seq, void *v)
30971da177e4SLinus Torvalds {
3098645ca708SEric Dumazet 	struct udp_iter_state *state = seq->private;
3099919dfa0bSKuniyuki Iwashima 	struct udp_seq_afinfo *afinfo;
3100478aee5dSKuniyuki Iwashima 	struct udp_table *udptable;
3101645ca708SEric Dumazet 
31029e8ca27aSYonghong Song 	if (state->bpf_seq_afinfo)
31039e8ca27aSYonghong Song 		afinfo = state->bpf_seq_afinfo;
31049e8ca27aSYonghong Song 	else
3105359745d7SMuchun Song 		afinfo = pde_data(file_inode(seq->file));
31069e8ca27aSYonghong Song 
3107478aee5dSKuniyuki Iwashima 	udptable = udp_get_table_afinfo(afinfo, seq_file_net(seq));
3108478aee5dSKuniyuki Iwashima 
3109478aee5dSKuniyuki Iwashima 	if (state->bucket <= udptable->mask)
3110478aee5dSKuniyuki Iwashima 		spin_unlock_bh(&udptable->hash[state->bucket].lock);
31111da177e4SLinus Torvalds }
3112a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_stop);
3113db8dac20SDavid S. Miller 
3114db8dac20SDavid S. Miller /* ------------------------------------------------------------------------ */
31155e659e4cSPavel Emelyanov static void udp4_format_sock(struct sock *sp, struct seq_file *f,
3116652586dfSTetsuo Handa 		int bucket)
3117db8dac20SDavid S. Miller {
3118db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sp);
3119c720c7e8SEric Dumazet 	__be32 dest = inet->inet_daddr;
3120c720c7e8SEric Dumazet 	__be32 src  = inet->inet_rcv_saddr;
3121c720c7e8SEric Dumazet 	__u16 destp	  = ntohs(inet->inet_dport);
3122c720c7e8SEric Dumazet 	__u16 srcp	  = ntohs(inet->inet_sport);
3123db8dac20SDavid S. Miller 
3124f86dcc5aSEric Dumazet 	seq_printf(f, "%5d: %08X:%04X %08X:%04X"
3125ea9a0379SPatrick Talbert 		" %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %u",
3126db8dac20SDavid S. Miller 		bucket, src, srcp, dest, destp, sp->sk_state,
312731e6d363SEric Dumazet 		sk_wmem_alloc_get(sp),
31286c206b20SPaolo Abeni 		udp_rqueue_get(sp),
3129a7cb5a49SEric W. Biederman 		0, 0L, 0,
3130a7cb5a49SEric W. Biederman 		from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
3131a7cb5a49SEric W. Biederman 		0, sock_i_ino(sp),
313241c6d650SReshetova, Elena 		refcount_read(&sp->sk_refcnt), sp,
3133652586dfSTetsuo Handa 		atomic_read(&sp->sk_drops));
3134db8dac20SDavid S. Miller }
3135db8dac20SDavid S. Miller 
3136db8dac20SDavid S. Miller int udp4_seq_show(struct seq_file *seq, void *v)
3137db8dac20SDavid S. Miller {
3138652586dfSTetsuo Handa 	seq_setwidth(seq, 127);
3139db8dac20SDavid S. Miller 	if (v == SEQ_START_TOKEN)
3140652586dfSTetsuo Handa 		seq_puts(seq, "   sl  local_address rem_address   st tx_queue "
3141db8dac20SDavid S. Miller 			   "rx_queue tr tm->when retrnsmt   uid  timeout "
3142cb61cb9bSEric Dumazet 			   "inode ref pointer drops");
3143db8dac20SDavid S. Miller 	else {
3144db8dac20SDavid S. Miller 		struct udp_iter_state *state = seq->private;
3145db8dac20SDavid S. Miller 
3146652586dfSTetsuo Handa 		udp4_format_sock(v, seq, state->bucket);
3147db8dac20SDavid S. Miller 	}
3148652586dfSTetsuo Handa 	seq_pad(seq, '\n');
3149db8dac20SDavid S. Miller 	return 0;
3150db8dac20SDavid S. Miller }
3151db8dac20SDavid S. Miller 
31525788b3a0SYonghong Song #ifdef CONFIG_BPF_SYSCALL
31535788b3a0SYonghong Song struct bpf_iter__udp {
31545788b3a0SYonghong Song 	__bpf_md_ptr(struct bpf_iter_meta *, meta);
31555788b3a0SYonghong Song 	__bpf_md_ptr(struct udp_sock *, udp_sk);
31565788b3a0SYonghong Song 	uid_t uid __aligned(8);
31575788b3a0SYonghong Song 	int bucket __aligned(8);
31585788b3a0SYonghong Song };
31595788b3a0SYonghong Song 
31605788b3a0SYonghong Song static int udp_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
31615788b3a0SYonghong Song 			     struct udp_sock *udp_sk, uid_t uid, int bucket)
31625788b3a0SYonghong Song {
31635788b3a0SYonghong Song 	struct bpf_iter__udp ctx;
31645788b3a0SYonghong Song 
31655788b3a0SYonghong Song 	meta->seq_num--;  /* skip SEQ_START_TOKEN */
31665788b3a0SYonghong Song 	ctx.meta = meta;
31675788b3a0SYonghong Song 	ctx.udp_sk = udp_sk;
31685788b3a0SYonghong Song 	ctx.uid = uid;
31695788b3a0SYonghong Song 	ctx.bucket = bucket;
31705788b3a0SYonghong Song 	return bpf_iter_run_prog(prog, &ctx);
31715788b3a0SYonghong Song }
31725788b3a0SYonghong Song 
31735788b3a0SYonghong Song static int bpf_iter_udp_seq_show(struct seq_file *seq, void *v)
31745788b3a0SYonghong Song {
31755788b3a0SYonghong Song 	struct udp_iter_state *state = seq->private;
31765788b3a0SYonghong Song 	struct bpf_iter_meta meta;
31775788b3a0SYonghong Song 	struct bpf_prog *prog;
31785788b3a0SYonghong Song 	struct sock *sk = v;
31795788b3a0SYonghong Song 	uid_t uid;
31805788b3a0SYonghong Song 
31815788b3a0SYonghong Song 	if (v == SEQ_START_TOKEN)
31825788b3a0SYonghong Song 		return 0;
31835788b3a0SYonghong Song 
31845788b3a0SYonghong Song 	uid = from_kuid_munged(seq_user_ns(seq), sock_i_uid(sk));
31855788b3a0SYonghong Song 	meta.seq = seq;
31865788b3a0SYonghong Song 	prog = bpf_iter_get_info(&meta, false);
31875788b3a0SYonghong Song 	return udp_prog_seq_show(prog, &meta, v, uid, state->bucket);
31885788b3a0SYonghong Song }
31895788b3a0SYonghong Song 
31905788b3a0SYonghong Song static void bpf_iter_udp_seq_stop(struct seq_file *seq, void *v)
31915788b3a0SYonghong Song {
31925788b3a0SYonghong Song 	struct bpf_iter_meta meta;
31935788b3a0SYonghong Song 	struct bpf_prog *prog;
31945788b3a0SYonghong Song 
31955788b3a0SYonghong Song 	if (!v) {
31965788b3a0SYonghong Song 		meta.seq = seq;
31975788b3a0SYonghong Song 		prog = bpf_iter_get_info(&meta, true);
31985788b3a0SYonghong Song 		if (prog)
31995788b3a0SYonghong Song 			(void)udp_prog_seq_show(prog, &meta, v, 0, 0);
32005788b3a0SYonghong Song 	}
32015788b3a0SYonghong Song 
32025788b3a0SYonghong Song 	udp_seq_stop(seq, v);
32035788b3a0SYonghong Song }
32045788b3a0SYonghong Song 
32055788b3a0SYonghong Song static const struct seq_operations bpf_iter_udp_seq_ops = {
32065788b3a0SYonghong Song 	.start		= udp_seq_start,
32075788b3a0SYonghong Song 	.next		= udp_seq_next,
32085788b3a0SYonghong Song 	.stop		= bpf_iter_udp_seq_stop,
32095788b3a0SYonghong Song 	.show		= bpf_iter_udp_seq_show,
32105788b3a0SYonghong Song };
32115788b3a0SYonghong Song #endif
32125788b3a0SYonghong Song 
3213c3506372SChristoph Hellwig const struct seq_operations udp_seq_ops = {
3214a3d2599bSChristoph Hellwig 	.start		= udp_seq_start,
3215a3d2599bSChristoph Hellwig 	.next		= udp_seq_next,
3216a3d2599bSChristoph Hellwig 	.stop		= udp_seq_stop,
3217a3d2599bSChristoph Hellwig 	.show		= udp4_seq_show,
3218a3d2599bSChristoph Hellwig };
3219c3506372SChristoph Hellwig EXPORT_SYMBOL(udp_seq_ops);
322073cb88ecSArjan van de Ven 
3221db8dac20SDavid S. Miller static struct udp_seq_afinfo udp4_seq_afinfo = {
3222db8dac20SDavid S. Miller 	.family		= AF_INET,
3223478aee5dSKuniyuki Iwashima 	.udp_table	= NULL,
3224db8dac20SDavid S. Miller };
3225db8dac20SDavid S. Miller 
32262c8c1e72SAlexey Dobriyan static int __net_init udp4_proc_init_net(struct net *net)
322715439febSPavel Emelyanov {
3228c3506372SChristoph Hellwig 	if (!proc_create_net_data("udp", 0444, net->proc_net, &udp_seq_ops,
3229c3506372SChristoph Hellwig 			sizeof(struct udp_iter_state), &udp4_seq_afinfo))
3230a3d2599bSChristoph Hellwig 		return -ENOMEM;
3231a3d2599bSChristoph Hellwig 	return 0;
323215439febSPavel Emelyanov }
323315439febSPavel Emelyanov 
32342c8c1e72SAlexey Dobriyan static void __net_exit udp4_proc_exit_net(struct net *net)
323515439febSPavel Emelyanov {
3236a3d2599bSChristoph Hellwig 	remove_proc_entry("udp", net->proc_net);
323715439febSPavel Emelyanov }
323815439febSPavel Emelyanov 
323915439febSPavel Emelyanov static struct pernet_operations udp4_net_ops = {
324015439febSPavel Emelyanov 	.init = udp4_proc_init_net,
324115439febSPavel Emelyanov 	.exit = udp4_proc_exit_net,
324215439febSPavel Emelyanov };
324315439febSPavel Emelyanov 
3244db8dac20SDavid S. Miller int __init udp4_proc_init(void)
3245db8dac20SDavid S. Miller {
324615439febSPavel Emelyanov 	return register_pernet_subsys(&udp4_net_ops);
3247db8dac20SDavid S. Miller }
3248db8dac20SDavid S. Miller 
3249db8dac20SDavid S. Miller void udp4_proc_exit(void)
3250db8dac20SDavid S. Miller {
325115439febSPavel Emelyanov 	unregister_pernet_subsys(&udp4_net_ops);
3252db8dac20SDavid S. Miller }
32531da177e4SLinus Torvalds #endif /* CONFIG_PROC_FS */
32541da177e4SLinus Torvalds 
3255f86dcc5aSEric Dumazet static __initdata unsigned long uhash_entries;
3256f86dcc5aSEric Dumazet static int __init set_uhash_entries(char *str)
3257645ca708SEric Dumazet {
3258413c27d8SEldad Zack 	ssize_t ret;
3259413c27d8SEldad Zack 
3260f86dcc5aSEric Dumazet 	if (!str)
3261f86dcc5aSEric Dumazet 		return 0;
3262413c27d8SEldad Zack 
3263413c27d8SEldad Zack 	ret = kstrtoul(str, 0, &uhash_entries);
3264413c27d8SEldad Zack 	if (ret)
3265413c27d8SEldad Zack 		return 0;
3266413c27d8SEldad Zack 
3267f86dcc5aSEric Dumazet 	if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
3268f86dcc5aSEric Dumazet 		uhash_entries = UDP_HTABLE_SIZE_MIN;
3269f86dcc5aSEric Dumazet 	return 1;
3270f86dcc5aSEric Dumazet }
3271f86dcc5aSEric Dumazet __setup("uhash_entries=", set_uhash_entries);
3272645ca708SEric Dumazet 
3273f86dcc5aSEric Dumazet void __init udp_table_init(struct udp_table *table, const char *name)
3274f86dcc5aSEric Dumazet {
3275f86dcc5aSEric Dumazet 	unsigned int i;
3276f86dcc5aSEric Dumazet 
3277f86dcc5aSEric Dumazet 	table->hash = alloc_large_system_hash(name,
3278512615b6SEric Dumazet 					      2 * sizeof(struct udp_hslot),
3279f86dcc5aSEric Dumazet 					      uhash_entries,
3280f86dcc5aSEric Dumazet 					      21, /* one slot per 2 MB */
3281f86dcc5aSEric Dumazet 					      0,
3282f86dcc5aSEric Dumazet 					      &table->log,
3283f86dcc5aSEric Dumazet 					      &table->mask,
328431fe62b9STim Bird 					      UDP_HTABLE_SIZE_MIN,
32859804985bSKuniyuki Iwashima 					      UDP_HTABLE_SIZE_MAX);
328631fe62b9STim Bird 
3287512615b6SEric Dumazet 	table->hash2 = table->hash + (table->mask + 1);
3288f86dcc5aSEric Dumazet 	for (i = 0; i <= table->mask; i++) {
3289ca065d0cSEric Dumazet 		INIT_HLIST_HEAD(&table->hash[i].head);
3290fdcc8aa9SEric Dumazet 		table->hash[i].count = 0;
3291645ca708SEric Dumazet 		spin_lock_init(&table->hash[i].lock);
3292645ca708SEric Dumazet 	}
3293512615b6SEric Dumazet 	for (i = 0; i <= table->mask; i++) {
3294ca065d0cSEric Dumazet 		INIT_HLIST_HEAD(&table->hash2[i].head);
3295512615b6SEric Dumazet 		table->hash2[i].count = 0;
3296512615b6SEric Dumazet 		spin_lock_init(&table->hash2[i].lock);
3297512615b6SEric Dumazet 	}
3298645ca708SEric Dumazet }
3299645ca708SEric Dumazet 
3300723b8e46STom Herbert u32 udp_flow_hashrnd(void)
3301723b8e46STom Herbert {
3302723b8e46STom Herbert 	static u32 hashrnd __read_mostly;
3303723b8e46STom Herbert 
3304723b8e46STom Herbert 	net_get_random_once(&hashrnd, sizeof(hashrnd));
3305723b8e46STom Herbert 
3306723b8e46STom Herbert 	return hashrnd;
3307723b8e46STom Herbert }
3308723b8e46STom Herbert EXPORT_SYMBOL(udp_flow_hashrnd);
3309723b8e46STom Herbert 
33109804985bSKuniyuki Iwashima static void __net_init udp_sysctl_init(struct net *net)
33111e802951STonghao Zhang {
3312100fdd1fSEric Dumazet 	net->ipv4.sysctl_udp_rmem_min = PAGE_SIZE;
3313100fdd1fSEric Dumazet 	net->ipv4.sysctl_udp_wmem_min = PAGE_SIZE;
33141e802951STonghao Zhang 
33151e802951STonghao Zhang #ifdef CONFIG_NET_L3_MASTER_DEV
33161e802951STonghao Zhang 	net->ipv4.sysctl_udp_l3mdev_accept = 0;
33171e802951STonghao Zhang #endif
33189804985bSKuniyuki Iwashima }
33199804985bSKuniyuki Iwashima 
33209804985bSKuniyuki Iwashima static struct udp_table __net_init *udp_pernet_table_alloc(unsigned int hash_entries)
33219804985bSKuniyuki Iwashima {
33229804985bSKuniyuki Iwashima 	struct udp_table *udptable;
33239804985bSKuniyuki Iwashima 	int i;
33249804985bSKuniyuki Iwashima 
33259804985bSKuniyuki Iwashima 	udptable = kmalloc(sizeof(*udptable), GFP_KERNEL);
33269804985bSKuniyuki Iwashima 	if (!udptable)
33279804985bSKuniyuki Iwashima 		goto out;
33289804985bSKuniyuki Iwashima 
33299804985bSKuniyuki Iwashima 	udptable->hash = vmalloc_huge(hash_entries * 2 * sizeof(struct udp_hslot),
33309804985bSKuniyuki Iwashima 				      GFP_KERNEL_ACCOUNT);
33319804985bSKuniyuki Iwashima 	if (!udptable->hash)
33329804985bSKuniyuki Iwashima 		goto free_table;
33339804985bSKuniyuki Iwashima 
33349804985bSKuniyuki Iwashima 	udptable->hash2 = udptable->hash + hash_entries;
33359804985bSKuniyuki Iwashima 	udptable->mask = hash_entries - 1;
33369804985bSKuniyuki Iwashima 	udptable->log = ilog2(hash_entries);
33379804985bSKuniyuki Iwashima 
33389804985bSKuniyuki Iwashima 	for (i = 0; i < hash_entries; i++) {
33399804985bSKuniyuki Iwashima 		INIT_HLIST_HEAD(&udptable->hash[i].head);
33409804985bSKuniyuki Iwashima 		udptable->hash[i].count = 0;
33419804985bSKuniyuki Iwashima 		spin_lock_init(&udptable->hash[i].lock);
33429804985bSKuniyuki Iwashima 
33439804985bSKuniyuki Iwashima 		INIT_HLIST_HEAD(&udptable->hash2[i].head);
33449804985bSKuniyuki Iwashima 		udptable->hash2[i].count = 0;
33459804985bSKuniyuki Iwashima 		spin_lock_init(&udptable->hash2[i].lock);
33469804985bSKuniyuki Iwashima 	}
33479804985bSKuniyuki Iwashima 
33489804985bSKuniyuki Iwashima 	return udptable;
33499804985bSKuniyuki Iwashima 
33509804985bSKuniyuki Iwashima free_table:
33519804985bSKuniyuki Iwashima 	kfree(udptable);
33529804985bSKuniyuki Iwashima out:
33539804985bSKuniyuki Iwashima 	return NULL;
33549804985bSKuniyuki Iwashima }
33559804985bSKuniyuki Iwashima 
33569804985bSKuniyuki Iwashima static void __net_exit udp_pernet_table_free(struct net *net)
33579804985bSKuniyuki Iwashima {
33589804985bSKuniyuki Iwashima 	struct udp_table *udptable = net->ipv4.udp_table;
33599804985bSKuniyuki Iwashima 
33609804985bSKuniyuki Iwashima 	if (udptable == &udp_table)
33619804985bSKuniyuki Iwashima 		return;
33629804985bSKuniyuki Iwashima 
33639804985bSKuniyuki Iwashima 	kvfree(udptable->hash);
33649804985bSKuniyuki Iwashima 	kfree(udptable);
33659804985bSKuniyuki Iwashima }
33669804985bSKuniyuki Iwashima 
33679804985bSKuniyuki Iwashima static void __net_init udp_set_table(struct net *net)
33689804985bSKuniyuki Iwashima {
33699804985bSKuniyuki Iwashima 	struct udp_table *udptable;
33709804985bSKuniyuki Iwashima 	unsigned int hash_entries;
33719804985bSKuniyuki Iwashima 	struct net *old_net;
33729804985bSKuniyuki Iwashima 
33739804985bSKuniyuki Iwashima 	if (net_eq(net, &init_net))
33749804985bSKuniyuki Iwashima 		goto fallback;
33759804985bSKuniyuki Iwashima 
33769804985bSKuniyuki Iwashima 	old_net = current->nsproxy->net_ns;
33779804985bSKuniyuki Iwashima 	hash_entries = READ_ONCE(old_net->ipv4.sysctl_udp_child_hash_entries);
33789804985bSKuniyuki Iwashima 	if (!hash_entries)
33799804985bSKuniyuki Iwashima 		goto fallback;
33809804985bSKuniyuki Iwashima 
33819804985bSKuniyuki Iwashima 	/* Set min to keep the bitmap on stack in udp_lib_get_port() */
33829804985bSKuniyuki Iwashima 	if (hash_entries < UDP_HTABLE_SIZE_MIN_PERNET)
33839804985bSKuniyuki Iwashima 		hash_entries = UDP_HTABLE_SIZE_MIN_PERNET;
33849804985bSKuniyuki Iwashima 	else
33859804985bSKuniyuki Iwashima 		hash_entries = roundup_pow_of_two(hash_entries);
33869804985bSKuniyuki Iwashima 
33879804985bSKuniyuki Iwashima 	udptable = udp_pernet_table_alloc(hash_entries);
33889804985bSKuniyuki Iwashima 	if (udptable) {
33899804985bSKuniyuki Iwashima 		net->ipv4.udp_table = udptable;
33909804985bSKuniyuki Iwashima 	} else {
33919804985bSKuniyuki Iwashima 		pr_warn("Failed to allocate UDP hash table (entries: %u) "
33929804985bSKuniyuki Iwashima 			"for a netns, fallback to the global one\n",
33939804985bSKuniyuki Iwashima 			hash_entries);
33949804985bSKuniyuki Iwashima fallback:
33959804985bSKuniyuki Iwashima 		net->ipv4.udp_table = &udp_table;
33969804985bSKuniyuki Iwashima 	}
33979804985bSKuniyuki Iwashima }
33989804985bSKuniyuki Iwashima 
33999804985bSKuniyuki Iwashima static int __net_init udp_pernet_init(struct net *net)
34009804985bSKuniyuki Iwashima {
34019804985bSKuniyuki Iwashima 	udp_sysctl_init(net);
34029804985bSKuniyuki Iwashima 	udp_set_table(net);
34031e802951STonghao Zhang 
34041e802951STonghao Zhang 	return 0;
34051e802951STonghao Zhang }
34061e802951STonghao Zhang 
34079804985bSKuniyuki Iwashima static void __net_exit udp_pernet_exit(struct net *net)
34089804985bSKuniyuki Iwashima {
34099804985bSKuniyuki Iwashima 	udp_pernet_table_free(net);
34109804985bSKuniyuki Iwashima }
34119804985bSKuniyuki Iwashima 
34121e802951STonghao Zhang static struct pernet_operations __net_initdata udp_sysctl_ops = {
34139804985bSKuniyuki Iwashima 	.init	= udp_pernet_init,
34149804985bSKuniyuki Iwashima 	.exit	= udp_pernet_exit,
34151e802951STonghao Zhang };
34161e802951STonghao Zhang 
34175788b3a0SYonghong Song #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
34185788b3a0SYonghong Song DEFINE_BPF_ITER_FUNC(udp, struct bpf_iter_meta *meta,
34195788b3a0SYonghong Song 		     struct udp_sock *udp_sk, uid_t uid, int bucket)
34205788b3a0SYonghong Song 
3421f9c79272SYonghong Song static int bpf_iter_init_udp(void *priv_data, struct bpf_iter_aux_info *aux)
34225788b3a0SYonghong Song {
34235788b3a0SYonghong Song 	struct udp_iter_state *st = priv_data;
34245788b3a0SYonghong Song 	struct udp_seq_afinfo *afinfo;
34255788b3a0SYonghong Song 	int ret;
34265788b3a0SYonghong Song 
34275788b3a0SYonghong Song 	afinfo = kmalloc(sizeof(*afinfo), GFP_USER | __GFP_NOWARN);
34285788b3a0SYonghong Song 	if (!afinfo)
34295788b3a0SYonghong Song 		return -ENOMEM;
34305788b3a0SYonghong Song 
34315788b3a0SYonghong Song 	afinfo->family = AF_UNSPEC;
3432478aee5dSKuniyuki Iwashima 	afinfo->udp_table = NULL;
34335788b3a0SYonghong Song 	st->bpf_seq_afinfo = afinfo;
3434f9c79272SYonghong Song 	ret = bpf_iter_init_seq_net(priv_data, aux);
34355788b3a0SYonghong Song 	if (ret)
34365788b3a0SYonghong Song 		kfree(afinfo);
34375788b3a0SYonghong Song 	return ret;
34385788b3a0SYonghong Song }
34395788b3a0SYonghong Song 
34405788b3a0SYonghong Song static void bpf_iter_fini_udp(void *priv_data)
34415788b3a0SYonghong Song {
34425788b3a0SYonghong Song 	struct udp_iter_state *st = priv_data;
34435788b3a0SYonghong Song 
34445788b3a0SYonghong Song 	kfree(st->bpf_seq_afinfo);
34455788b3a0SYonghong Song 	bpf_iter_fini_seq_net(priv_data);
34465788b3a0SYonghong Song }
34475788b3a0SYonghong Song 
344814fc6bd6SYonghong Song static const struct bpf_iter_seq_info udp_seq_info = {
34495788b3a0SYonghong Song 	.seq_ops		= &bpf_iter_udp_seq_ops,
34505788b3a0SYonghong Song 	.init_seq_private	= bpf_iter_init_udp,
34515788b3a0SYonghong Song 	.fini_seq_private	= bpf_iter_fini_udp,
34525788b3a0SYonghong Song 	.seq_priv_size		= sizeof(struct udp_iter_state),
345314fc6bd6SYonghong Song };
345414fc6bd6SYonghong Song 
345514fc6bd6SYonghong Song static struct bpf_iter_reg udp_reg_info = {
345614fc6bd6SYonghong Song 	.target			= "udp",
34575788b3a0SYonghong Song 	.ctx_arg_info_size	= 1,
34585788b3a0SYonghong Song 	.ctx_arg_info		= {
34595788b3a0SYonghong Song 		{ offsetof(struct bpf_iter__udp, udp_sk),
34605788b3a0SYonghong Song 		  PTR_TO_BTF_ID_OR_NULL },
34615788b3a0SYonghong Song 	},
346214fc6bd6SYonghong Song 	.seq_info		= &udp_seq_info,
34635788b3a0SYonghong Song };
34645788b3a0SYonghong Song 
34655788b3a0SYonghong Song static void __init bpf_iter_register(void)
34665788b3a0SYonghong Song {
3467951cf368SYonghong Song 	udp_reg_info.ctx_arg_info[0].btf_id = btf_sock_ids[BTF_SOCK_TYPE_UDP];
34685788b3a0SYonghong Song 	if (bpf_iter_reg_target(&udp_reg_info))
34695788b3a0SYonghong Song 		pr_warn("Warning: could not register bpf iterator udp\n");
34705788b3a0SYonghong Song }
34715788b3a0SYonghong Song #endif
34725788b3a0SYonghong Song 
347395766fffSHideo Aoki void __init udp_init(void)
347495766fffSHideo Aoki {
3475f03d78dbSEric Dumazet 	unsigned long limit;
34764b272750SEric Dumazet 	unsigned int i;
347795766fffSHideo Aoki 
3478f86dcc5aSEric Dumazet 	udp_table_init(&udp_table, "UDP");
3479f03d78dbSEric Dumazet 	limit = nr_free_buffer_pages() / 8;
348095766fffSHideo Aoki 	limit = max(limit, 128UL);
348195766fffSHideo Aoki 	sysctl_udp_mem[0] = limit / 4 * 3;
348295766fffSHideo Aoki 	sysctl_udp_mem[1] = limit;
348395766fffSHideo Aoki 	sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
348495766fffSHideo Aoki 
34854b272750SEric Dumazet 	/* 16 spinlocks per cpu */
34864b272750SEric Dumazet 	udp_busylocks_log = ilog2(nr_cpu_ids) + 4;
34874b272750SEric Dumazet 	udp_busylocks = kmalloc(sizeof(spinlock_t) << udp_busylocks_log,
34884b272750SEric Dumazet 				GFP_KERNEL);
34894b272750SEric Dumazet 	if (!udp_busylocks)
34904b272750SEric Dumazet 		panic("UDP: failed to alloc udp_busylocks\n");
34914b272750SEric Dumazet 	for (i = 0; i < (1U << udp_busylocks_log); i++)
34924b272750SEric Dumazet 		spin_lock_init(udp_busylocks + i);
34931e802951STonghao Zhang 
34941e802951STonghao Zhang 	if (register_pernet_subsys(&udp_sysctl_ops))
34951e802951STonghao Zhang 		panic("UDP: failed to init sysctl parameters.\n");
34965788b3a0SYonghong Song 
34975788b3a0SYonghong Song #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
34985788b3a0SYonghong Song 	bpf_iter_register();
34995788b3a0SYonghong Song #endif
350095766fffSHideo Aoki }
3501