xref: /linux/net/ipv4/udp.c (revision d457a0e329b0bfd3a1450e0b1a18cd2b47a25a08)
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>
106*d457a0e3SEric Dumazet #include <net/gso.h>
1071da177e4SLinus Torvalds #include <net/xfrm.h>
108296f7ea7SSatoru Moriya #include <trace/events/udp.h>
109447167bfSEric Dumazet #include <linux/static_key.h>
110951cf368SYonghong Song #include <linux/btf_ids.h>
11122911fc5SEric Dumazet #include <trace/events/skb.h>
112076bb0c8SEliezer Tamir #include <net/busy_poll.h>
113ba4e58ecSGerrit Renker #include "udp_impl.h"
114e32ea7e7SCraig Gallek #include <net/sock_reuseport.h>
115217375a0SEric Dumazet #include <net/addrconf.h>
11660fb9567SPaolo Abeni #include <net/udp_tunnel.h>
1170146dca7SSabrina Dubroca #if IS_ENABLED(CONFIG_IPV6)
1180146dca7SSabrina Dubroca #include <net/ipv6_stubs.h>
1190146dca7SSabrina Dubroca #endif
1201da177e4SLinus Torvalds 
121f86dcc5aSEric Dumazet struct udp_table udp_table __read_mostly;
122645ca708SEric Dumazet EXPORT_SYMBOL(udp_table);
1231da177e4SLinus Torvalds 
1248d987e5cSEric Dumazet long sysctl_udp_mem[3] __read_mostly;
12595766fffSHideo Aoki EXPORT_SYMBOL(sysctl_udp_mem);
126c482c568SEric Dumazet 
12791b6d325SEric Dumazet atomic_long_t udp_memory_allocated ____cacheline_aligned_in_smp;
12895766fffSHideo Aoki EXPORT_SYMBOL(udp_memory_allocated);
1290defbb0aSEric Dumazet DEFINE_PER_CPU(int, udp_memory_per_cpu_fw_alloc);
1300defbb0aSEric Dumazet EXPORT_PER_CPU_SYMBOL_GPL(udp_memory_per_cpu_fw_alloc);
13195766fffSHideo Aoki 
132f86dcc5aSEric Dumazet #define MAX_UDP_PORTS 65536
1339804985bSKuniyuki Iwashima #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN_PERNET)
13498322f22SEric Dumazet 
13567fb4330SKuniyuki Iwashima static struct udp_table *udp_get_table_prot(struct sock *sk)
13667fb4330SKuniyuki Iwashima {
13767fb4330SKuniyuki Iwashima 	return sk->sk_prot->h.udp_table ? : sock_net(sk)->ipv4.udp_table;
13867fb4330SKuniyuki Iwashima }
13967fb4330SKuniyuki Iwashima 
140f24d43c0SEric Dumazet static int udp_lib_lport_inuse(struct net *net, __u16 num,
141645ca708SEric Dumazet 			       const struct udp_hslot *hslot,
14298322f22SEric Dumazet 			       unsigned long *bitmap,
143fe38d2a1SJosef Bacik 			       struct sock *sk, unsigned int log)
14425030a7fSGerrit Renker {
145f24d43c0SEric Dumazet 	struct sock *sk2;
146ba418fa3STom Herbert 	kuid_t uid = sock_i_uid(sk);
14725030a7fSGerrit Renker 
148ca065d0cSEric Dumazet 	sk_for_each(sk2, &hslot->head) {
149f24d43c0SEric Dumazet 		if (net_eq(sock_net(sk2), net) &&
150f24d43c0SEric Dumazet 		    sk2 != sk &&
151d4cada4aSEric Dumazet 		    (bitmap || udp_sk(sk2)->udp_port_hash == num) &&
152f24d43c0SEric Dumazet 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
1539d4fb27dSJoe Perches 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
1549d4fb27dSJoe Perches 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
155fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, true)) {
156df560056SEric Garver 			if (sk2->sk_reuseport && sk->sk_reuseport &&
157df560056SEric Garver 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
158df560056SEric Garver 			    uid_eq(uid, sock_i_uid(sk2))) {
159df560056SEric Garver 				if (!bitmap)
160df560056SEric Garver 					return 0;
161df560056SEric Garver 			} else {
1624243cdc2SJoe Perches 				if (!bitmap)
163fc038410SDavid S. Miller 					return 1;
164df560056SEric Garver 				__set_bit(udp_sk(sk2)->udp_port_hash >> log,
165df560056SEric Garver 					  bitmap);
166df560056SEric Garver 			}
1674243cdc2SJoe Perches 		}
16898322f22SEric Dumazet 	}
16925030a7fSGerrit Renker 	return 0;
17025030a7fSGerrit Renker }
17125030a7fSGerrit Renker 
17230fff923SEric Dumazet /*
17330fff923SEric Dumazet  * Note: we still hold spinlock of primary hash chain, so no other writer
17430fff923SEric Dumazet  * can insert/delete a socket with local_port == num
17530fff923SEric Dumazet  */
17630fff923SEric Dumazet static int udp_lib_lport_inuse2(struct net *net, __u16 num,
17730fff923SEric Dumazet 				struct udp_hslot *hslot2,
178fe38d2a1SJosef Bacik 				struct sock *sk)
17930fff923SEric Dumazet {
18030fff923SEric Dumazet 	struct sock *sk2;
181ba418fa3STom Herbert 	kuid_t uid = sock_i_uid(sk);
18230fff923SEric Dumazet 	int res = 0;
18330fff923SEric Dumazet 
18430fff923SEric Dumazet 	spin_lock(&hslot2->lock);
185ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry(sk2, &hslot2->head) {
18630fff923SEric Dumazet 		if (net_eq(sock_net(sk2), net) &&
18730fff923SEric Dumazet 		    sk2 != sk &&
18830fff923SEric Dumazet 		    (udp_sk(sk2)->udp_port_hash == num) &&
18930fff923SEric Dumazet 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
1909d4fb27dSJoe Perches 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
1919d4fb27dSJoe Perches 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
192fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, true)) {
193df560056SEric Garver 			if (sk2->sk_reuseport && sk->sk_reuseport &&
194df560056SEric Garver 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
195df560056SEric Garver 			    uid_eq(uid, sock_i_uid(sk2))) {
196df560056SEric Garver 				res = 0;
197df560056SEric Garver 			} else {
19830fff923SEric Dumazet 				res = 1;
199df560056SEric Garver 			}
20030fff923SEric Dumazet 			break;
20130fff923SEric Dumazet 		}
2024243cdc2SJoe Perches 	}
20330fff923SEric Dumazet 	spin_unlock(&hslot2->lock);
20430fff923SEric Dumazet 	return res;
20530fff923SEric Dumazet }
20630fff923SEric Dumazet 
207fe38d2a1SJosef Bacik static int udp_reuseport_add_sock(struct sock *sk, struct udp_hslot *hslot)
208e32ea7e7SCraig Gallek {
209e32ea7e7SCraig Gallek 	struct net *net = sock_net(sk);
210e32ea7e7SCraig Gallek 	kuid_t uid = sock_i_uid(sk);
211e32ea7e7SCraig Gallek 	struct sock *sk2;
212e32ea7e7SCraig Gallek 
213ca065d0cSEric Dumazet 	sk_for_each(sk2, &hslot->head) {
214e32ea7e7SCraig Gallek 		if (net_eq(sock_net(sk2), net) &&
215e32ea7e7SCraig Gallek 		    sk2 != sk &&
216e32ea7e7SCraig Gallek 		    sk2->sk_family == sk->sk_family &&
217e32ea7e7SCraig Gallek 		    ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
218e32ea7e7SCraig Gallek 		    (udp_sk(sk2)->udp_port_hash == udp_sk(sk)->udp_port_hash) &&
219e32ea7e7SCraig Gallek 		    (sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
220e32ea7e7SCraig Gallek 		    sk2->sk_reuseport && uid_eq(uid, sock_i_uid(sk2)) &&
221fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, false)) {
2222dbb9b9eSMartin KaFai Lau 			return reuseport_add_sock(sk, sk2,
2232dbb9b9eSMartin KaFai Lau 						  inet_rcv_saddr_any(sk));
224e32ea7e7SCraig Gallek 		}
225e32ea7e7SCraig Gallek 	}
226e32ea7e7SCraig Gallek 
2272dbb9b9eSMartin KaFai Lau 	return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
228e32ea7e7SCraig Gallek }
229e32ea7e7SCraig Gallek 
23025030a7fSGerrit Renker /**
2316ba5a3c5SPavel Emelyanov  *  udp_lib_get_port  -  UDP/-Lite port lookup for IPv4 and IPv6
23225030a7fSGerrit Renker  *
23325030a7fSGerrit Renker  *  @sk:          socket struct in question
23425030a7fSGerrit Renker  *  @snum:        port number to look up
23525985edcSLucas De Marchi  *  @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
23630fff923SEric Dumazet  *                   with NULL address
23725030a7fSGerrit Renker  */
2386ba5a3c5SPavel Emelyanov int udp_lib_get_port(struct sock *sk, unsigned short snum,
23930fff923SEric Dumazet 		     unsigned int hash2_nulladdr)
2401da177e4SLinus Torvalds {
24167fb4330SKuniyuki Iwashima 	struct udp_table *udptable = udp_get_table_prot(sk);
242919dfa0bSKuniyuki Iwashima 	struct udp_hslot *hslot, *hslot2;
2433b1e0a65SYOSHIFUJI Hideaki 	struct net *net = sock_net(sk);
2447a7160edSKuniyuki Iwashima 	int error = -EADDRINUSE;
2451da177e4SLinus Torvalds 
24632c1da70SStephen Hemminger 	if (!snum) {
247919dfa0bSKuniyuki Iwashima 		DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
248919dfa0bSKuniyuki Iwashima 		unsigned short first, last;
2499088c560SEric Dumazet 		int low, high, remaining;
25095c96174SEric Dumazet 		unsigned int rand;
2511da177e4SLinus Torvalds 
25291d0b78cSJakub Sitnicki 		inet_sk_get_local_port_range(sk, &low, &high);
253a25de534SAnton Arapov 		remaining = (high - low) + 1;
254227b60f5SStephen Hemminger 
255a251c17aSJason A. Donenfeld 		rand = get_random_u32();
2568fc54f68SDaniel Borkmann 		first = reciprocal_scale(rand, remaining) + low;
25798322f22SEric Dumazet 		/*
25898322f22SEric Dumazet 		 * force rand to be an odd multiple of UDP_HTABLE_SIZE
25998322f22SEric Dumazet 		 */
260f86dcc5aSEric Dumazet 		rand = (rand | 1) * (udptable->mask + 1);
2615781b235SEric Dumazet 		last = first + udptable->mask + 1;
2625781b235SEric Dumazet 		do {
263f86dcc5aSEric Dumazet 			hslot = udp_hashslot(udptable, net, first);
26498322f22SEric Dumazet 			bitmap_zero(bitmap, PORTS_PER_CHAIN);
265645ca708SEric Dumazet 			spin_lock_bh(&hslot->lock);
26698322f22SEric Dumazet 			udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
267fe38d2a1SJosef Bacik 					    udptable->log);
26898322f22SEric Dumazet 
26998322f22SEric Dumazet 			snum = first;
27098322f22SEric Dumazet 			/*
27198322f22SEric Dumazet 			 * Iterate on all possible values of snum for this hash.
27298322f22SEric Dumazet 			 * Using steps of an odd multiple of UDP_HTABLE_SIZE
27398322f22SEric Dumazet 			 * give us randomization and full range coverage.
27498322f22SEric Dumazet 			 */
2759088c560SEric Dumazet 			do {
27698322f22SEric Dumazet 				if (low <= snum && snum <= high &&
277e3826f1eSAmerigo Wang 				    !test_bit(snum >> udptable->log, bitmap) &&
278122ff243SWANG Cong 				    !inet_is_local_reserved_port(net, snum))
27998322f22SEric Dumazet 					goto found;
28098322f22SEric Dumazet 				snum += rand;
28198322f22SEric Dumazet 			} while (snum != first);
28298322f22SEric Dumazet 			spin_unlock_bh(&hslot->lock);
283df560056SEric Garver 			cond_resched();
2845781b235SEric Dumazet 		} while (++first != last);
28598322f22SEric Dumazet 		goto fail;
286645ca708SEric Dumazet 	} else {
287f86dcc5aSEric Dumazet 		hslot = udp_hashslot(udptable, net, snum);
288645ca708SEric Dumazet 		spin_lock_bh(&hslot->lock);
28930fff923SEric Dumazet 		if (hslot->count > 10) {
29030fff923SEric Dumazet 			int exist;
29130fff923SEric Dumazet 			unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
29230fff923SEric Dumazet 
29330fff923SEric Dumazet 			slot2          &= udptable->mask;
29430fff923SEric Dumazet 			hash2_nulladdr &= udptable->mask;
29530fff923SEric Dumazet 
29630fff923SEric Dumazet 			hslot2 = udp_hashslot2(udptable, slot2);
29730fff923SEric Dumazet 			if (hslot->count < hslot2->count)
29830fff923SEric Dumazet 				goto scan_primary_hash;
29930fff923SEric Dumazet 
300fe38d2a1SJosef Bacik 			exist = udp_lib_lport_inuse2(net, snum, hslot2, sk);
30130fff923SEric Dumazet 			if (!exist && (hash2_nulladdr != slot2)) {
30230fff923SEric Dumazet 				hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
30330fff923SEric Dumazet 				exist = udp_lib_lport_inuse2(net, snum, hslot2,
304fe38d2a1SJosef Bacik 							     sk);
30530fff923SEric Dumazet 			}
30630fff923SEric Dumazet 			if (exist)
30730fff923SEric Dumazet 				goto fail_unlock;
30830fff923SEric Dumazet 			else
30930fff923SEric Dumazet 				goto found;
31030fff923SEric Dumazet 		}
31130fff923SEric Dumazet scan_primary_hash:
312fe38d2a1SJosef Bacik 		if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, 0))
313645ca708SEric Dumazet 			goto fail_unlock;
314645ca708SEric Dumazet 	}
31598322f22SEric Dumazet found:
316c720c7e8SEric Dumazet 	inet_sk(sk)->inet_num = snum;
317d4cada4aSEric Dumazet 	udp_sk(sk)->udp_port_hash = snum;
318d4cada4aSEric Dumazet 	udp_sk(sk)->udp_portaddr_hash ^= snum;
3191da177e4SLinus Torvalds 	if (sk_unhashed(sk)) {
320e32ea7e7SCraig Gallek 		if (sk->sk_reuseport &&
321fe38d2a1SJosef Bacik 		    udp_reuseport_add_sock(sk, hslot)) {
322e32ea7e7SCraig Gallek 			inet_sk(sk)->inet_num = 0;
323e32ea7e7SCraig Gallek 			udp_sk(sk)->udp_port_hash = 0;
324e32ea7e7SCraig Gallek 			udp_sk(sk)->udp_portaddr_hash ^= snum;
325e32ea7e7SCraig Gallek 			goto fail_unlock;
326e32ea7e7SCraig Gallek 		}
327e32ea7e7SCraig Gallek 
328ca065d0cSEric Dumazet 		sk_add_node_rcu(sk, &hslot->head);
329fdcc8aa9SEric Dumazet 		hslot->count++;
330c29a0bc4SPavel Emelyanov 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
331512615b6SEric Dumazet 
332512615b6SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
333512615b6SEric Dumazet 		spin_lock(&hslot2->lock);
334d894ba18SCraig Gallek 		if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
335d894ba18SCraig Gallek 		    sk->sk_family == AF_INET6)
3361602f49bSDavid S. Miller 			hlist_add_tail_rcu(&udp_sk(sk)->udp_portaddr_node,
337d894ba18SCraig Gallek 					   &hslot2->head);
338d894ba18SCraig Gallek 		else
339ca065d0cSEric Dumazet 			hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
340512615b6SEric Dumazet 					   &hslot2->head);
341512615b6SEric Dumazet 		hslot2->count++;
342512615b6SEric Dumazet 		spin_unlock(&hslot2->lock);
3431da177e4SLinus Torvalds 	}
344ca065d0cSEric Dumazet 	sock_set_flag(sk, SOCK_RCU_FREE);
34525030a7fSGerrit Renker 	error = 0;
346645ca708SEric Dumazet fail_unlock:
347645ca708SEric Dumazet 	spin_unlock_bh(&hslot->lock);
3481da177e4SLinus Torvalds fail:
34925030a7fSGerrit Renker 	return error;
3501da177e4SLinus Torvalds }
351c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_get_port);
3521da177e4SLinus Torvalds 
3536ba5a3c5SPavel Emelyanov int udp_v4_get_port(struct sock *sk, unsigned short snum)
354db8dac20SDavid S. Miller {
35530fff923SEric Dumazet 	unsigned int hash2_nulladdr =
356f0b1e64cSMartin KaFai Lau 		ipv4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
35730fff923SEric Dumazet 	unsigned int hash2_partial =
358f0b1e64cSMartin KaFai Lau 		ipv4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
35930fff923SEric Dumazet 
360d4cada4aSEric Dumazet 	/* precompute partial secondary hash */
36130fff923SEric Dumazet 	udp_sk(sk)->udp_portaddr_hash = hash2_partial;
362fe38d2a1SJosef Bacik 	return udp_lib_get_port(sk, snum, hash2_nulladdr);
363db8dac20SDavid S. Miller }
364db8dac20SDavid S. Miller 
365d1e37288SSu, Xuemin static int compute_score(struct sock *sk, struct net *net,
366d1e37288SSu, Xuemin 			 __be32 saddr, __be16 sport,
367fb74c277SDavid Ahern 			 __be32 daddr, unsigned short hnum,
36873545373STim Beale 			 int dif, int sdif)
369645ca708SEric Dumazet {
37060c04aecSJoe Perches 	int score;
37160c04aecSJoe Perches 	struct inet_sock *inet;
3726da5b0f0SMike Manning 	bool dev_match;
373645ca708SEric Dumazet 
37460c04aecSJoe Perches 	if (!net_eq(sock_net(sk), net) ||
37560c04aecSJoe Perches 	    udp_sk(sk)->udp_port_hash != hnum ||
37660c04aecSJoe Perches 	    ipv6_only_sock(sk))
37760c04aecSJoe Perches 		return -1;
378645ca708SEric Dumazet 
3794cdeeee9SPeter Oskolkov 	if (sk->sk_rcv_saddr != daddr)
380645ca708SEric Dumazet 		return -1;
38160c04aecSJoe Perches 
3824cdeeee9SPeter Oskolkov 	score = (sk->sk_family == PF_INET) ? 2 : 1;
3834cdeeee9SPeter Oskolkov 
3844cdeeee9SPeter Oskolkov 	inet = inet_sk(sk);
385c720c7e8SEric Dumazet 	if (inet->inet_daddr) {
386c720c7e8SEric Dumazet 		if (inet->inet_daddr != saddr)
387645ca708SEric Dumazet 			return -1;
388ba418fa3STom Herbert 		score += 4;
389645ca708SEric Dumazet 	}
39060c04aecSJoe Perches 
391c720c7e8SEric Dumazet 	if (inet->inet_dport) {
392c720c7e8SEric Dumazet 		if (inet->inet_dport != sport)
393645ca708SEric Dumazet 			return -1;
394ba418fa3STom Herbert 		score += 4;
395645ca708SEric Dumazet 	}
39660c04aecSJoe Perches 
3976da5b0f0SMike Manning 	dev_match = udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if,
3986da5b0f0SMike Manning 					dif, sdif);
39969678bcdSPaolo Abeni 	if (!dev_match)
400645ca708SEric Dumazet 		return -1;
4018d6c414cSMike Manning 	if (sk->sk_bound_dev_if)
402ba418fa3STom Herbert 		score += 4;
403fb74c277SDavid Ahern 
4047170a977SEric Dumazet 	if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
40570da268bSEric Dumazet 		score++;
406645ca708SEric Dumazet 	return score;
407645ca708SEric Dumazet }
408645ca708SEric Dumazet 
4096eada011SEric Dumazet static u32 udp_ehashfn(const struct net *net, const __be32 laddr,
41065cd8033SHannes Frederic Sowa 		       const __u16 lport, const __be32 faddr,
41165cd8033SHannes Frederic Sowa 		       const __be16 fport)
41265cd8033SHannes Frederic Sowa {
4131bbdceefSHannes Frederic Sowa 	static u32 udp_ehash_secret __read_mostly;
4141bbdceefSHannes Frederic Sowa 
4151bbdceefSHannes Frederic Sowa 	net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret));
4161bbdceefSHannes Frederic Sowa 
41765cd8033SHannes Frederic Sowa 	return __inet_ehashfn(laddr, lport, faddr, fport,
4181bbdceefSHannes Frederic Sowa 			      udp_ehash_secret + net_hash_mix(net));
41965cd8033SHannes Frederic Sowa }
42065cd8033SHannes Frederic Sowa 
421a57066b1SDavid S. Miller static struct sock *lookup_reuseport(struct net *net, struct sock *sk,
4227629c73aSJakub Sitnicki 				     struct sk_buff *skb,
4237629c73aSJakub Sitnicki 				     __be32 saddr, __be16 sport,
4247629c73aSJakub Sitnicki 				     __be32 daddr, unsigned short hnum)
4257629c73aSJakub Sitnicki {
4267629c73aSJakub Sitnicki 	struct sock *reuse_sk = NULL;
4277629c73aSJakub Sitnicki 	u32 hash;
4287629c73aSJakub Sitnicki 
4297629c73aSJakub Sitnicki 	if (sk->sk_reuseport && sk->sk_state != TCP_ESTABLISHED) {
4307629c73aSJakub Sitnicki 		hash = udp_ehashfn(net, daddr, hnum, saddr, sport);
4317629c73aSJakub Sitnicki 		reuse_sk = reuseport_select_sock(sk, hash, skb,
4327629c73aSJakub Sitnicki 						 sizeof(struct udphdr));
4337629c73aSJakub Sitnicki 	}
4347629c73aSJakub Sitnicki 	return reuse_sk;
4357629c73aSJakub Sitnicki }
4367629c73aSJakub Sitnicki 
437d1e37288SSu, Xuemin /* called with rcu_read_lock() */
4385051ebd2SEric Dumazet static struct sock *udp4_lib_lookup2(struct net *net,
4395051ebd2SEric Dumazet 				     __be32 saddr, __be16 sport,
440fb74c277SDavid Ahern 				     __be32 daddr, unsigned int hnum,
44173545373STim Beale 				     int dif, int sdif,
442d1e37288SSu, Xuemin 				     struct udp_hslot *hslot2,
4431134158bSCraig Gallek 				     struct sk_buff *skb)
4445051ebd2SEric Dumazet {
4455051ebd2SEric Dumazet 	struct sock *sk, *result;
446e94a62f5SPaolo Abeni 	int score, badness;
4475051ebd2SEric Dumazet 
4485051ebd2SEric Dumazet 	result = NULL;
449ba418fa3STom Herbert 	badness = 0;
450ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
451d1e37288SSu, Xuemin 		score = compute_score(sk, net, saddr, sport,
45273545373STim Beale 				      daddr, hnum, dif, sdif);
4535051ebd2SEric Dumazet 		if (score > badness) {
4547629c73aSJakub Sitnicki 			result = lookup_reuseport(net, sk, skb,
4557629c73aSJakub Sitnicki 						  saddr, sport, daddr, hnum);
456a57066b1SDavid S. Miller 			/* Fall back to scoring if group has connections */
45769421bf9SKuniyuki Iwashima 			if (result && !reuseport_has_conns(sk))
458ca065d0cSEric Dumazet 				return result;
4597629c73aSJakub Sitnicki 
460a57066b1SDavid S. Miller 			result = result ? : sk;
461ca065d0cSEric Dumazet 			badness = score;
4625051ebd2SEric Dumazet 		}
4635051ebd2SEric Dumazet 	}
4645051ebd2SEric Dumazet 	return result;
4655051ebd2SEric Dumazet }
4665051ebd2SEric Dumazet 
467a57066b1SDavid S. Miller static struct sock *udp4_lookup_run_bpf(struct net *net,
46872f7e944SJakub Sitnicki 					struct udp_table *udptable,
46972f7e944SJakub Sitnicki 					struct sk_buff *skb,
47072f7e944SJakub Sitnicki 					__be32 saddr, __be16 sport,
471f8931565SMark Pashmfouroush 					__be32 daddr, u16 hnum, const int dif)
47272f7e944SJakub Sitnicki {
47372f7e944SJakub Sitnicki 	struct sock *sk, *reuse_sk;
47472f7e944SJakub Sitnicki 	bool no_reuseport;
47572f7e944SJakub Sitnicki 
476ba6aac15SKuniyuki Iwashima 	if (udptable != net->ipv4.udp_table)
47772f7e944SJakub Sitnicki 		return NULL; /* only UDP is supported */
47872f7e944SJakub Sitnicki 
479f8931565SMark Pashmfouroush 	no_reuseport = bpf_sk_lookup_run_v4(net, IPPROTO_UDP, saddr, sport,
480f8931565SMark Pashmfouroush 					    daddr, hnum, dif, &sk);
48172f7e944SJakub Sitnicki 	if (no_reuseport || IS_ERR_OR_NULL(sk))
48272f7e944SJakub Sitnicki 		return sk;
48372f7e944SJakub Sitnicki 
48472f7e944SJakub Sitnicki 	reuse_sk = lookup_reuseport(net, sk, skb, saddr, sport, daddr, hnum);
485c64c9c28SJakub Sitnicki 	if (reuse_sk)
48672f7e944SJakub Sitnicki 		sk = reuse_sk;
48772f7e944SJakub Sitnicki 	return sk;
48872f7e944SJakub Sitnicki }
48972f7e944SJakub Sitnicki 
490db8dac20SDavid S. Miller /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
491db8dac20SDavid S. Miller  * harder than this. -DaveM
492db8dac20SDavid S. Miller  */
493fce82338SPavel Emelyanov struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
494fb74c277SDavid Ahern 		__be16 sport, __be32 daddr, __be16 dport, int dif,
495fb74c277SDavid Ahern 		int sdif, struct udp_table *udptable, struct sk_buff *skb)
496db8dac20SDavid S. Miller {
497db8dac20SDavid S. Miller 	unsigned short hnum = ntohs(dport);
4984cdeeee9SPeter Oskolkov 	unsigned int hash2, slot2;
4994cdeeee9SPeter Oskolkov 	struct udp_hslot *hslot2;
50072f7e944SJakub Sitnicki 	struct sock *result, *sk;
501db8dac20SDavid S. Miller 
502f0b1e64cSMartin KaFai Lau 	hash2 = ipv4_portaddr_hash(net, daddr, hnum);
5035051ebd2SEric Dumazet 	slot2 = hash2 & udptable->mask;
5045051ebd2SEric Dumazet 	hslot2 = &udptable->hash2[slot2];
5055051ebd2SEric Dumazet 
50672f7e944SJakub Sitnicki 	/* Lookup connected or non-wildcard socket */
5075051ebd2SEric Dumazet 	result = udp4_lib_lookup2(net, saddr, sport,
508fb74c277SDavid Ahern 				  daddr, hnum, dif, sdif,
50973545373STim Beale 				  hslot2, skb);
51072f7e944SJakub Sitnicki 	if (!IS_ERR_OR_NULL(result) && result->sk_state == TCP_ESTABLISHED)
51172f7e944SJakub Sitnicki 		goto done;
51272f7e944SJakub Sitnicki 
51372f7e944SJakub Sitnicki 	/* Lookup redirect from BPF */
51472f7e944SJakub Sitnicki 	if (static_branch_unlikely(&bpf_sk_lookup_enabled)) {
51572f7e944SJakub Sitnicki 		sk = udp4_lookup_run_bpf(net, udptable, skb,
516f8931565SMark Pashmfouroush 					 saddr, sport, daddr, hnum, dif);
51772f7e944SJakub Sitnicki 		if (sk) {
51872f7e944SJakub Sitnicki 			result = sk;
51972f7e944SJakub Sitnicki 			goto done;
52072f7e944SJakub Sitnicki 		}
52172f7e944SJakub Sitnicki 	}
52272f7e944SJakub Sitnicki 
52372f7e944SJakub Sitnicki 	/* Got non-wildcard socket or error on first lookup */
52472f7e944SJakub Sitnicki 	if (result)
52572f7e944SJakub Sitnicki 		goto done;
52672f7e944SJakub Sitnicki 
52772f7e944SJakub Sitnicki 	/* Lookup wildcard sockets */
528f0b1e64cSMartin KaFai Lau 	hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
5295051ebd2SEric Dumazet 	slot2 = hash2 & udptable->mask;
5305051ebd2SEric Dumazet 	hslot2 = &udptable->hash2[slot2];
5315051ebd2SEric Dumazet 
5321223c67cSJorge Boncompte [DTI2] 	result = udp4_lib_lookup2(net, saddr, sport,
5334cdeeee9SPeter Oskolkov 				  htonl(INADDR_ANY), hnum, dif, sdif,
53473545373STim Beale 				  hslot2, skb);
53572f7e944SJakub Sitnicki done:
53688e235b8SEnrico Weigelt 	if (IS_ERR(result))
5378217ca65SMartin KaFai Lau 		return NULL;
5385051ebd2SEric Dumazet 	return result;
5395051ebd2SEric Dumazet }
540fce82338SPavel Emelyanov EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
541db8dac20SDavid S. Miller 
542607c4aafSKOVACS Krisztian static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
543607c4aafSKOVACS Krisztian 						 __be16 sport, __be16 dport,
544645ca708SEric Dumazet 						 struct udp_table *udptable)
545607c4aafSKOVACS Krisztian {
546607c4aafSKOVACS Krisztian 	const struct iphdr *iph = ip_hdr(skb);
547607c4aafSKOVACS Krisztian 
548ed7cbbceSAlexander Duyck 	return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
549607c4aafSKOVACS Krisztian 				 iph->daddr, dport, inet_iif(skb),
550fb74c277SDavid Ahern 				 inet_sdif(skb), udptable, skb);
551607c4aafSKOVACS Krisztian }
552607c4aafSKOVACS Krisztian 
5537b58e63eSEric Dumazet struct sock *udp4_lib_lookup_skb(const struct sk_buff *skb,
55463058308STom Herbert 				 __be16 sport, __be16 dport)
55563058308STom Herbert {
556257a525fSMartin KaFai Lau 	const struct iphdr *iph = ip_hdr(skb);
557ba6aac15SKuniyuki Iwashima 	struct net *net = dev_net(skb->dev);
558257a525fSMartin KaFai Lau 
559ba6aac15SKuniyuki Iwashima 	return __udp4_lib_lookup(net, iph->saddr, sport,
560257a525fSMartin KaFai Lau 				 iph->daddr, dport, inet_iif(skb),
561ba6aac15SKuniyuki Iwashima 				 inet_sdif(skb), net->ipv4.udp_table, NULL);
56263058308STom Herbert }
56363058308STom Herbert 
564ca065d0cSEric Dumazet /* Must be called under rcu_read_lock().
565ca065d0cSEric Dumazet  * Does increment socket refcount.
566ca065d0cSEric Dumazet  */
5676e86000cSArnd Bergmann #if IS_ENABLED(CONFIG_NF_TPROXY_IPV4) || IS_ENABLED(CONFIG_NF_SOCKET_IPV4)
568bcd41303SKOVACS Krisztian struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
569bcd41303SKOVACS Krisztian 			     __be32 daddr, __be16 dport, int dif)
570bcd41303SKOVACS Krisztian {
571ca065d0cSEric Dumazet 	struct sock *sk;
572ca065d0cSEric Dumazet 
573ca065d0cSEric Dumazet 	sk = __udp4_lib_lookup(net, saddr, sport, daddr, dport,
574ba6aac15SKuniyuki Iwashima 			       dif, 0, net->ipv4.udp_table, NULL);
57541c6d650SReshetova, Elena 	if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
576ca065d0cSEric Dumazet 		sk = NULL;
577ca065d0cSEric Dumazet 	return sk;
578bcd41303SKOVACS Krisztian }
579bcd41303SKOVACS Krisztian EXPORT_SYMBOL_GPL(udp4_lib_lookup);
580ca065d0cSEric Dumazet #endif
581bcd41303SKOVACS Krisztian 
582a0a989d3SEric Dumazet static inline bool __udp_is_mcast_sock(struct net *net, const struct sock *sk,
583421b3885SShawn Bohrer 				       __be16 loc_port, __be32 loc_addr,
584421b3885SShawn Bohrer 				       __be16 rmt_port, __be32 rmt_addr,
585fb74c277SDavid Ahern 				       int dif, int sdif, unsigned short hnum)
586421b3885SShawn Bohrer {
587a0a989d3SEric Dumazet 	const struct inet_sock *inet = inet_sk(sk);
588421b3885SShawn Bohrer 
589421b3885SShawn Bohrer 	if (!net_eq(sock_net(sk), net) ||
590421b3885SShawn Bohrer 	    udp_sk(sk)->udp_port_hash != hnum ||
591421b3885SShawn Bohrer 	    (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
592421b3885SShawn Bohrer 	    (inet->inet_dport != rmt_port && inet->inet_dport) ||
593421b3885SShawn Bohrer 	    (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) ||
594421b3885SShawn Bohrer 	    ipv6_only_sock(sk) ||
59582ba25c6STim Beale 	    !udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif))
596421b3885SShawn Bohrer 		return false;
59760d9b031SDavid Ahern 	if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif, sdif))
598421b3885SShawn Bohrer 		return false;
599421b3885SShawn Bohrer 	return true;
600421b3885SShawn Bohrer }
601421b3885SShawn Bohrer 
602a36e185eSStefano Brivio DEFINE_STATIC_KEY_FALSE(udp_encap_needed_key);
603a36e185eSStefano Brivio void udp_encap_enable(void)
604a36e185eSStefano Brivio {
6059c480601SPaolo Abeni 	static_branch_inc(&udp_encap_needed_key);
606a36e185eSStefano Brivio }
607a36e185eSStefano Brivio EXPORT_SYMBOL(udp_encap_enable);
608a36e185eSStefano Brivio 
609a4a600ddSXin Long void udp_encap_disable(void)
610a4a600ddSXin Long {
611a4a600ddSXin Long 	static_branch_dec(&udp_encap_needed_key);
612a4a600ddSXin Long }
613a4a600ddSXin Long EXPORT_SYMBOL(udp_encap_disable);
614a4a600ddSXin Long 
615e7cc0824SStefano Brivio /* Handler for tunnels with arbitrary destination ports: no socket lookup, go
616e7cc0824SStefano Brivio  * through error handlers in encapsulations looking for a match.
617e7cc0824SStefano Brivio  */
618e7cc0824SStefano Brivio static int __udp4_lib_err_encap_no_sk(struct sk_buff *skb, u32 info)
619e7cc0824SStefano Brivio {
620e7cc0824SStefano Brivio 	int i;
621e7cc0824SStefano Brivio 
622e7cc0824SStefano Brivio 	for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) {
623e7cc0824SStefano Brivio 		int (*handler)(struct sk_buff *skb, u32 info);
62492b95364SPaolo Abeni 		const struct ip_tunnel_encap_ops *encap;
625e7cc0824SStefano Brivio 
62692b95364SPaolo Abeni 		encap = rcu_dereference(iptun_encaps[i]);
62792b95364SPaolo Abeni 		if (!encap)
628e7cc0824SStefano Brivio 			continue;
62992b95364SPaolo Abeni 		handler = encap->err_handler;
630e7cc0824SStefano Brivio 		if (handler && !handler(skb, info))
631e7cc0824SStefano Brivio 			return 0;
632e7cc0824SStefano Brivio 	}
633e7cc0824SStefano Brivio 
634e7cc0824SStefano Brivio 	return -ENOENT;
635e7cc0824SStefano Brivio }
636e7cc0824SStefano Brivio 
637a36e185eSStefano Brivio /* Try to match ICMP errors to UDP tunnels by looking up a socket without
638a36e185eSStefano Brivio  * reversing source and destination port: this will match tunnels that force the
639a36e185eSStefano Brivio  * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that
640a36e185eSStefano Brivio  * lwtunnels might actually break this assumption by being configured with
641a36e185eSStefano Brivio  * different destination ports on endpoints, in this case we won't be able to
642a36e185eSStefano Brivio  * trace ICMP messages back to them.
643a36e185eSStefano Brivio  *
644e7cc0824SStefano Brivio  * If this doesn't match any socket, probe tunnels with arbitrary destination
645e7cc0824SStefano Brivio  * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port
646e7cc0824SStefano Brivio  * we've sent packets to won't necessarily match the local destination port.
647e7cc0824SStefano Brivio  *
648a36e185eSStefano Brivio  * Then ask the tunnel implementation to match the error against a valid
649a36e185eSStefano Brivio  * association.
650a36e185eSStefano Brivio  *
651e7cc0824SStefano Brivio  * Return an error if we can't find a match, the socket if we need further
652e7cc0824SStefano Brivio  * processing, zero otherwise.
653a36e185eSStefano Brivio  */
654a36e185eSStefano Brivio static struct sock *__udp4_lib_err_encap(struct net *net,
655a36e185eSStefano Brivio 					 const struct iphdr *iph,
656a36e185eSStefano Brivio 					 struct udphdr *uh,
657a36e185eSStefano Brivio 					 struct udp_table *udptable,
6589bfce73cSVadim Fedorenko 					 struct sock *sk,
659e7cc0824SStefano Brivio 					 struct sk_buff *skb, u32 info)
660a36e185eSStefano Brivio {
6619bfce73cSVadim Fedorenko 	int (*lookup)(struct sock *sk, struct sk_buff *skb);
662a36e185eSStefano Brivio 	int network_offset, transport_offset;
6639bfce73cSVadim Fedorenko 	struct udp_sock *up;
664a36e185eSStefano Brivio 
665a36e185eSStefano Brivio 	network_offset = skb_network_offset(skb);
666a36e185eSStefano Brivio 	transport_offset = skb_transport_offset(skb);
667a36e185eSStefano Brivio 
668a36e185eSStefano Brivio 	/* Network header needs to point to the outer IPv4 header inside ICMP */
669a36e185eSStefano Brivio 	skb_reset_network_header(skb);
670a36e185eSStefano Brivio 
671a36e185eSStefano Brivio 	/* Transport header needs to point to the UDP header */
672a36e185eSStefano Brivio 	skb_set_transport_header(skb, iph->ihl << 2);
673a36e185eSStefano Brivio 
6749bfce73cSVadim Fedorenko 	if (sk) {
6759bfce73cSVadim Fedorenko 		up = udp_sk(sk);
6769bfce73cSVadim Fedorenko 
6779bfce73cSVadim Fedorenko 		lookup = READ_ONCE(up->encap_err_lookup);
6789bfce73cSVadim Fedorenko 		if (lookup && lookup(sk, skb))
6799bfce73cSVadim Fedorenko 			sk = NULL;
6809bfce73cSVadim Fedorenko 
6819bfce73cSVadim Fedorenko 		goto out;
6829bfce73cSVadim Fedorenko 	}
6839bfce73cSVadim Fedorenko 
684e7cc0824SStefano Brivio 	sk = __udp4_lib_lookup(net, iph->daddr, uh->source,
685e7cc0824SStefano Brivio 			       iph->saddr, uh->dest, skb->dev->ifindex, 0,
686e7cc0824SStefano Brivio 			       udptable, NULL);
687e7cc0824SStefano Brivio 	if (sk) {
6889bfce73cSVadim Fedorenko 		up = udp_sk(sk);
689e7cc0824SStefano Brivio 
690a36e185eSStefano Brivio 		lookup = READ_ONCE(up->encap_err_lookup);
691a36e185eSStefano Brivio 		if (!lookup || lookup(sk, skb))
692a36e185eSStefano Brivio 			sk = NULL;
693e7cc0824SStefano Brivio 	}
694e7cc0824SStefano Brivio 
6959bfce73cSVadim Fedorenko out:
696e7cc0824SStefano Brivio 	if (!sk)
697e7cc0824SStefano Brivio 		sk = ERR_PTR(__udp4_lib_err_encap_no_sk(skb, info));
698a36e185eSStefano Brivio 
699a36e185eSStefano Brivio 	skb_set_transport_header(skb, transport_offset);
700a36e185eSStefano Brivio 	skb_set_network_header(skb, network_offset);
701a36e185eSStefano Brivio 
702a36e185eSStefano Brivio 	return sk;
703a36e185eSStefano Brivio }
704a36e185eSStefano Brivio 
705db8dac20SDavid S. Miller /*
706db8dac20SDavid S. Miller  * This routine is called by the ICMP module when it gets some
707db8dac20SDavid S. Miller  * sort of error condition.  If err < 0 then the socket should
708db8dac20SDavid S. Miller  * be closed and the error returned to the user.  If err > 0
709db8dac20SDavid S. Miller  * it's just the icmp type << 8 | icmp code.
710db8dac20SDavid S. Miller  * Header points to the ip header of the error packet. We move
711db8dac20SDavid S. Miller  * on past this. Then (as it used to claim before adjustment)
712db8dac20SDavid S. Miller  * header points to the first 8 bytes of the udp header.  We need
713db8dac20SDavid S. Miller  * to find the appropriate port.
714db8dac20SDavid S. Miller  */
715db8dac20SDavid S. Miller 
71632bbd879SStefano Brivio int __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
717db8dac20SDavid S. Miller {
718db8dac20SDavid S. Miller 	struct inet_sock *inet;
719b71d1d42SEric Dumazet 	const struct iphdr *iph = (const struct iphdr *)skb->data;
720db8dac20SDavid S. Miller 	struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
721db8dac20SDavid S. Miller 	const int type = icmp_hdr(skb)->type;
722db8dac20SDavid S. Miller 	const int code = icmp_hdr(skb)->code;
723a36e185eSStefano Brivio 	bool tunnel = false;
724db8dac20SDavid S. Miller 	struct sock *sk;
725db8dac20SDavid S. Miller 	int harderr;
726db8dac20SDavid S. Miller 	int err;
727fd54d716SPavel Emelyanov 	struct net *net = dev_net(skb->dev);
728db8dac20SDavid S. Miller 
729fd54d716SPavel Emelyanov 	sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
730f64bf6b8SMike Manning 			       iph->saddr, uh->source, skb->dev->ifindex,
731f64bf6b8SMike Manning 			       inet_sdif(skb), udptable, NULL);
7329bfce73cSVadim Fedorenko 
733d26796aeSXin Long 	if (!sk || udp_sk(sk)->encap_type) {
734a36e185eSStefano Brivio 		/* No socket for error: try tunnels before discarding */
735e7cc0824SStefano Brivio 		if (static_branch_unlikely(&udp_encap_needed_key)) {
7369bfce73cSVadim Fedorenko 			sk = __udp4_lib_err_encap(net, iph, uh, udptable, sk, skb,
737e7cc0824SStefano Brivio 						  info);
738e7cc0824SStefano Brivio 			if (!sk)
739e7cc0824SStefano Brivio 				return 0;
7409bfce73cSVadim Fedorenko 		} else
7419bfce73cSVadim Fedorenko 			sk = ERR_PTR(-ENOENT);
742e7cc0824SStefano Brivio 
743e7cc0824SStefano Brivio 		if (IS_ERR(sk)) {
744e7cc0824SStefano Brivio 			__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
745e7cc0824SStefano Brivio 			return PTR_ERR(sk);
746e7cc0824SStefano Brivio 		}
747e7cc0824SStefano Brivio 
748a36e185eSStefano Brivio 		tunnel = true;
749db8dac20SDavid S. Miller 	}
750db8dac20SDavid S. Miller 
751db8dac20SDavid S. Miller 	err = 0;
752db8dac20SDavid S. Miller 	harderr = 0;
753db8dac20SDavid S. Miller 	inet = inet_sk(sk);
754db8dac20SDavid S. Miller 
755db8dac20SDavid S. Miller 	switch (type) {
756db8dac20SDavid S. Miller 	default:
757db8dac20SDavid S. Miller 	case ICMP_TIME_EXCEEDED:
758db8dac20SDavid S. Miller 		err = EHOSTUNREACH;
759db8dac20SDavid S. Miller 		break;
760db8dac20SDavid S. Miller 	case ICMP_SOURCE_QUENCH:
761db8dac20SDavid S. Miller 		goto out;
762db8dac20SDavid S. Miller 	case ICMP_PARAMETERPROB:
763db8dac20SDavid S. Miller 		err = EPROTO;
764db8dac20SDavid S. Miller 		harderr = 1;
765db8dac20SDavid S. Miller 		break;
766db8dac20SDavid S. Miller 	case ICMP_DEST_UNREACH:
767db8dac20SDavid S. Miller 		if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
76836393395SDavid S. Miller 			ipv4_sk_update_pmtu(skb, sk, info);
769db8dac20SDavid S. Miller 			if (inet->pmtudisc != IP_PMTUDISC_DONT) {
770db8dac20SDavid S. Miller 				err = EMSGSIZE;
771db8dac20SDavid S. Miller 				harderr = 1;
772db8dac20SDavid S. Miller 				break;
773db8dac20SDavid S. Miller 			}
774db8dac20SDavid S. Miller 			goto out;
775db8dac20SDavid S. Miller 		}
776db8dac20SDavid S. Miller 		err = EHOSTUNREACH;
777db8dac20SDavid S. Miller 		if (code <= NR_ICMP_UNREACH) {
778db8dac20SDavid S. Miller 			harderr = icmp_err_convert[code].fatal;
779db8dac20SDavid S. Miller 			err = icmp_err_convert[code].errno;
780db8dac20SDavid S. Miller 		}
781db8dac20SDavid S. Miller 		break;
78255be7a9cSDavid S. Miller 	case ICMP_REDIRECT:
78355be7a9cSDavid S. Miller 		ipv4_sk_redirect(skb, sk);
7841a462d18SDuan Jiong 		goto out;
785db8dac20SDavid S. Miller 	}
786db8dac20SDavid S. Miller 
787db8dac20SDavid S. Miller 	/*
788db8dac20SDavid S. Miller 	 *      RFC1122: OK.  Passes ICMP errors back to application, as per
789db8dac20SDavid S. Miller 	 *	4.1.3.3.
790db8dac20SDavid S. Miller 	 */
791a36e185eSStefano Brivio 	if (tunnel) {
792a36e185eSStefano Brivio 		/* ...not for tunnels though: we don't have a sending socket */
793ac56a0b4SDavid Howells 		if (udp_sk(sk)->encap_err_rcv)
79442fb06b3SDavid Howells 			udp_sk(sk)->encap_err_rcv(sk, skb, err, uh->dest, info,
79542fb06b3SDavid Howells 						  (u8 *)(uh+1));
796a36e185eSStefano Brivio 		goto out;
797a36e185eSStefano Brivio 	}
798db8dac20SDavid S. Miller 	if (!inet->recverr) {
799db8dac20SDavid S. Miller 		if (!harderr || sk->sk_state != TCP_ESTABLISHED)
800db8dac20SDavid S. Miller 			goto out;
801b1faf566SEric Dumazet 	} else
802db8dac20SDavid S. Miller 		ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
803b1faf566SEric Dumazet 
804db8dac20SDavid S. Miller 	sk->sk_err = err;
805e3ae2365SAlexander Aring 	sk_error_report(sk);
806db8dac20SDavid S. Miller out:
80732bbd879SStefano Brivio 	return 0;
808db8dac20SDavid S. Miller }
809db8dac20SDavid S. Miller 
81032bbd879SStefano Brivio int udp_err(struct sk_buff *skb, u32 info)
811db8dac20SDavid S. Miller {
812ba6aac15SKuniyuki Iwashima 	return __udp4_lib_err(skb, info, dev_net(skb->dev)->ipv4.udp_table);
813db8dac20SDavid S. Miller }
814db8dac20SDavid S. Miller 
815db8dac20SDavid S. Miller /*
816db8dac20SDavid S. Miller  * Throw away all pending data and cancel the corking. Socket is locked.
817db8dac20SDavid S. Miller  */
81836d926b9SDenis V. Lunev void udp_flush_pending_frames(struct sock *sk)
819db8dac20SDavid S. Miller {
820db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
821db8dac20SDavid S. Miller 
822db8dac20SDavid S. Miller 	if (up->pending) {
823db8dac20SDavid S. Miller 		up->len = 0;
824db8dac20SDavid S. Miller 		up->pending = 0;
825db8dac20SDavid S. Miller 		ip_flush_pending_frames(sk);
826db8dac20SDavid S. Miller 	}
827db8dac20SDavid S. Miller }
82836d926b9SDenis V. Lunev EXPORT_SYMBOL(udp_flush_pending_frames);
829db8dac20SDavid S. Miller 
830db8dac20SDavid S. Miller /**
831f6b9664fSHerbert Xu  * 	udp4_hwcsum  -  handle outgoing HW checksumming
832db8dac20SDavid S. Miller  * 	@skb: 	sk_buff containing the filled-in UDP header
833db8dac20SDavid S. Miller  * 	        (checksum field must be zeroed out)
834f6b9664fSHerbert Xu  *	@src:	source IP address
835f6b9664fSHerbert Xu  *	@dst:	destination IP address
836db8dac20SDavid S. Miller  */
837c26bf4a5SThomas Graf void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
838db8dac20SDavid S. Miller {
839db8dac20SDavid S. Miller 	struct udphdr *uh = udp_hdr(skb);
840f6b9664fSHerbert Xu 	int offset = skb_transport_offset(skb);
841f6b9664fSHerbert Xu 	int len = skb->len - offset;
842f6b9664fSHerbert Xu 	int hlen = len;
843db8dac20SDavid S. Miller 	__wsum csum = 0;
844db8dac20SDavid S. Miller 
845ebbe495fSWANG Cong 	if (!skb_has_frag_list(skb)) {
846db8dac20SDavid S. Miller 		/*
847db8dac20SDavid S. Miller 		 * Only one fragment on the socket.
848db8dac20SDavid S. Miller 		 */
849db8dac20SDavid S. Miller 		skb->csum_start = skb_transport_header(skb) - skb->head;
850db8dac20SDavid S. Miller 		skb->csum_offset = offsetof(struct udphdr, check);
851f6b9664fSHerbert Xu 		uh->check = ~csum_tcpudp_magic(src, dst, len,
852f6b9664fSHerbert Xu 					       IPPROTO_UDP, 0);
853db8dac20SDavid S. Miller 	} else {
854ebbe495fSWANG Cong 		struct sk_buff *frags;
855ebbe495fSWANG Cong 
856db8dac20SDavid S. Miller 		/*
857db8dac20SDavid S. Miller 		 * HW-checksum won't work as there are two or more
858db8dac20SDavid S. Miller 		 * fragments on the socket so that all csums of sk_buffs
859db8dac20SDavid S. Miller 		 * should be together
860db8dac20SDavid S. Miller 		 */
861ebbe495fSWANG Cong 		skb_walk_frags(skb, frags) {
862f6b9664fSHerbert Xu 			csum = csum_add(csum, frags->csum);
863f6b9664fSHerbert Xu 			hlen -= frags->len;
864ebbe495fSWANG Cong 		}
865db8dac20SDavid S. Miller 
866f6b9664fSHerbert Xu 		csum = skb_checksum(skb, offset, hlen, csum);
867db8dac20SDavid S. Miller 		skb->ip_summed = CHECKSUM_NONE;
868db8dac20SDavid S. Miller 
869db8dac20SDavid S. Miller 		uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
870db8dac20SDavid S. Miller 		if (uh->check == 0)
871db8dac20SDavid S. Miller 			uh->check = CSUM_MANGLED_0;
872db8dac20SDavid S. Miller 	}
873db8dac20SDavid S. Miller }
874c26bf4a5SThomas Graf EXPORT_SYMBOL_GPL(udp4_hwcsum);
875db8dac20SDavid S. Miller 
876af5fcba7STom Herbert /* Function to set UDP checksum for an IPv4 UDP packet. This is intended
877af5fcba7STom Herbert  * for the simple case like when setting the checksum for a UDP tunnel.
878af5fcba7STom Herbert  */
879af5fcba7STom Herbert void udp_set_csum(bool nocheck, struct sk_buff *skb,
880af5fcba7STom Herbert 		  __be32 saddr, __be32 daddr, int len)
881af5fcba7STom Herbert {
882af5fcba7STom Herbert 	struct udphdr *uh = udp_hdr(skb);
883af5fcba7STom Herbert 
884179bc67fSEdward Cree 	if (nocheck) {
885af5fcba7STom Herbert 		uh->check = 0;
886179bc67fSEdward Cree 	} else if (skb_is_gso(skb)) {
887af5fcba7STom Herbert 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
888179bc67fSEdward Cree 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) {
889179bc67fSEdward Cree 		uh->check = 0;
890179bc67fSEdward Cree 		uh->check = udp_v4_check(len, saddr, daddr, lco_csum(skb));
891179bc67fSEdward Cree 		if (uh->check == 0)
892179bc67fSEdward Cree 			uh->check = CSUM_MANGLED_0;
893d75f1306SEdward Cree 	} else {
894af5fcba7STom Herbert 		skb->ip_summed = CHECKSUM_PARTIAL;
895af5fcba7STom Herbert 		skb->csum_start = skb_transport_header(skb) - skb->head;
896af5fcba7STom Herbert 		skb->csum_offset = offsetof(struct udphdr, check);
897af5fcba7STom Herbert 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
898af5fcba7STom Herbert 	}
899af5fcba7STom Herbert }
900af5fcba7STom Herbert EXPORT_SYMBOL(udp_set_csum);
901af5fcba7STom Herbert 
902bec1f6f6SWillem de Bruijn static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4,
903bec1f6f6SWillem de Bruijn 			struct inet_cork *cork)
904f6b9664fSHerbert Xu {
905f6b9664fSHerbert Xu 	struct sock *sk = skb->sk;
906f6b9664fSHerbert Xu 	struct inet_sock *inet = inet_sk(sk);
907f6b9664fSHerbert Xu 	struct udphdr *uh;
908cffb8f61SMenglong Dong 	int err;
909f6b9664fSHerbert Xu 	int is_udplite = IS_UDPLITE(sk);
910f6b9664fSHerbert Xu 	int offset = skb_transport_offset(skb);
911f6b9664fSHerbert Xu 	int len = skb->len - offset;
9124094871dSJosh Hunt 	int datalen = len - sizeof(*uh);
913f6b9664fSHerbert Xu 	__wsum csum = 0;
914f6b9664fSHerbert Xu 
915f6b9664fSHerbert Xu 	/*
916f6b9664fSHerbert Xu 	 * Create a UDP header
917f6b9664fSHerbert Xu 	 */
918f6b9664fSHerbert Xu 	uh = udp_hdr(skb);
919f6b9664fSHerbert Xu 	uh->source = inet->inet_sport;
92079ab0531SDavid S. Miller 	uh->dest = fl4->fl4_dport;
921f6b9664fSHerbert Xu 	uh->len = htons(len);
922f6b9664fSHerbert Xu 	uh->check = 0;
923f6b9664fSHerbert Xu 
924bec1f6f6SWillem de Bruijn 	if (cork->gso_size) {
925bec1f6f6SWillem de Bruijn 		const int hlen = skb_network_header_len(skb) +
926bec1f6f6SWillem de Bruijn 				 sizeof(struct udphdr);
927bec1f6f6SWillem de Bruijn 
9280f149c9fSWillem de Bruijn 		if (hlen + cork->gso_size > cork->fragsize) {
9290f149c9fSWillem de Bruijn 			kfree_skb(skb);
930bec1f6f6SWillem de Bruijn 			return -EINVAL;
9310f149c9fSWillem de Bruijn 		}
932158390e4SJianguo Wu 		if (datalen > cork->gso_size * UDP_MAX_SEGMENTS) {
9330f149c9fSWillem de Bruijn 			kfree_skb(skb);
934bec1f6f6SWillem de Bruijn 			return -EINVAL;
9350f149c9fSWillem de Bruijn 		}
9360f149c9fSWillem de Bruijn 		if (sk->sk_no_check_tx) {
9370f149c9fSWillem de Bruijn 			kfree_skb(skb);
938a8c744a8SWillem de Bruijn 			return -EINVAL;
9390f149c9fSWillem de Bruijn 		}
940ff06342cSWillem de Bruijn 		if (skb->ip_summed != CHECKSUM_PARTIAL || is_udplite ||
9410f149c9fSWillem de Bruijn 		    dst_xfrm(skb_dst(skb))) {
9420f149c9fSWillem de Bruijn 			kfree_skb(skb);
943bec1f6f6SWillem de Bruijn 			return -EIO;
9440f149c9fSWillem de Bruijn 		}
945bec1f6f6SWillem de Bruijn 
9464094871dSJosh Hunt 		if (datalen > cork->gso_size) {
947bec1f6f6SWillem de Bruijn 			skb_shinfo(skb)->gso_size = cork->gso_size;
948bec1f6f6SWillem de Bruijn 			skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4;
9494094871dSJosh Hunt 			skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(datalen,
950dfec0ee2SAlexander Duyck 								 cork->gso_size);
9514094871dSJosh Hunt 		}
952a8c744a8SWillem de Bruijn 		goto csum_partial;
953bec1f6f6SWillem de Bruijn 	}
954bec1f6f6SWillem de Bruijn 
955f6b9664fSHerbert Xu 	if (is_udplite)  				 /*     UDP-Lite      */
956f6b9664fSHerbert Xu 		csum = udplite_csum(skb);
957f6b9664fSHerbert Xu 
958ab2fb7e3SWillem de Bruijn 	else if (sk->sk_no_check_tx) {			 /* UDP csum off */
959f6b9664fSHerbert Xu 
960f6b9664fSHerbert Xu 		skb->ip_summed = CHECKSUM_NONE;
961f6b9664fSHerbert Xu 		goto send;
962f6b9664fSHerbert Xu 
963f6b9664fSHerbert Xu 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
964a8c744a8SWillem de Bruijn csum_partial:
965f6b9664fSHerbert Xu 
96679ab0531SDavid S. Miller 		udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
967f6b9664fSHerbert Xu 		goto send;
968f6b9664fSHerbert Xu 
969f6b9664fSHerbert Xu 	} else
970f6b9664fSHerbert Xu 		csum = udp_csum(skb);
971f6b9664fSHerbert Xu 
972f6b9664fSHerbert Xu 	/* add protocol-dependent pseudo-header */
97379ab0531SDavid S. Miller 	uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
974f6b9664fSHerbert Xu 				      sk->sk_protocol, csum);
975f6b9664fSHerbert Xu 	if (uh->check == 0)
976f6b9664fSHerbert Xu 		uh->check = CSUM_MANGLED_0;
977f6b9664fSHerbert Xu 
978f6b9664fSHerbert Xu send:
979b5ec8eeaSEric Dumazet 	err = ip_send_skb(sock_net(sk), skb);
980f6b9664fSHerbert Xu 	if (err) {
981f6b9664fSHerbert Xu 		if (err == -ENOBUFS && !inet->recverr) {
9826aef70a8SEric Dumazet 			UDP_INC_STATS(sock_net(sk),
983f6b9664fSHerbert Xu 				      UDP_MIB_SNDBUFERRORS, is_udplite);
984f6b9664fSHerbert Xu 			err = 0;
985f6b9664fSHerbert Xu 		}
986f6b9664fSHerbert Xu 	} else
9876aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
988f6b9664fSHerbert Xu 			      UDP_MIB_OUTDATAGRAMS, is_udplite);
989f6b9664fSHerbert Xu 	return err;
990f6b9664fSHerbert Xu }
991f6b9664fSHerbert Xu 
992db8dac20SDavid S. Miller /*
993db8dac20SDavid S. Miller  * Push out all pending data as one UDP datagram. Socket is locked.
994db8dac20SDavid S. Miller  */
9958822b64aSHannes Frederic Sowa int udp_push_pending_frames(struct sock *sk)
996db8dac20SDavid S. Miller {
997db8dac20SDavid S. Miller 	struct udp_sock  *up = udp_sk(sk);
998db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
999b6f21b26SDavid S. Miller 	struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
1000db8dac20SDavid S. Miller 	struct sk_buff *skb;
1001db8dac20SDavid S. Miller 	int err = 0;
1002db8dac20SDavid S. Miller 
100377968b78SDavid S. Miller 	skb = ip_finish_skb(sk, fl4);
1004f6b9664fSHerbert Xu 	if (!skb)
1005db8dac20SDavid S. Miller 		goto out;
1006db8dac20SDavid S. Miller 
1007bec1f6f6SWillem de Bruijn 	err = udp_send_skb(skb, fl4, &inet->cork.base);
1008db8dac20SDavid S. Miller 
1009db8dac20SDavid S. Miller out:
1010db8dac20SDavid S. Miller 	up->len = 0;
1011db8dac20SDavid S. Miller 	up->pending = 0;
1012db8dac20SDavid S. Miller 	return err;
1013db8dac20SDavid S. Miller }
10148822b64aSHannes Frederic Sowa EXPORT_SYMBOL(udp_push_pending_frames);
1015db8dac20SDavid S. Miller 
10162e8de857SWillem de Bruijn static int __udp_cmsg_send(struct cmsghdr *cmsg, u16 *gso_size)
10172e8de857SWillem de Bruijn {
10182e8de857SWillem de Bruijn 	switch (cmsg->cmsg_type) {
10192e8de857SWillem de Bruijn 	case UDP_SEGMENT:
10202e8de857SWillem de Bruijn 		if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u16)))
10212e8de857SWillem de Bruijn 			return -EINVAL;
10222e8de857SWillem de Bruijn 		*gso_size = *(__u16 *)CMSG_DATA(cmsg);
10232e8de857SWillem de Bruijn 		return 0;
10242e8de857SWillem de Bruijn 	default:
10252e8de857SWillem de Bruijn 		return -EINVAL;
10262e8de857SWillem de Bruijn 	}
10272e8de857SWillem de Bruijn }
10282e8de857SWillem de Bruijn 
10292e8de857SWillem de Bruijn int udp_cmsg_send(struct sock *sk, struct msghdr *msg, u16 *gso_size)
10302e8de857SWillem de Bruijn {
10312e8de857SWillem de Bruijn 	struct cmsghdr *cmsg;
10322e8de857SWillem de Bruijn 	bool need_ip = false;
10332e8de857SWillem de Bruijn 	int err;
10342e8de857SWillem de Bruijn 
10352e8de857SWillem de Bruijn 	for_each_cmsghdr(cmsg, msg) {
10362e8de857SWillem de Bruijn 		if (!CMSG_OK(msg, cmsg))
10372e8de857SWillem de Bruijn 			return -EINVAL;
10382e8de857SWillem de Bruijn 
10392e8de857SWillem de Bruijn 		if (cmsg->cmsg_level != SOL_UDP) {
10402e8de857SWillem de Bruijn 			need_ip = true;
10412e8de857SWillem de Bruijn 			continue;
10422e8de857SWillem de Bruijn 		}
10432e8de857SWillem de Bruijn 
10442e8de857SWillem de Bruijn 		err = __udp_cmsg_send(cmsg, gso_size);
10452e8de857SWillem de Bruijn 		if (err)
10462e8de857SWillem de Bruijn 			return err;
10472e8de857SWillem de Bruijn 	}
10482e8de857SWillem de Bruijn 
10492e8de857SWillem de Bruijn 	return need_ip;
10502e8de857SWillem de Bruijn }
10512e8de857SWillem de Bruijn EXPORT_SYMBOL_GPL(udp_cmsg_send);
10522e8de857SWillem de Bruijn 
10531b784140SYing Xue int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1054db8dac20SDavid S. Miller {
1055db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1056db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
10571cedee13SAndrey Ignatov 	DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
1058e474995fSDavid S. Miller 	struct flowi4 fl4_stack;
1059b6f21b26SDavid S. Miller 	struct flowi4 *fl4;
1060db8dac20SDavid S. Miller 	int ulen = len;
1061db8dac20SDavid S. Miller 	struct ipcm_cookie ipc;
1062db8dac20SDavid S. Miller 	struct rtable *rt = NULL;
1063db8dac20SDavid S. Miller 	int free = 0;
1064db8dac20SDavid S. Miller 	int connected = 0;
1065db8dac20SDavid S. Miller 	__be32 daddr, faddr, saddr;
10660e26371dSGuillaume Nault 	u8 tos, scope;
1067db8dac20SDavid S. Miller 	__be16 dport;
1068db8dac20SDavid S. Miller 	int err, is_udplite = IS_UDPLITE(sk);
1069a9f59707SEric Dumazet 	int corkreq = READ_ONCE(up->corkflag) || msg->msg_flags&MSG_MORE;
1070db8dac20SDavid S. Miller 	int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
1071903ab86dSHerbert Xu 	struct sk_buff *skb;
1072f6d8bd05SEric Dumazet 	struct ip_options_data opt_copy;
1073db8dac20SDavid S. Miller 
1074db8dac20SDavid S. Miller 	if (len > 0xFFFF)
1075db8dac20SDavid S. Miller 		return -EMSGSIZE;
1076db8dac20SDavid S. Miller 
1077db8dac20SDavid S. Miller 	/*
1078db8dac20SDavid S. Miller 	 *	Check the flags.
1079db8dac20SDavid S. Miller 	 */
1080db8dac20SDavid S. Miller 
1081db8dac20SDavid S. Miller 	if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
1082db8dac20SDavid S. Miller 		return -EOPNOTSUPP;
1083db8dac20SDavid S. Miller 
1084903ab86dSHerbert Xu 	getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
1085903ab86dSHerbert Xu 
1086f5fca608SDavid S. Miller 	fl4 = &inet->cork.fl.u.ip4;
1087db8dac20SDavid S. Miller 	if (up->pending) {
1088db8dac20SDavid S. Miller 		/*
1089db8dac20SDavid S. Miller 		 * There are pending frames.
1090db8dac20SDavid S. Miller 		 * The socket lock must be held while it's corked.
1091db8dac20SDavid S. Miller 		 */
1092db8dac20SDavid S. Miller 		lock_sock(sk);
1093db8dac20SDavid S. Miller 		if (likely(up->pending)) {
1094db8dac20SDavid S. Miller 			if (unlikely(up->pending != AF_INET)) {
1095db8dac20SDavid S. Miller 				release_sock(sk);
1096db8dac20SDavid S. Miller 				return -EINVAL;
1097db8dac20SDavid S. Miller 			}
1098db8dac20SDavid S. Miller 			goto do_append_data;
1099db8dac20SDavid S. Miller 		}
1100db8dac20SDavid S. Miller 		release_sock(sk);
1101db8dac20SDavid S. Miller 	}
1102db8dac20SDavid S. Miller 	ulen += sizeof(struct udphdr);
1103db8dac20SDavid S. Miller 
1104db8dac20SDavid S. Miller 	/*
1105db8dac20SDavid S. Miller 	 *	Get and verify the address.
1106db8dac20SDavid S. Miller 	 */
11071cedee13SAndrey Ignatov 	if (usin) {
1108db8dac20SDavid S. Miller 		if (msg->msg_namelen < sizeof(*usin))
1109db8dac20SDavid S. Miller 			return -EINVAL;
1110db8dac20SDavid S. Miller 		if (usin->sin_family != AF_INET) {
1111db8dac20SDavid S. Miller 			if (usin->sin_family != AF_UNSPEC)
1112db8dac20SDavid S. Miller 				return -EAFNOSUPPORT;
1113db8dac20SDavid S. Miller 		}
1114db8dac20SDavid S. Miller 
1115db8dac20SDavid S. Miller 		daddr = usin->sin_addr.s_addr;
1116db8dac20SDavid S. Miller 		dport = usin->sin_port;
1117db8dac20SDavid S. Miller 		if (dport == 0)
1118db8dac20SDavid S. Miller 			return -EINVAL;
1119db8dac20SDavid S. Miller 	} else {
1120db8dac20SDavid S. Miller 		if (sk->sk_state != TCP_ESTABLISHED)
1121db8dac20SDavid S. Miller 			return -EDESTADDRREQ;
1122c720c7e8SEric Dumazet 		daddr = inet->inet_daddr;
1123c720c7e8SEric Dumazet 		dport = inet->inet_dport;
1124db8dac20SDavid S. Miller 		/* Open fast path for connected socket.
1125db8dac20SDavid S. Miller 		   Route will not be used, if at least one option is set.
1126db8dac20SDavid S. Miller 		 */
1127db8dac20SDavid S. Miller 		connected = 1;
1128db8dac20SDavid S. Miller 	}
1129c14ac945SSoheil Hassas Yeganeh 
113035178206SWillem de Bruijn 	ipcm_init_sk(&ipc, inet);
113118a419baSEric Dumazet 	ipc.gso_size = READ_ONCE(up->gso_size);
1132bf84a010SDaniel Borkmann 
1133db8dac20SDavid S. Miller 	if (msg->msg_controllen) {
11342e8de857SWillem de Bruijn 		err = udp_cmsg_send(sk, msg, &ipc.gso_size);
11352e8de857SWillem de Bruijn 		if (err > 0)
11362e8de857SWillem de Bruijn 			err = ip_cmsg_send(sk, msg, &ipc,
11372e8de857SWillem de Bruijn 					   sk->sk_family == AF_INET6);
11382e8de857SWillem de Bruijn 		if (unlikely(err < 0)) {
113991948309SEric Dumazet 			kfree(ipc.opt);
1140db8dac20SDavid S. Miller 			return err;
114191948309SEric Dumazet 		}
1142db8dac20SDavid S. Miller 		if (ipc.opt)
1143db8dac20SDavid S. Miller 			free = 1;
1144db8dac20SDavid S. Miller 		connected = 0;
1145db8dac20SDavid S. Miller 	}
1146f6d8bd05SEric Dumazet 	if (!ipc.opt) {
1147f6d8bd05SEric Dumazet 		struct ip_options_rcu *inet_opt;
1148f6d8bd05SEric Dumazet 
1149f6d8bd05SEric Dumazet 		rcu_read_lock();
1150f6d8bd05SEric Dumazet 		inet_opt = rcu_dereference(inet->inet_opt);
1151f6d8bd05SEric Dumazet 		if (inet_opt) {
1152f6d8bd05SEric Dumazet 			memcpy(&opt_copy, inet_opt,
1153f6d8bd05SEric Dumazet 			       sizeof(*inet_opt) + inet_opt->opt.optlen);
1154f6d8bd05SEric Dumazet 			ipc.opt = &opt_copy.opt;
1155f6d8bd05SEric Dumazet 		}
1156f6d8bd05SEric Dumazet 		rcu_read_unlock();
1157f6d8bd05SEric Dumazet 	}
1158db8dac20SDavid S. Miller 
11596fc88c35SDave Marchevsky 	if (cgroup_bpf_enabled(CGROUP_UDP4_SENDMSG) && !connected) {
11601cedee13SAndrey Ignatov 		err = BPF_CGROUP_RUN_PROG_UDP4_SENDMSG_LOCK(sk,
11611cedee13SAndrey Ignatov 					    (struct sockaddr *)usin, &ipc.addr);
11621cedee13SAndrey Ignatov 		if (err)
11631cedee13SAndrey Ignatov 			goto out_free;
11641cedee13SAndrey Ignatov 		if (usin) {
11651cedee13SAndrey Ignatov 			if (usin->sin_port == 0) {
11661cedee13SAndrey Ignatov 				/* BPF program set invalid port. Reject it. */
11671cedee13SAndrey Ignatov 				err = -EINVAL;
11681cedee13SAndrey Ignatov 				goto out_free;
11691cedee13SAndrey Ignatov 			}
11701cedee13SAndrey Ignatov 			daddr = usin->sin_addr.s_addr;
11711cedee13SAndrey Ignatov 			dport = usin->sin_port;
11721cedee13SAndrey Ignatov 		}
11731cedee13SAndrey Ignatov 	}
11741cedee13SAndrey Ignatov 
1175db8dac20SDavid S. Miller 	saddr = ipc.addr;
1176db8dac20SDavid S. Miller 	ipc.addr = faddr = daddr;
1177db8dac20SDavid S. Miller 
1178f6d8bd05SEric Dumazet 	if (ipc.opt && ipc.opt->opt.srr) {
11791b97013bSAndrey Ignatov 		if (!daddr) {
11801b97013bSAndrey Ignatov 			err = -EINVAL;
11811b97013bSAndrey Ignatov 			goto out_free;
11821b97013bSAndrey Ignatov 		}
1183f6d8bd05SEric Dumazet 		faddr = ipc.opt->opt.faddr;
1184db8dac20SDavid S. Miller 		connected = 0;
1185db8dac20SDavid S. Miller 	}
1186aa661581SFrancesco Fusco 	tos = get_rttos(&ipc, inet);
11870e26371dSGuillaume Nault 	scope = ip_sendmsg_scope(inet, &ipc, msg);
11880e26371dSGuillaume Nault 	if (scope == RT_SCOPE_LINK)
1189db8dac20SDavid S. Miller 		connected = 0;
1190db8dac20SDavid S. Miller 
1191db8dac20SDavid S. Miller 	if (ipv4_is_multicast(daddr)) {
1192854da991SRobert Shearman 		if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif))
1193db8dac20SDavid S. Miller 			ipc.oif = inet->mc_index;
1194db8dac20SDavid S. Miller 		if (!saddr)
1195db8dac20SDavid S. Miller 			saddr = inet->mc_addr;
1196db8dac20SDavid S. Miller 		connected = 0;
11979515a2e0SDavid Ahern 	} else if (!ipc.oif) {
119876e21053SErich E. Hoover 		ipc.oif = inet->uc_index;
11999515a2e0SDavid Ahern 	} else if (ipv4_is_lbcast(daddr) && inet->uc_index) {
12009515a2e0SDavid Ahern 		/* oif is set, packet is to local broadcast and
12012bdcc73cSRandy Dunlap 		 * uc_index is set. oif is most likely set
12029515a2e0SDavid Ahern 		 * by sk_bound_dev_if. If uc_index != oif check if the
12039515a2e0SDavid Ahern 		 * oif is an L3 master and uc_index is an L3 slave.
12049515a2e0SDavid Ahern 		 * If so, we want to allow the send using the uc_index.
12059515a2e0SDavid Ahern 		 */
12069515a2e0SDavid Ahern 		if (ipc.oif != inet->uc_index &&
12079515a2e0SDavid Ahern 		    ipc.oif == l3mdev_master_ifindex_by_index(sock_net(sk),
12089515a2e0SDavid Ahern 							      inet->uc_index)) {
12099515a2e0SDavid Ahern 			ipc.oif = inet->uc_index;
12109515a2e0SDavid Ahern 		}
12119515a2e0SDavid Ahern 	}
1212db8dac20SDavid S. Miller 
1213db8dac20SDavid S. Miller 	if (connected)
1214db8dac20SDavid S. Miller 		rt = (struct rtable *)sk_dst_check(sk, 0);
1215db8dac20SDavid S. Miller 
121651456b29SIan Morris 	if (!rt) {
121784a3aa00SPavel Emelyanov 		struct net *net = sock_net(sk);
12189a24abfaSDavid Ahern 		__u8 flow_flags = inet_sk_flowi_flags(sk);
121984a3aa00SPavel Emelyanov 
1220e474995fSDavid S. Miller 		fl4 = &fl4_stack;
12219a24abfaSDavid Ahern 
12220e26371dSGuillaume Nault 		flowi4_init_output(fl4, ipc.oif, ipc.sockc.mark, tos, scope,
12230e26371dSGuillaume Nault 				   sk->sk_protocol, flow_flags, faddr, saddr,
12240e26371dSGuillaume Nault 				   dport, inet->inet_sport, sk->sk_uid);
1225c0951cbcSDavid S. Miller 
12263df98d79SPaul Moore 		security_sk_classify_flow(sk, flowi4_to_flowi_common(fl4));
1227e474995fSDavid S. Miller 		rt = ip_route_output_flow(net, fl4, sk);
1228b23dd4feSDavid S. Miller 		if (IS_ERR(rt)) {
1229b23dd4feSDavid S. Miller 			err = PTR_ERR(rt);
123006dc94b1SDavid S. Miller 			rt = NULL;
1231db8dac20SDavid S. Miller 			if (err == -ENETUNREACH)
1232f1d8cba6SEric Dumazet 				IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
1233db8dac20SDavid S. Miller 			goto out;
1234db8dac20SDavid S. Miller 		}
1235db8dac20SDavid S. Miller 
1236db8dac20SDavid S. Miller 		err = -EACCES;
1237db8dac20SDavid S. Miller 		if ((rt->rt_flags & RTCF_BROADCAST) &&
1238db8dac20SDavid S. Miller 		    !sock_flag(sk, SOCK_BROADCAST))
1239db8dac20SDavid S. Miller 			goto out;
1240db8dac20SDavid S. Miller 		if (connected)
1241d8d1f30bSChangli Gao 			sk_dst_set(sk, dst_clone(&rt->dst));
1242db8dac20SDavid S. Miller 	}
1243db8dac20SDavid S. Miller 
1244db8dac20SDavid S. Miller 	if (msg->msg_flags&MSG_CONFIRM)
1245db8dac20SDavid S. Miller 		goto do_confirm;
1246db8dac20SDavid S. Miller back_from_confirm:
1247db8dac20SDavid S. Miller 
1248e474995fSDavid S. Miller 	saddr = fl4->saddr;
1249db8dac20SDavid S. Miller 	if (!ipc.addr)
1250e474995fSDavid S. Miller 		daddr = ipc.addr = fl4->daddr;
1251db8dac20SDavid S. Miller 
1252903ab86dSHerbert Xu 	/* Lockless fast path for the non-corking case. */
1253903ab86dSHerbert Xu 	if (!corkreq) {
12541cd7884dSWillem de Bruijn 		struct inet_cork cork;
12551cd7884dSWillem de Bruijn 
1256f69e6d13SAl Viro 		skb = ip_make_skb(sk, fl4, getfrag, msg, ulen,
1257903ab86dSHerbert Xu 				  sizeof(struct udphdr), &ipc, &rt,
12581cd7884dSWillem de Bruijn 				  &cork, msg->msg_flags);
1259903ab86dSHerbert Xu 		err = PTR_ERR(skb);
126050c3a487SYOSHIFUJI Hideaki / 吉藤英明 		if (!IS_ERR_OR_NULL(skb))
1261bec1f6f6SWillem de Bruijn 			err = udp_send_skb(skb, fl4, &cork);
1262903ab86dSHerbert Xu 		goto out;
1263903ab86dSHerbert Xu 	}
1264903ab86dSHerbert Xu 
1265db8dac20SDavid S. Miller 	lock_sock(sk);
1266db8dac20SDavid S. Miller 	if (unlikely(up->pending)) {
1267db8dac20SDavid S. Miller 		/* The socket is already corked while preparing it. */
1268db8dac20SDavid S. Miller 		/* ... which is an evident application bug. --ANK */
1269db8dac20SDavid S. Miller 		release_sock(sk);
1270db8dac20SDavid S. Miller 
1271197df02cSMatteo Croce 		net_dbg_ratelimited("socket already corked\n");
1272db8dac20SDavid S. Miller 		err = -EINVAL;
1273db8dac20SDavid S. Miller 		goto out;
1274db8dac20SDavid S. Miller 	}
1275db8dac20SDavid S. Miller 	/*
1276db8dac20SDavid S. Miller 	 *	Now cork the socket to pend data.
1277db8dac20SDavid S. Miller 	 */
1278b6f21b26SDavid S. Miller 	fl4 = &inet->cork.fl.u.ip4;
1279b6f21b26SDavid S. Miller 	fl4->daddr = daddr;
1280b6f21b26SDavid S. Miller 	fl4->saddr = saddr;
12819cce96dfSDavid S. Miller 	fl4->fl4_dport = dport;
12829cce96dfSDavid S. Miller 	fl4->fl4_sport = inet->inet_sport;
1283db8dac20SDavid S. Miller 	up->pending = AF_INET;
1284db8dac20SDavid S. Miller 
1285db8dac20SDavid S. Miller do_append_data:
1286db8dac20SDavid S. Miller 	up->len += ulen;
1287f69e6d13SAl Viro 	err = ip_append_data(sk, fl4, getfrag, msg, ulen,
12882e77d89bSEric Dumazet 			     sizeof(struct udphdr), &ipc, &rt,
1289db8dac20SDavid S. Miller 			     corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
1290db8dac20SDavid S. Miller 	if (err)
1291db8dac20SDavid S. Miller 		udp_flush_pending_frames(sk);
1292db8dac20SDavid S. Miller 	else if (!corkreq)
1293db8dac20SDavid S. Miller 		err = udp_push_pending_frames(sk);
1294db8dac20SDavid S. Miller 	else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
1295db8dac20SDavid S. Miller 		up->pending = 0;
1296db8dac20SDavid S. Miller 	release_sock(sk);
1297db8dac20SDavid S. Miller 
1298db8dac20SDavid S. Miller out:
1299db8dac20SDavid S. Miller 	ip_rt_put(rt);
13001b97013bSAndrey Ignatov out_free:
1301db8dac20SDavid S. Miller 	if (free)
1302db8dac20SDavid S. Miller 		kfree(ipc.opt);
1303db8dac20SDavid S. Miller 	if (!err)
1304db8dac20SDavid S. Miller 		return len;
1305db8dac20SDavid S. Miller 	/*
1306db8dac20SDavid S. Miller 	 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space.  Reporting
1307db8dac20SDavid S. Miller 	 * ENOBUFS might not be good (it's not tunable per se), but otherwise
1308db8dac20SDavid S. Miller 	 * we don't have a good statistic (IpOutDiscards but it can be too many
1309db8dac20SDavid S. Miller 	 * things).  We could add another new stat but at least for now that
1310db8dac20SDavid S. Miller 	 * seems like overkill.
1311db8dac20SDavid S. Miller 	 */
1312db8dac20SDavid S. Miller 	if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
13136aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
1314629ca23cSPavel Emelyanov 			      UDP_MIB_SNDBUFERRORS, is_udplite);
1315db8dac20SDavid S. Miller 	}
1316db8dac20SDavid S. Miller 	return err;
1317db8dac20SDavid S. Miller 
1318db8dac20SDavid S. Miller do_confirm:
13190dec879fSJulian Anastasov 	if (msg->msg_flags & MSG_PROBE)
13200dec879fSJulian Anastasov 		dst_confirm_neigh(&rt->dst, &fl4->daddr);
1321db8dac20SDavid S. Miller 	if (!(msg->msg_flags&MSG_PROBE) || len)
1322db8dac20SDavid S. Miller 		goto back_from_confirm;
1323db8dac20SDavid S. Miller 	err = 0;
1324db8dac20SDavid S. Miller 	goto out;
1325db8dac20SDavid S. Miller }
1326c482c568SEric Dumazet EXPORT_SYMBOL(udp_sendmsg);
1327db8dac20SDavid S. Miller 
13281d7e4538SDavid Howells void udp_splice_eof(struct socket *sock)
13291d7e4538SDavid Howells {
13301d7e4538SDavid Howells 	struct sock *sk = sock->sk;
13311d7e4538SDavid Howells 	struct udp_sock *up = udp_sk(sk);
13321d7e4538SDavid Howells 
13331d7e4538SDavid Howells 	if (!up->pending || READ_ONCE(up->corkflag))
13341d7e4538SDavid Howells 		return;
13351d7e4538SDavid Howells 
13361d7e4538SDavid Howells 	lock_sock(sk);
13371d7e4538SDavid Howells 	if (up->pending && !READ_ONCE(up->corkflag))
13381d7e4538SDavid Howells 		udp_push_pending_frames(sk);
13391d7e4538SDavid Howells 	release_sock(sk);
13401d7e4538SDavid Howells }
13411d7e4538SDavid Howells EXPORT_SYMBOL_GPL(udp_splice_eof);
13421d7e4538SDavid Howells 
1343db8dac20SDavid S. Miller int udp_sendpage(struct sock *sk, struct page *page, int offset,
1344db8dac20SDavid S. Miller 		 size_t size, int flags)
1345db8dac20SDavid S. Miller {
13467ac7c987SDavid Howells 	struct bio_vec bvec;
13477ac7c987SDavid Howells 	struct msghdr msg = { .msg_flags = flags | MSG_SPLICE_PAGES };
1348db8dac20SDavid S. Miller 
1349d3f7d56aSShawn Landden 	if (flags & MSG_SENDPAGE_NOTLAST)
13507ac7c987SDavid Howells 		msg.msg_flags |= MSG_MORE;
1351d3f7d56aSShawn Landden 
13527ac7c987SDavid Howells 	bvec_set_page(&bvec, page, size, offset);
13537ac7c987SDavid Howells 	iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, &bvec, 1, size);
13547ac7c987SDavid Howells 	return udp_sendmsg(sk, &msg, size);
1355db8dac20SDavid S. Miller }
1356db8dac20SDavid S. Miller 
1357dce4551cSPaolo Abeni #define UDP_SKB_IS_STATELESS 0x80000000
1358dce4551cSPaolo Abeni 
1359677bf08cSFlorian Westphal /* all head states (dst, sk, nf conntrack) except skb extensions are
1360677bf08cSFlorian Westphal  * cleared by udp_rcv().
1361677bf08cSFlorian Westphal  *
1362677bf08cSFlorian Westphal  * We need to preserve secpath, if present, to eventually process
1363677bf08cSFlorian Westphal  * IP_CMSG_PASSSEC at recvmsg() time.
1364677bf08cSFlorian Westphal  *
1365677bf08cSFlorian Westphal  * Other extensions can be cleared.
1366677bf08cSFlorian Westphal  */
1367677bf08cSFlorian Westphal static bool udp_try_make_stateless(struct sk_buff *skb)
1368677bf08cSFlorian Westphal {
1369677bf08cSFlorian Westphal 	if (!skb_has_extensions(skb))
1370677bf08cSFlorian Westphal 		return true;
1371677bf08cSFlorian Westphal 
1372677bf08cSFlorian Westphal 	if (!secpath_exists(skb)) {
1373677bf08cSFlorian Westphal 		skb_ext_reset(skb);
1374677bf08cSFlorian Westphal 		return true;
1375677bf08cSFlorian Westphal 	}
1376677bf08cSFlorian Westphal 
1377677bf08cSFlorian Westphal 	return false;
1378677bf08cSFlorian Westphal }
1379677bf08cSFlorian Westphal 
1380b65ac446SPaolo Abeni static void udp_set_dev_scratch(struct sk_buff *skb)
1381b65ac446SPaolo Abeni {
1382dce4551cSPaolo Abeni 	struct udp_dev_scratch *scratch = udp_skb_scratch(skb);
1383b65ac446SPaolo Abeni 
1384b65ac446SPaolo Abeni 	BUILD_BUG_ON(sizeof(struct udp_dev_scratch) > sizeof(long));
1385dce4551cSPaolo Abeni 	scratch->_tsize_state = skb->truesize;
1386dce4551cSPaolo Abeni #if BITS_PER_LONG == 64
1387b65ac446SPaolo Abeni 	scratch->len = skb->len;
1388b65ac446SPaolo Abeni 	scratch->csum_unnecessary = !!skb_csum_unnecessary(skb);
1389b65ac446SPaolo Abeni 	scratch->is_linear = !skb_is_nonlinear(skb);
1390b65ac446SPaolo Abeni #endif
1391677bf08cSFlorian Westphal 	if (udp_try_make_stateless(skb))
1392dce4551cSPaolo Abeni 		scratch->_tsize_state |= UDP_SKB_IS_STATELESS;
1393dce4551cSPaolo Abeni }
1394dce4551cSPaolo Abeni 
1395a793183cSEric Dumazet static void udp_skb_csum_unnecessary_set(struct sk_buff *skb)
1396a793183cSEric Dumazet {
1397a793183cSEric Dumazet 	/* We come here after udp_lib_checksum_complete() returned 0.
1398a793183cSEric Dumazet 	 * This means that __skb_checksum_complete() might have
1399a793183cSEric Dumazet 	 * set skb->csum_valid to 1.
1400a793183cSEric Dumazet 	 * On 64bit platforms, we can set csum_unnecessary
1401a793183cSEric Dumazet 	 * to true, but only if the skb is not shared.
1402a793183cSEric Dumazet 	 */
1403a793183cSEric Dumazet #if BITS_PER_LONG == 64
1404a793183cSEric Dumazet 	if (!skb_shared(skb))
1405a793183cSEric Dumazet 		udp_skb_scratch(skb)->csum_unnecessary = true;
1406a793183cSEric Dumazet #endif
1407a793183cSEric Dumazet }
1408a793183cSEric Dumazet 
1409dce4551cSPaolo Abeni static int udp_skb_truesize(struct sk_buff *skb)
1410dce4551cSPaolo Abeni {
1411dce4551cSPaolo Abeni 	return udp_skb_scratch(skb)->_tsize_state & ~UDP_SKB_IS_STATELESS;
1412dce4551cSPaolo Abeni }
1413dce4551cSPaolo Abeni 
1414dce4551cSPaolo Abeni static bool udp_skb_has_head_state(struct sk_buff *skb)
1415dce4551cSPaolo Abeni {
1416dce4551cSPaolo Abeni 	return !(udp_skb_scratch(skb)->_tsize_state & UDP_SKB_IS_STATELESS);
1417dce4551cSPaolo Abeni }
1418b65ac446SPaolo Abeni 
14197c13f97fSPaolo Abeni /* fully reclaim rmem/fwd memory allocated for skb */
14206dfb4367SPaolo Abeni static void udp_rmem_release(struct sock *sk, int size, int partial,
14216dfb4367SPaolo Abeni 			     bool rx_queue_lock_held)
1422f970bd9eSPaolo Abeni {
14236b229cf7SEric Dumazet 	struct udp_sock *up = udp_sk(sk);
14242276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue;
1425f970bd9eSPaolo Abeni 	int amt;
1426f970bd9eSPaolo Abeni 
14276b229cf7SEric Dumazet 	if (likely(partial)) {
14286b229cf7SEric Dumazet 		up->forward_deficit += size;
14296b229cf7SEric Dumazet 		size = up->forward_deficit;
14308a3854c7SPaolo Abeni 		if (size < READ_ONCE(up->forward_threshold) &&
1431d39ca259SPaolo Abeni 		    !skb_queue_empty(&up->reader_queue))
14326b229cf7SEric Dumazet 			return;
14336b229cf7SEric Dumazet 	} else {
14346b229cf7SEric Dumazet 		size += up->forward_deficit;
14356b229cf7SEric Dumazet 	}
14366b229cf7SEric Dumazet 	up->forward_deficit = 0;
14376b229cf7SEric Dumazet 
14386dfb4367SPaolo Abeni 	/* acquire the sk_receive_queue for fwd allocated memory scheduling,
14396dfb4367SPaolo Abeni 	 * if the called don't held it already
14406dfb4367SPaolo Abeni 	 */
14412276f58aSPaolo Abeni 	sk_queue = &sk->sk_receive_queue;
14426dfb4367SPaolo Abeni 	if (!rx_queue_lock_held)
14432276f58aSPaolo Abeni 		spin_lock(&sk_queue->lock);
14442276f58aSPaolo Abeni 
14456dfb4367SPaolo Abeni 
1446f970bd9eSPaolo Abeni 	sk->sk_forward_alloc += size;
1447100fdd1fSEric Dumazet 	amt = (sk->sk_forward_alloc - partial) & ~(PAGE_SIZE - 1);
1448f970bd9eSPaolo Abeni 	sk->sk_forward_alloc -= amt;
1449f970bd9eSPaolo Abeni 
1450f970bd9eSPaolo Abeni 	if (amt)
1451100fdd1fSEric Dumazet 		__sk_mem_reduce_allocated(sk, amt >> PAGE_SHIFT);
145202ab0d13SEric Dumazet 
145302ab0d13SEric Dumazet 	atomic_sub(size, &sk->sk_rmem_alloc);
14542276f58aSPaolo Abeni 
14552276f58aSPaolo Abeni 	/* this can save us from acquiring the rx queue lock on next receive */
14562276f58aSPaolo Abeni 	skb_queue_splice_tail_init(sk_queue, &up->reader_queue);
14572276f58aSPaolo Abeni 
14586dfb4367SPaolo Abeni 	if (!rx_queue_lock_held)
14592276f58aSPaolo Abeni 		spin_unlock(&sk_queue->lock);
1460f970bd9eSPaolo Abeni }
1461f970bd9eSPaolo Abeni 
14622276f58aSPaolo Abeni /* Note: called with reader_queue.lock held.
1463c84d9490SEric Dumazet  * Instead of using skb->truesize here, find a copy of it in skb->dev_scratch
1464c84d9490SEric Dumazet  * This avoids a cache line miss while receive_queue lock is held.
1465c84d9490SEric Dumazet  * Look at __udp_enqueue_schedule_skb() to find where this copy is done.
1466c84d9490SEric Dumazet  */
14677c13f97fSPaolo Abeni void udp_skb_destructor(struct sock *sk, struct sk_buff *skb)
1468f970bd9eSPaolo Abeni {
1469b65ac446SPaolo Abeni 	prefetch(&skb->data);
1470b65ac446SPaolo Abeni 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, false);
1471f970bd9eSPaolo Abeni }
14727c13f97fSPaolo Abeni EXPORT_SYMBOL(udp_skb_destructor);
1473f970bd9eSPaolo Abeni 
14746dfb4367SPaolo Abeni /* as above, but the caller held the rx queue lock, too */
147564f5102dSColin Ian King static void udp_skb_dtor_locked(struct sock *sk, struct sk_buff *skb)
14766dfb4367SPaolo Abeni {
1477b65ac446SPaolo Abeni 	prefetch(&skb->data);
1478b65ac446SPaolo Abeni 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, true);
14796dfb4367SPaolo Abeni }
14806dfb4367SPaolo Abeni 
14814b272750SEric Dumazet /* Idea of busylocks is to let producers grab an extra spinlock
14824b272750SEric Dumazet  * to relieve pressure on the receive_queue spinlock shared by consumer.
14834b272750SEric Dumazet  * Under flood, this means that only one producer can be in line
14844b272750SEric Dumazet  * trying to acquire the receive_queue spinlock.
14854b272750SEric Dumazet  * These busylock can be allocated on a per cpu manner, instead of a
14864b272750SEric Dumazet  * per socket one (that would consume a cache line per socket)
14874b272750SEric Dumazet  */
14884b272750SEric Dumazet static int udp_busylocks_log __read_mostly;
14894b272750SEric Dumazet static spinlock_t *udp_busylocks __read_mostly;
14904b272750SEric Dumazet 
14914b272750SEric Dumazet static spinlock_t *busylock_acquire(void *ptr)
14924b272750SEric Dumazet {
14934b272750SEric Dumazet 	spinlock_t *busy;
14944b272750SEric Dumazet 
14954b272750SEric Dumazet 	busy = udp_busylocks + hash_ptr(ptr, udp_busylocks_log);
14964b272750SEric Dumazet 	spin_lock(busy);
14974b272750SEric Dumazet 	return busy;
14984b272750SEric Dumazet }
14994b272750SEric Dumazet 
15004b272750SEric Dumazet static void busylock_release(spinlock_t *busy)
15014b272750SEric Dumazet {
15024b272750SEric Dumazet 	if (busy)
15034b272750SEric Dumazet 		spin_unlock(busy);
15044b272750SEric Dumazet }
15054b272750SEric Dumazet 
1506fd9c31f8SJason Xing static int udp_rmem_schedule(struct sock *sk, int size)
1507fd9c31f8SJason Xing {
1508fd9c31f8SJason Xing 	int delta;
1509fd9c31f8SJason Xing 
1510fd9c31f8SJason Xing 	delta = size - sk->sk_forward_alloc;
1511fd9c31f8SJason Xing 	if (delta > 0 && !__sk_mem_schedule(sk, delta, SK_MEM_RECV))
1512fd9c31f8SJason Xing 		return -ENOBUFS;
1513fd9c31f8SJason Xing 
1514fd9c31f8SJason Xing 	return 0;
1515fd9c31f8SJason Xing }
1516fd9c31f8SJason Xing 
1517f970bd9eSPaolo Abeni int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb)
1518f970bd9eSPaolo Abeni {
1519f970bd9eSPaolo Abeni 	struct sk_buff_head *list = &sk->sk_receive_queue;
1520fd9c31f8SJason Xing 	int rmem, err = -ENOMEM;
15214b272750SEric Dumazet 	spinlock_t *busy = NULL;
1522c8c8b127SEric Dumazet 	int size;
1523f970bd9eSPaolo Abeni 
1524f970bd9eSPaolo Abeni 	/* try to avoid the costly atomic add/sub pair when the receive
1525f970bd9eSPaolo Abeni 	 * queue is full; always allow at least a packet
1526f970bd9eSPaolo Abeni 	 */
1527f970bd9eSPaolo Abeni 	rmem = atomic_read(&sk->sk_rmem_alloc);
1528363dc73aSPaolo Abeni 	if (rmem > sk->sk_rcvbuf)
1529f970bd9eSPaolo Abeni 		goto drop;
1530f970bd9eSPaolo Abeni 
1531c8c8b127SEric Dumazet 	/* Under mem pressure, it might be helpful to help udp_recvmsg()
1532c8c8b127SEric Dumazet 	 * having linear skbs :
1533c8c8b127SEric Dumazet 	 * - Reduce memory overhead and thus increase receive queue capacity
1534c8c8b127SEric Dumazet 	 * - Less cache line misses at copyout() time
1535c8c8b127SEric Dumazet 	 * - Less work at consume_skb() (less alien page frag freeing)
1536c8c8b127SEric Dumazet 	 */
15374b272750SEric Dumazet 	if (rmem > (sk->sk_rcvbuf >> 1)) {
1538c8c8b127SEric Dumazet 		skb_condense(skb);
15394b272750SEric Dumazet 
15404b272750SEric Dumazet 		busy = busylock_acquire(sk);
15414b272750SEric Dumazet 	}
1542c8c8b127SEric Dumazet 	size = skb->truesize;
1543b65ac446SPaolo Abeni 	udp_set_dev_scratch(skb);
1544c8c8b127SEric Dumazet 
1545f970bd9eSPaolo Abeni 	/* we drop only if the receive buf is full and the receive
1546f970bd9eSPaolo Abeni 	 * queue contains some other skb
1547f970bd9eSPaolo Abeni 	 */
1548f970bd9eSPaolo Abeni 	rmem = atomic_add_return(size, &sk->sk_rmem_alloc);
1549feed8a4fSAntonio Messina 	if (rmem > (size + (unsigned int)sk->sk_rcvbuf))
1550f970bd9eSPaolo Abeni 		goto uncharge_drop;
1551f970bd9eSPaolo Abeni 
1552f970bd9eSPaolo Abeni 	spin_lock(&list->lock);
1553fd9c31f8SJason Xing 	err = udp_rmem_schedule(sk, size);
1554fd9c31f8SJason Xing 	if (err) {
1555f970bd9eSPaolo Abeni 		spin_unlock(&list->lock);
1556f970bd9eSPaolo Abeni 		goto uncharge_drop;
1557f970bd9eSPaolo Abeni 	}
1558f970bd9eSPaolo Abeni 
1559f970bd9eSPaolo Abeni 	sk->sk_forward_alloc -= size;
1560f970bd9eSPaolo Abeni 
15617c13f97fSPaolo Abeni 	/* no need to setup a destructor, we will explicitly release the
15627c13f97fSPaolo Abeni 	 * forward allocated memory on dequeue
15637c13f97fSPaolo Abeni 	 */
1564f970bd9eSPaolo Abeni 	sock_skb_set_dropcount(sk, skb);
1565f970bd9eSPaolo Abeni 
1566f970bd9eSPaolo Abeni 	__skb_queue_tail(list, skb);
1567f970bd9eSPaolo Abeni 	spin_unlock(&list->lock);
1568f970bd9eSPaolo Abeni 
1569f970bd9eSPaolo Abeni 	if (!sock_flag(sk, SOCK_DEAD))
1570f970bd9eSPaolo Abeni 		sk->sk_data_ready(sk);
1571f970bd9eSPaolo Abeni 
15724b272750SEric Dumazet 	busylock_release(busy);
1573f970bd9eSPaolo Abeni 	return 0;
1574f970bd9eSPaolo Abeni 
1575f970bd9eSPaolo Abeni uncharge_drop:
1576f970bd9eSPaolo Abeni 	atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
1577f970bd9eSPaolo Abeni 
1578f970bd9eSPaolo Abeni drop:
1579f970bd9eSPaolo Abeni 	atomic_inc(&sk->sk_drops);
15804b272750SEric Dumazet 	busylock_release(busy);
1581f970bd9eSPaolo Abeni 	return err;
1582f970bd9eSPaolo Abeni }
1583f970bd9eSPaolo Abeni EXPORT_SYMBOL_GPL(__udp_enqueue_schedule_skb);
1584f970bd9eSPaolo Abeni 
1585d38afeecSKuniyuki Iwashima void udp_destruct_common(struct sock *sk)
1586f970bd9eSPaolo Abeni {
1587f970bd9eSPaolo Abeni 	/* reclaim completely the forward allocated memory */
15882276f58aSPaolo Abeni 	struct udp_sock *up = udp_sk(sk);
15897c13f97fSPaolo Abeni 	unsigned int total = 0;
15907c13f97fSPaolo Abeni 	struct sk_buff *skb;
15917c13f97fSPaolo Abeni 
15922276f58aSPaolo Abeni 	skb_queue_splice_tail_init(&sk->sk_receive_queue, &up->reader_queue);
15932276f58aSPaolo Abeni 	while ((skb = __skb_dequeue(&up->reader_queue)) != NULL) {
15947c13f97fSPaolo Abeni 		total += skb->truesize;
15957c13f97fSPaolo Abeni 		kfree_skb(skb);
15967c13f97fSPaolo Abeni 	}
15976dfb4367SPaolo Abeni 	udp_rmem_release(sk, total, 0, true);
1598d38afeecSKuniyuki Iwashima }
1599d38afeecSKuniyuki Iwashima EXPORT_SYMBOL_GPL(udp_destruct_common);
16007c13f97fSPaolo Abeni 
1601d38afeecSKuniyuki Iwashima static void udp_destruct_sock(struct sock *sk)
1602d38afeecSKuniyuki Iwashima {
1603d38afeecSKuniyuki Iwashima 	udp_destruct_common(sk);
1604f970bd9eSPaolo Abeni 	inet_sock_destruct(sk);
1605f970bd9eSPaolo Abeni }
1606f970bd9eSPaolo Abeni 
1607f970bd9eSPaolo Abeni int udp_init_sock(struct sock *sk)
1608f970bd9eSPaolo Abeni {
16098a3854c7SPaolo Abeni 	udp_lib_init_sock(sk);
1610f970bd9eSPaolo Abeni 	sk->sk_destruct = udp_destruct_sock;
1611e993ffe3SPavel Begunkov 	set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
1612f970bd9eSPaolo Abeni 	return 0;
1613f970bd9eSPaolo Abeni }
1614f970bd9eSPaolo Abeni 
1615f970bd9eSPaolo Abeni void skb_consume_udp(struct sock *sk, struct sk_buff *skb, int len)
1616f970bd9eSPaolo Abeni {
1617f970bd9eSPaolo Abeni 	if (unlikely(READ_ONCE(sk->sk_peek_off) >= 0)) {
1618f970bd9eSPaolo Abeni 		bool slow = lock_sock_fast(sk);
1619f970bd9eSPaolo Abeni 
1620f970bd9eSPaolo Abeni 		sk_peek_offset_bwd(sk, len);
1621f970bd9eSPaolo Abeni 		unlock_sock_fast(sk, slow);
1622f970bd9eSPaolo Abeni 	}
16230a463c78SPaolo Abeni 
1624ca2c1418SPaolo Abeni 	if (!skb_unref(skb))
1625ca2c1418SPaolo Abeni 		return;
1626ca2c1418SPaolo Abeni 
1627dce4551cSPaolo Abeni 	/* In the more common cases we cleared the head states previously,
1628dce4551cSPaolo Abeni 	 * see __udp_queue_rcv_skb().
16290ddf3fb2SPaolo Abeni 	 */
1630dce4551cSPaolo Abeni 	if (unlikely(udp_skb_has_head_state(skb)))
16310ddf3fb2SPaolo Abeni 		skb_release_head_state(skb);
1632ca2c1418SPaolo Abeni 	__consume_stateless_skb(skb);
1633f970bd9eSPaolo Abeni }
1634f970bd9eSPaolo Abeni EXPORT_SYMBOL_GPL(skb_consume_udp);
1635f970bd9eSPaolo Abeni 
16362276f58aSPaolo Abeni static struct sk_buff *__first_packet_length(struct sock *sk,
16372276f58aSPaolo Abeni 					     struct sk_buff_head *rcvq,
16382276f58aSPaolo Abeni 					     int *total)
16392276f58aSPaolo Abeni {
16402276f58aSPaolo Abeni 	struct sk_buff *skb;
16412276f58aSPaolo Abeni 
16429bd780f5SPaolo Abeni 	while ((skb = skb_peek(rcvq)) != NULL) {
16439bd780f5SPaolo Abeni 		if (udp_lib_checksum_complete(skb)) {
16442276f58aSPaolo Abeni 			__UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS,
16452276f58aSPaolo Abeni 					IS_UDPLITE(sk));
16462276f58aSPaolo Abeni 			__UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS,
16472276f58aSPaolo Abeni 					IS_UDPLITE(sk));
16482276f58aSPaolo Abeni 			atomic_inc(&sk->sk_drops);
16492276f58aSPaolo Abeni 			__skb_unlink(skb, rcvq);
16502276f58aSPaolo Abeni 			*total += skb->truesize;
16512276f58aSPaolo Abeni 			kfree_skb(skb);
16529bd780f5SPaolo Abeni 		} else {
1653a793183cSEric Dumazet 			udp_skb_csum_unnecessary_set(skb);
16549bd780f5SPaolo Abeni 			break;
16559bd780f5SPaolo Abeni 		}
16562276f58aSPaolo Abeni 	}
16572276f58aSPaolo Abeni 	return skb;
16582276f58aSPaolo Abeni }
16592276f58aSPaolo Abeni 
166085584672SEric Dumazet /**
166185584672SEric Dumazet  *	first_packet_length	- return length of first packet in receive queue
166285584672SEric Dumazet  *	@sk: socket
166385584672SEric Dumazet  *
166485584672SEric Dumazet  *	Drops all bad checksum frames, until a valid one is found.
1665e83c6744SEric Dumazet  *	Returns the length of found skb, or -1 if none is found.
166685584672SEric Dumazet  */
1667e83c6744SEric Dumazet static int first_packet_length(struct sock *sk)
166885584672SEric Dumazet {
16692276f58aSPaolo Abeni 	struct sk_buff_head *rcvq = &udp_sk(sk)->reader_queue;
16702276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
167185584672SEric Dumazet 	struct sk_buff *skb;
16727c13f97fSPaolo Abeni 	int total = 0;
1673e83c6744SEric Dumazet 	int res;
167485584672SEric Dumazet 
167585584672SEric Dumazet 	spin_lock_bh(&rcvq->lock);
16762276f58aSPaolo Abeni 	skb = __first_packet_length(sk, rcvq, &total);
1677137a0dbeSEric Dumazet 	if (!skb && !skb_queue_empty_lockless(sk_queue)) {
16782276f58aSPaolo Abeni 		spin_lock(&sk_queue->lock);
16792276f58aSPaolo Abeni 		skb_queue_splice_tail_init(sk_queue, rcvq);
16802276f58aSPaolo Abeni 		spin_unlock(&sk_queue->lock);
16812276f58aSPaolo Abeni 
16822276f58aSPaolo Abeni 		skb = __first_packet_length(sk, rcvq, &total);
168385584672SEric Dumazet 	}
1684e83c6744SEric Dumazet 	res = skb ? skb->len : -1;
16857c13f97fSPaolo Abeni 	if (total)
16866dfb4367SPaolo Abeni 		udp_rmem_release(sk, total, 1, false);
168785584672SEric Dumazet 	spin_unlock_bh(&rcvq->lock);
168885584672SEric Dumazet 	return res;
168985584672SEric Dumazet }
169085584672SEric Dumazet 
16911da177e4SLinus Torvalds /*
16921da177e4SLinus Torvalds  *	IOCTL requests applicable to the UDP protocol
16931da177e4SLinus Torvalds  */
16941da177e4SLinus Torvalds 
16951da177e4SLinus Torvalds int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
16961da177e4SLinus Torvalds {
16976516c655SStephen Hemminger 	switch (cmd) {
16981da177e4SLinus Torvalds 	case SIOCOUTQ:
16991da177e4SLinus Torvalds 	{
170031e6d363SEric Dumazet 		int amount = sk_wmem_alloc_get(sk);
170131e6d363SEric Dumazet 
17021da177e4SLinus Torvalds 		return put_user(amount, (int __user *)arg);
17031da177e4SLinus Torvalds 	}
17041da177e4SLinus Torvalds 
17051da177e4SLinus Torvalds 	case SIOCINQ:
17061da177e4SLinus Torvalds 	{
1707e83c6744SEric Dumazet 		int amount = max_t(int, 0, first_packet_length(sk));
17081da177e4SLinus Torvalds 
17091da177e4SLinus Torvalds 		return put_user(amount, (int __user *)arg);
17101da177e4SLinus Torvalds 	}
17111da177e4SLinus Torvalds 
17121da177e4SLinus Torvalds 	default:
17131da177e4SLinus Torvalds 		return -ENOIOCTLCMD;
17141da177e4SLinus Torvalds 	}
17156516c655SStephen Hemminger 
17166516c655SStephen Hemminger 	return 0;
17171da177e4SLinus Torvalds }
1718c482c568SEric Dumazet EXPORT_SYMBOL(udp_ioctl);
17191da177e4SLinus Torvalds 
17202276f58aSPaolo Abeni struct sk_buff *__skb_recv_udp(struct sock *sk, unsigned int flags,
1721ec095263SOliver Hartkopp 			       int *off, int *err)
17222276f58aSPaolo Abeni {
17232276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
17242276f58aSPaolo Abeni 	struct sk_buff_head *queue;
17252276f58aSPaolo Abeni 	struct sk_buff *last;
17262276f58aSPaolo Abeni 	long timeo;
17272276f58aSPaolo Abeni 	int error;
17282276f58aSPaolo Abeni 
17292276f58aSPaolo Abeni 	queue = &udp_sk(sk)->reader_queue;
17302276f58aSPaolo Abeni 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
17312276f58aSPaolo Abeni 	do {
17322276f58aSPaolo Abeni 		struct sk_buff *skb;
17332276f58aSPaolo Abeni 
17342276f58aSPaolo Abeni 		error = sock_error(sk);
17352276f58aSPaolo Abeni 		if (error)
17362276f58aSPaolo Abeni 			break;
17372276f58aSPaolo Abeni 
17382276f58aSPaolo Abeni 		error = -EAGAIN;
17392276f58aSPaolo Abeni 		do {
17402276f58aSPaolo Abeni 			spin_lock_bh(&queue->lock);
1741e427cad6SPaolo Abeni 			skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1742e427cad6SPaolo Abeni 							err, &last);
17432276f58aSPaolo Abeni 			if (skb) {
1744e427cad6SPaolo Abeni 				if (!(flags & MSG_PEEK))
1745e427cad6SPaolo Abeni 					udp_skb_destructor(sk, skb);
17462276f58aSPaolo Abeni 				spin_unlock_bh(&queue->lock);
17472276f58aSPaolo Abeni 				return skb;
17482276f58aSPaolo Abeni 			}
17492276f58aSPaolo Abeni 
1750137a0dbeSEric Dumazet 			if (skb_queue_empty_lockless(sk_queue)) {
17512276f58aSPaolo Abeni 				spin_unlock_bh(&queue->lock);
17522276f58aSPaolo Abeni 				goto busy_check;
17532276f58aSPaolo Abeni 			}
17542276f58aSPaolo Abeni 
17556dfb4367SPaolo Abeni 			/* refill the reader queue and walk it again
17566dfb4367SPaolo Abeni 			 * keep both queues locked to avoid re-acquiring
17576dfb4367SPaolo Abeni 			 * the sk_receive_queue lock if fwd memory scheduling
17586dfb4367SPaolo Abeni 			 * is needed.
17596dfb4367SPaolo Abeni 			 */
17602276f58aSPaolo Abeni 			spin_lock(&sk_queue->lock);
17612276f58aSPaolo Abeni 			skb_queue_splice_tail_init(sk_queue, queue);
17622276f58aSPaolo Abeni 
1763e427cad6SPaolo Abeni 			skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1764e427cad6SPaolo Abeni 							err, &last);
1765e427cad6SPaolo Abeni 			if (skb && !(flags & MSG_PEEK))
1766e427cad6SPaolo Abeni 				udp_skb_dtor_locked(sk, skb);
17676dfb4367SPaolo Abeni 			spin_unlock(&sk_queue->lock);
17682276f58aSPaolo Abeni 			spin_unlock_bh(&queue->lock);
1769de321ed3SAndrey Vagin 			if (skb)
17702276f58aSPaolo Abeni 				return skb;
17712276f58aSPaolo Abeni 
17722276f58aSPaolo Abeni busy_check:
17732276f58aSPaolo Abeni 			if (!sk_can_busy_loop(sk))
17742276f58aSPaolo Abeni 				break;
17752276f58aSPaolo Abeni 
17762276f58aSPaolo Abeni 			sk_busy_loop(sk, flags & MSG_DONTWAIT);
1777137a0dbeSEric Dumazet 		} while (!skb_queue_empty_lockless(sk_queue));
17782276f58aSPaolo Abeni 
17792276f58aSPaolo Abeni 		/* sk_queue is empty, reader_queue may contain peeked packets */
17802276f58aSPaolo Abeni 	} while (timeo &&
1781b50b0580SSabrina Dubroca 		 !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,
1782b50b0580SSabrina Dubroca 					      &error, &timeo,
17832276f58aSPaolo Abeni 					      (struct sk_buff *)sk_queue));
17842276f58aSPaolo Abeni 
17852276f58aSPaolo Abeni 	*err = error;
17862276f58aSPaolo Abeni 	return NULL;
17872276f58aSPaolo Abeni }
17887e823644SJiri Kosina EXPORT_SYMBOL(__skb_recv_udp);
17892276f58aSPaolo Abeni 
1790965b57b4SCong Wang int udp_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
1791d7f57118SCong Wang {
1792d7f57118SCong Wang 	struct sk_buff *skb;
179378fa0d61SJohn Fastabend 	int err;
1794d7f57118SCong Wang 
179531f1fbcbSPeilin Ye try_again:
1796ec095263SOliver Hartkopp 	skb = skb_recv_udp(sk, MSG_DONTWAIT, &err);
1797d7f57118SCong Wang 	if (!skb)
1798d7f57118SCong Wang 		return err;
1799099f896fSCong Wang 
1800099f896fSCong Wang 	if (udp_lib_checksum_complete(skb)) {
180131f1fbcbSPeilin Ye 		int is_udplite = IS_UDPLITE(sk);
180231f1fbcbSPeilin Ye 		struct net *net = sock_net(sk);
180331f1fbcbSPeilin Ye 
180431f1fbcbSPeilin Ye 		__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, is_udplite);
180531f1fbcbSPeilin Ye 		__UDP_INC_STATS(net, UDP_MIB_INERRORS, is_udplite);
1806099f896fSCong Wang 		atomic_inc(&sk->sk_drops);
1807099f896fSCong Wang 		kfree_skb(skb);
180831f1fbcbSPeilin Ye 		goto try_again;
1809099f896fSCong Wang 	}
1810099f896fSCong Wang 
1811db39dfdcSPeilin Ye 	WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk));
181278fa0d61SJohn Fastabend 	return recv_actor(sk, skb);
1813d7f57118SCong Wang }
1814965b57b4SCong Wang EXPORT_SYMBOL(udp_read_skb);
1815d7f57118SCong Wang 
1816db8dac20SDavid S. Miller /*
1817db8dac20SDavid S. Miller  * 	This should be easy, if there is something there we
1818db8dac20SDavid S. Miller  * 	return it, otherwise we block.
1819db8dac20SDavid S. Miller  */
1820db8dac20SDavid S. Miller 
1821ec095263SOliver Hartkopp int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags,
1822ec095263SOliver Hartkopp 		int *addr_len)
1823db8dac20SDavid S. Miller {
1824db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1825342dfc30SSteffen Hurrle 	DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
1826db8dac20SDavid S. Miller 	struct sk_buff *skb;
182759c2cdaeSDavid S. Miller 	unsigned int ulen, copied;
1828fd69c399SPaolo Abeni 	int off, err, peeking = flags & MSG_PEEK;
1829db8dac20SDavid S. Miller 	int is_udplite = IS_UDPLITE(sk);
1830197c949eSEric Dumazet 	bool checksum_valid = false;
1831db8dac20SDavid S. Miller 
1832db8dac20SDavid S. Miller 	if (flags & MSG_ERRQUEUE)
183385fbaa75SHannes Frederic Sowa 		return ip_recv_error(sk, msg, len, addr_len);
1834db8dac20SDavid S. Miller 
1835db8dac20SDavid S. Miller try_again:
1836a0917e0bSMatthew Dawson 	off = sk_peek_offset(sk, flags);
1837ec095263SOliver Hartkopp 	skb = __skb_recv_udp(sk, flags, &off, &err);
1838db8dac20SDavid S. Miller 	if (!skb)
1839627d2d6bSsamanthakumar 		return err;
1840db8dac20SDavid S. Miller 
1841b65ac446SPaolo Abeni 	ulen = udp_skb_len(skb);
184259c2cdaeSDavid S. Miller 	copied = len;
1843627d2d6bSsamanthakumar 	if (copied > ulen - off)
1844627d2d6bSsamanthakumar 		copied = ulen - off;
184559c2cdaeSDavid S. Miller 	else if (copied < ulen)
1846db8dac20SDavid S. Miller 		msg->msg_flags |= MSG_TRUNC;
1847db8dac20SDavid S. Miller 
1848db8dac20SDavid S. Miller 	/*
1849db8dac20SDavid S. Miller 	 * If checksum is needed at all, try to do it while copying the
1850db8dac20SDavid S. Miller 	 * data.  If the data is truncated, or if we only want a partial
1851db8dac20SDavid S. Miller 	 * coverage checksum (UDP-Lite), do it before the copy.
1852db8dac20SDavid S. Miller 	 */
1853db8dac20SDavid S. Miller 
1854d21dbdfeSEric Dumazet 	if (copied < ulen || peeking ||
1855d21dbdfeSEric Dumazet 	    (is_udplite && UDP_SKB_CB(skb)->partial_cov)) {
1856b65ac446SPaolo Abeni 		checksum_valid = udp_skb_csum_unnecessary(skb) ||
1857b65ac446SPaolo Abeni 				!__udp_lib_checksum_complete(skb);
1858197c949eSEric Dumazet 		if (!checksum_valid)
1859db8dac20SDavid S. Miller 			goto csum_copy_err;
1860db8dac20SDavid S. Miller 	}
1861db8dac20SDavid S. Miller 
1862b65ac446SPaolo Abeni 	if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
1863b65ac446SPaolo Abeni 		if (udp_skb_is_linear(skb))
1864b65ac446SPaolo Abeni 			err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
1865b65ac446SPaolo Abeni 		else
1866627d2d6bSsamanthakumar 			err = skb_copy_datagram_msg(skb, off, msg, copied);
1867b65ac446SPaolo Abeni 	} else {
1868627d2d6bSsamanthakumar 		err = skb_copy_and_csum_datagram_msg(skb, off, msg);
1869db8dac20SDavid S. Miller 
1870db8dac20SDavid S. Miller 		if (err == -EINVAL)
1871db8dac20SDavid S. Miller 			goto csum_copy_err;
1872db8dac20SDavid S. Miller 	}
1873db8dac20SDavid S. Miller 
187422911fc5SEric Dumazet 	if (unlikely(err)) {
1875fd69c399SPaolo Abeni 		if (!peeking) {
1876979402b1SEric Dumazet 			atomic_inc(&sk->sk_drops);
18776aef70a8SEric Dumazet 			UDP_INC_STATS(sock_net(sk),
1878979402b1SEric Dumazet 				      UDP_MIB_INERRORS, is_udplite);
1879979402b1SEric Dumazet 		}
1880850cbaddSPaolo Abeni 		kfree_skb(skb);
1881627d2d6bSsamanthakumar 		return err;
188222911fc5SEric Dumazet 	}
1883db8dac20SDavid S. Miller 
1884fd69c399SPaolo Abeni 	if (!peeking)
18856aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
1886629ca23cSPavel Emelyanov 			      UDP_MIB_INDATAGRAMS, is_udplite);
1887db8dac20SDavid S. Miller 
18886fd1d51cSErin MacNeil 	sock_recv_cmsgs(msg, sk, skb);
1889db8dac20SDavid S. Miller 
1890db8dac20SDavid S. Miller 	/* Copy the address. */
1891c482c568SEric Dumazet 	if (sin) {
1892db8dac20SDavid S. Miller 		sin->sin_family = AF_INET;
1893db8dac20SDavid S. Miller 		sin->sin_port = udp_hdr(skb)->source;
1894db8dac20SDavid S. Miller 		sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
1895db8dac20SDavid S. Miller 		memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
1896bceaa902SHannes Frederic Sowa 		*addr_len = sizeof(*sin);
1897983695faSDaniel Borkmann 
1898983695faSDaniel Borkmann 		BPF_CGROUP_RUN_PROG_UDP4_RECVMSG_LOCK(sk,
1899983695faSDaniel Borkmann 						      (struct sockaddr *)sin);
1900db8dac20SDavid S. Miller 	}
1901bcd1665eSPaolo Abeni 
1902bcd1665eSPaolo Abeni 	if (udp_sk(sk)->gro_enabled)
1903bcd1665eSPaolo Abeni 		udp_cmsg_recv(msg, sk, skb);
1904bcd1665eSPaolo Abeni 
1905db8dac20SDavid S. Miller 	if (inet->cmsg_flags)
1906ad959036SPaolo Abeni 		ip_cmsg_recv_offset(msg, sk, skb, sizeof(struct udphdr), off);
1907db8dac20SDavid S. Miller 
190859c2cdaeSDavid S. Miller 	err = copied;
1909db8dac20SDavid S. Miller 	if (flags & MSG_TRUNC)
1910db8dac20SDavid S. Miller 		err = ulen;
1911db8dac20SDavid S. Miller 
1912850cbaddSPaolo Abeni 	skb_consume_udp(sk, skb, peeking ? -err : err);
1913db8dac20SDavid S. Miller 	return err;
1914db8dac20SDavid S. Miller 
1915db8dac20SDavid S. Miller csum_copy_err:
19162276f58aSPaolo Abeni 	if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags,
19172276f58aSPaolo Abeni 				 udp_skb_destructor)) {
19186aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
19196aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
19206a5dc9e5SEric Dumazet 	}
1921850cbaddSPaolo Abeni 	kfree_skb(skb);
1922db8dac20SDavid S. Miller 
1923beb39db5SEric Dumazet 	/* starting over for a new packet, but check if we need to yield */
1924beb39db5SEric Dumazet 	cond_resched();
19259cfaa8deSXufeng Zhang 	msg->msg_flags &= ~MSG_TRUNC;
1926db8dac20SDavid S. Miller 	goto try_again;
1927db8dac20SDavid S. Miller }
1928db8dac20SDavid S. Miller 
1929d74bad4eSAndrey Ignatov int udp_pre_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
1930d74bad4eSAndrey Ignatov {
1931d74bad4eSAndrey Ignatov 	/* This check is replicated from __ip4_datagram_connect() and
1932d74bad4eSAndrey Ignatov 	 * intended to prevent BPF program called below from accessing bytes
1933d74bad4eSAndrey Ignatov 	 * that are out of the bound specified by user in addr_len.
1934d74bad4eSAndrey Ignatov 	 */
1935d74bad4eSAndrey Ignatov 	if (addr_len < sizeof(struct sockaddr_in))
1936d74bad4eSAndrey Ignatov 		return -EINVAL;
1937d74bad4eSAndrey Ignatov 
1938d74bad4eSAndrey Ignatov 	return BPF_CGROUP_RUN_PROG_INET4_CONNECT_LOCK(sk, uaddr);
1939d74bad4eSAndrey Ignatov }
1940d74bad4eSAndrey Ignatov EXPORT_SYMBOL(udp_pre_connect);
1941d74bad4eSAndrey Ignatov 
1942286c72deSEric Dumazet int __udp_disconnect(struct sock *sk, int flags)
19431da177e4SLinus Torvalds {
19441da177e4SLinus Torvalds 	struct inet_sock *inet = inet_sk(sk);
19451da177e4SLinus Torvalds 	/*
19461da177e4SLinus Torvalds 	 *	1003.1g - break association.
19471da177e4SLinus Torvalds 	 */
19481da177e4SLinus Torvalds 
19491da177e4SLinus Torvalds 	sk->sk_state = TCP_CLOSE;
1950c720c7e8SEric Dumazet 	inet->inet_daddr = 0;
1951c720c7e8SEric Dumazet 	inet->inet_dport = 0;
1952bdeab991STom Herbert 	sock_rps_reset_rxhash(sk);
19531da177e4SLinus Torvalds 	sk->sk_bound_dev_if = 0;
1954303d0403SWillem de Bruijn 	if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) {
19551da177e4SLinus Torvalds 		inet_reset_saddr(sk);
1956303d0403SWillem de Bruijn 		if (sk->sk_prot->rehash &&
1957303d0403SWillem de Bruijn 		    (sk->sk_userlocks & SOCK_BINDPORT_LOCK))
1958303d0403SWillem de Bruijn 			sk->sk_prot->rehash(sk);
1959303d0403SWillem de Bruijn 	}
19601da177e4SLinus Torvalds 
19611da177e4SLinus Torvalds 	if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
19621da177e4SLinus Torvalds 		sk->sk_prot->unhash(sk);
1963c720c7e8SEric Dumazet 		inet->inet_sport = 0;
19641da177e4SLinus Torvalds 	}
19651da177e4SLinus Torvalds 	sk_dst_reset(sk);
19661da177e4SLinus Torvalds 	return 0;
19671da177e4SLinus Torvalds }
1968286c72deSEric Dumazet EXPORT_SYMBOL(__udp_disconnect);
1969286c72deSEric Dumazet 
1970286c72deSEric Dumazet int udp_disconnect(struct sock *sk, int flags)
1971286c72deSEric Dumazet {
1972286c72deSEric Dumazet 	lock_sock(sk);
1973286c72deSEric Dumazet 	__udp_disconnect(sk, flags);
1974286c72deSEric Dumazet 	release_sock(sk);
1975286c72deSEric Dumazet 	return 0;
1976286c72deSEric Dumazet }
1977c482c568SEric Dumazet EXPORT_SYMBOL(udp_disconnect);
19781da177e4SLinus Torvalds 
1979645ca708SEric Dumazet void udp_lib_unhash(struct sock *sk)
1980645ca708SEric Dumazet {
1981723b4610SEric Dumazet 	if (sk_hashed(sk)) {
198267fb4330SKuniyuki Iwashima 		struct udp_table *udptable = udp_get_table_prot(sk);
1983512615b6SEric Dumazet 		struct udp_hslot *hslot, *hslot2;
1984512615b6SEric Dumazet 
1985512615b6SEric Dumazet 		hslot  = udp_hashslot(udptable, sock_net(sk),
1986d4cada4aSEric Dumazet 				      udp_sk(sk)->udp_port_hash);
1987512615b6SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
1988645ca708SEric Dumazet 
1989c8db3fecSEric Dumazet 		spin_lock_bh(&hslot->lock);
1990e32ea7e7SCraig Gallek 		if (rcu_access_pointer(sk->sk_reuseport_cb))
1991e32ea7e7SCraig Gallek 			reuseport_detach_sock(sk);
1992ca065d0cSEric Dumazet 		if (sk_del_node_init_rcu(sk)) {
1993fdcc8aa9SEric Dumazet 			hslot->count--;
1994c720c7e8SEric Dumazet 			inet_sk(sk)->inet_num = 0;
1995645ca708SEric Dumazet 			sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
1996512615b6SEric Dumazet 
1997512615b6SEric Dumazet 			spin_lock(&hslot2->lock);
1998ca065d0cSEric Dumazet 			hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
1999512615b6SEric Dumazet 			hslot2->count--;
2000512615b6SEric Dumazet 			spin_unlock(&hslot2->lock);
2001645ca708SEric Dumazet 		}
2002c8db3fecSEric Dumazet 		spin_unlock_bh(&hslot->lock);
2003645ca708SEric Dumazet 	}
2004723b4610SEric Dumazet }
2005645ca708SEric Dumazet EXPORT_SYMBOL(udp_lib_unhash);
2006645ca708SEric Dumazet 
2007719f8358SEric Dumazet /*
2008719f8358SEric Dumazet  * inet_rcv_saddr was changed, we must rehash secondary hash
2009719f8358SEric Dumazet  */
2010719f8358SEric Dumazet void udp_lib_rehash(struct sock *sk, u16 newhash)
2011719f8358SEric Dumazet {
2012719f8358SEric Dumazet 	if (sk_hashed(sk)) {
201367fb4330SKuniyuki Iwashima 		struct udp_table *udptable = udp_get_table_prot(sk);
2014719f8358SEric Dumazet 		struct udp_hslot *hslot, *hslot2, *nhslot2;
2015719f8358SEric Dumazet 
2016719f8358SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
2017719f8358SEric Dumazet 		nhslot2 = udp_hashslot2(udptable, newhash);
2018719f8358SEric Dumazet 		udp_sk(sk)->udp_portaddr_hash = newhash;
2019e32ea7e7SCraig Gallek 
2020e32ea7e7SCraig Gallek 		if (hslot2 != nhslot2 ||
2021e32ea7e7SCraig Gallek 		    rcu_access_pointer(sk->sk_reuseport_cb)) {
2022719f8358SEric Dumazet 			hslot = udp_hashslot(udptable, sock_net(sk),
2023719f8358SEric Dumazet 					     udp_sk(sk)->udp_port_hash);
2024719f8358SEric Dumazet 			/* we must lock primary chain too */
2025719f8358SEric Dumazet 			spin_lock_bh(&hslot->lock);
2026e32ea7e7SCraig Gallek 			if (rcu_access_pointer(sk->sk_reuseport_cb))
2027e32ea7e7SCraig Gallek 				reuseport_detach_sock(sk);
2028719f8358SEric Dumazet 
2029e32ea7e7SCraig Gallek 			if (hslot2 != nhslot2) {
2030719f8358SEric Dumazet 				spin_lock(&hslot2->lock);
2031ca065d0cSEric Dumazet 				hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
2032719f8358SEric Dumazet 				hslot2->count--;
2033719f8358SEric Dumazet 				spin_unlock(&hslot2->lock);
2034719f8358SEric Dumazet 
2035719f8358SEric Dumazet 				spin_lock(&nhslot2->lock);
2036ca065d0cSEric Dumazet 				hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
2037719f8358SEric Dumazet 							 &nhslot2->head);
2038719f8358SEric Dumazet 				nhslot2->count++;
2039719f8358SEric Dumazet 				spin_unlock(&nhslot2->lock);
2040e32ea7e7SCraig Gallek 			}
2041719f8358SEric Dumazet 
2042719f8358SEric Dumazet 			spin_unlock_bh(&hslot->lock);
2043719f8358SEric Dumazet 		}
2044719f8358SEric Dumazet 	}
2045719f8358SEric Dumazet }
2046719f8358SEric Dumazet EXPORT_SYMBOL(udp_lib_rehash);
2047719f8358SEric Dumazet 
20488f6b5392SAlexey Kodanev void udp_v4_rehash(struct sock *sk)
2049719f8358SEric Dumazet {
2050f0b1e64cSMartin KaFai Lau 	u16 new_hash = ipv4_portaddr_hash(sock_net(sk),
2051719f8358SEric Dumazet 					  inet_sk(sk)->inet_rcv_saddr,
2052719f8358SEric Dumazet 					  inet_sk(sk)->inet_num);
2053719f8358SEric Dumazet 	udp_lib_rehash(sk, new_hash);
2054719f8358SEric Dumazet }
2055719f8358SEric Dumazet 
2056a3f96c47SPaolo Abeni static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
205793821778SHerbert Xu {
2058fec5e652STom Herbert 	int rc;
205993821778SHerbert Xu 
2060005ec974SShawn Bohrer 	if (inet_sk(sk)->inet_daddr) {
2061bdeab991STom Herbert 		sock_rps_save_rxhash(sk, skb);
2062005ec974SShawn Bohrer 		sk_mark_napi_id(sk, skb);
20632c8c56e1SEric Dumazet 		sk_incoming_cpu_update(sk);
2064e68b6e50SEric Dumazet 	} else {
2065e68b6e50SEric Dumazet 		sk_mark_napi_id_once(sk, skb);
2066005ec974SShawn Bohrer 	}
2067fec5e652STom Herbert 
2068850cbaddSPaolo Abeni 	rc = __udp_enqueue_schedule_skb(sk, skb);
2069766e9037SEric Dumazet 	if (rc < 0) {
2070766e9037SEric Dumazet 		int is_udplite = IS_UDPLITE(sk);
207108d4c037SMenglong Dong 		int drop_reason;
2072766e9037SEric Dumazet 
207393821778SHerbert Xu 		/* Note that an ENOMEM error is charged twice */
207408d4c037SMenglong Dong 		if (rc == -ENOMEM) {
2075e61da9e2SEric Dumazet 			UDP_INC_STATS(sock_net(sk), UDP_MIB_RCVBUFERRORS,
207693821778SHerbert Xu 					is_udplite);
207708d4c037SMenglong Dong 			drop_reason = SKB_DROP_REASON_SOCKET_RCVBUFF;
207808d4c037SMenglong Dong 		} else {
2079a3ce2b10SMenglong Dong 			UDP_INC_STATS(sock_net(sk), UDP_MIB_MEMERRORS,
2080a3ce2b10SMenglong Dong 				      is_udplite);
208108d4c037SMenglong Dong 			drop_reason = SKB_DROP_REASON_PROTO_MEM;
208208d4c037SMenglong Dong 		}
2083e61da9e2SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
208408d4c037SMenglong Dong 		kfree_skb_reason(skb, drop_reason);
2085296f7ea7SSatoru Moriya 		trace_udp_fail_queue_rcv_skb(rc, sk);
2086766e9037SEric Dumazet 		return -1;
208793821778SHerbert Xu 	}
208893821778SHerbert Xu 
208993821778SHerbert Xu 	return 0;
209093821778SHerbert Xu }
209193821778SHerbert Xu 
2092db8dac20SDavid S. Miller /* returns:
2093db8dac20SDavid S. Miller  *  -1: error
2094db8dac20SDavid S. Miller  *   0: success
2095db8dac20SDavid S. Miller  *  >0: "udp encap" protocol resubmission
2096db8dac20SDavid S. Miller  *
2097db8dac20SDavid S. Miller  * Note that in the success and error cases, the skb is assumed to
2098db8dac20SDavid S. Miller  * have either been requeued or freed.
2099db8dac20SDavid S. Miller  */
2100cf329aa4SPaolo Abeni static int udp_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
2101db8dac20SDavid S. Miller {
21021379a92dSMenglong Dong 	int drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2103db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
2104db8dac20SDavid S. Miller 	int is_udplite = IS_UDPLITE(sk);
2105db8dac20SDavid S. Miller 
2106db8dac20SDavid S. Miller 	/*
2107db8dac20SDavid S. Miller 	 *	Charge it to the socket, dropping if the queue is full.
2108db8dac20SDavid S. Miller 	 */
21091379a92dSMenglong Dong 	if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
21101379a92dSMenglong Dong 		drop_reason = SKB_DROP_REASON_XFRM_POLICY;
2111db8dac20SDavid S. Miller 		goto drop;
21121379a92dSMenglong Dong 	}
2113895b5c9fSFlorian Westphal 	nf_reset_ct(skb);
2114db8dac20SDavid S. Miller 
211588ab3108SDavidlohr Bueso 	if (static_branch_unlikely(&udp_encap_needed_key) && up->encap_type) {
21160ad92ad0SEric Dumazet 		int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
21170ad92ad0SEric Dumazet 
2118db8dac20SDavid S. Miller 		/*
2119db8dac20SDavid S. Miller 		 * This is an encapsulation socket so pass the skb to
2120db8dac20SDavid S. Miller 		 * the socket's udp_encap_rcv() hook. Otherwise, just
2121db8dac20SDavid S. Miller 		 * fall through and pass this up the UDP socket.
2122db8dac20SDavid S. Miller 		 * up->encap_rcv() returns the following value:
2123db8dac20SDavid S. Miller 		 * =0 if skb was successfully passed to the encap
2124db8dac20SDavid S. Miller 		 *    handler or was discarded by it.
2125db8dac20SDavid S. Miller 		 * >0 if skb should be passed on to UDP.
2126db8dac20SDavid S. Miller 		 * <0 if skb should be resubmitted as proto -N
2127db8dac20SDavid S. Miller 		 */
2128db8dac20SDavid S. Miller 
2129db8dac20SDavid S. Miller 		/* if we're overly short, let UDP handle it */
21306aa7de05SMark Rutland 		encap_rcv = READ_ONCE(up->encap_rcv);
2131e5aed006SHannes Frederic Sowa 		if (encap_rcv) {
2132db8dac20SDavid S. Miller 			int ret;
2133db8dac20SDavid S. Miller 
21340a80966bSTom Herbert 			/* Verify checksum before giving to encap */
21350a80966bSTom Herbert 			if (udp_lib_checksum_complete(skb))
21360a80966bSTom Herbert 				goto csum_error;
21370a80966bSTom Herbert 
21380ad92ad0SEric Dumazet 			ret = encap_rcv(sk, skb);
2139db8dac20SDavid S. Miller 			if (ret <= 0) {
214002c22347SEric Dumazet 				__UDP_INC_STATS(sock_net(sk),
21410283328eSPavel Emelyanov 						UDP_MIB_INDATAGRAMS,
2142db8dac20SDavid S. Miller 						is_udplite);
2143db8dac20SDavid S. Miller 				return -ret;
2144db8dac20SDavid S. Miller 			}
2145db8dac20SDavid S. Miller 		}
2146db8dac20SDavid S. Miller 
2147db8dac20SDavid S. Miller 		/* FALLTHROUGH -- it's a UDP Packet */
2148db8dac20SDavid S. Miller 	}
2149db8dac20SDavid S. Miller 
2150db8dac20SDavid S. Miller 	/*
2151db8dac20SDavid S. Miller 	 * 	UDP-Lite specific tests, ignored on UDP sockets
2152db8dac20SDavid S. Miller 	 */
2153b0a42277SMiaohe Lin 	if ((up->pcflag & UDPLITE_RECV_CC)  &&  UDP_SKB_CB(skb)->partial_cov) {
2154db8dac20SDavid S. Miller 
2155db8dac20SDavid S. Miller 		/*
2156db8dac20SDavid S. Miller 		 * MIB statistics other than incrementing the error count are
2157db8dac20SDavid S. Miller 		 * disabled for the following two types of errors: these depend
2158db8dac20SDavid S. Miller 		 * on the application settings, not on the functioning of the
2159db8dac20SDavid S. Miller 		 * protocol stack as such.
2160db8dac20SDavid S. Miller 		 *
2161db8dac20SDavid S. Miller 		 * RFC 3828 here recommends (sec 3.3): "There should also be a
2162db8dac20SDavid S. Miller 		 * way ... to ... at least let the receiving application block
2163db8dac20SDavid S. Miller 		 * delivery of packets with coverage values less than a value
2164db8dac20SDavid S. Miller 		 * provided by the application."
2165db8dac20SDavid S. Miller 		 */
2166db8dac20SDavid S. Miller 		if (up->pcrlen == 0) {          /* full coverage was set  */
2167ba7a46f1SJoe Perches 			net_dbg_ratelimited("UDPLite: partial coverage %d while full coverage %d requested\n",
2168db8dac20SDavid S. Miller 					    UDP_SKB_CB(skb)->cscov, skb->len);
2169db8dac20SDavid S. Miller 			goto drop;
2170db8dac20SDavid S. Miller 		}
2171db8dac20SDavid S. Miller 		/* The next case involves violating the min. coverage requested
2172db8dac20SDavid S. Miller 		 * by the receiver. This is subtle: if receiver wants x and x is
2173db8dac20SDavid S. Miller 		 * greater than the buffersize/MTU then receiver will complain
2174db8dac20SDavid S. Miller 		 * that it wants x while sender emits packets of smaller size y.
2175db8dac20SDavid S. Miller 		 * Therefore the above ...()->partial_cov statement is essential.
2176db8dac20SDavid S. Miller 		 */
2177db8dac20SDavid S. Miller 		if (UDP_SKB_CB(skb)->cscov  <  up->pcrlen) {
2178ba7a46f1SJoe Perches 			net_dbg_ratelimited("UDPLite: coverage %d too small, need min %d\n",
2179db8dac20SDavid S. Miller 					    UDP_SKB_CB(skb)->cscov, up->pcrlen);
2180db8dac20SDavid S. Miller 			goto drop;
2181db8dac20SDavid S. Miller 		}
2182db8dac20SDavid S. Miller 	}
2183db8dac20SDavid S. Miller 
2184dd99e425SPaolo Abeni 	prefetch(&sk->sk_rmem_alloc);
2185ce25d66aSEric Dumazet 	if (rcu_access_pointer(sk->sk_filter) &&
2186ce25d66aSEric Dumazet 	    udp_lib_checksum_complete(skb))
21876a5dc9e5SEric Dumazet 			goto csum_error;
2188ce25d66aSEric Dumazet 
21891379a92dSMenglong Dong 	if (sk_filter_trim_cap(sk, skb, sizeof(struct udphdr))) {
21901379a92dSMenglong Dong 		drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
2191a6127697SMichal Kubeček 		goto drop;
21921379a92dSMenglong Dong 	}
2193db8dac20SDavid S. Miller 
2194e6afc8acSsamanthakumar 	udp_csum_pull_header(skb);
2195db8dac20SDavid S. Miller 
2196fbf8866dSShawn Bohrer 	ipv4_pktinfo_prepare(sk, skb);
2197850cbaddSPaolo Abeni 	return __udp_queue_rcv_skb(sk, skb);
2198db8dac20SDavid S. Miller 
21996a5dc9e5SEric Dumazet csum_error:
22001379a92dSMenglong Dong 	drop_reason = SKB_DROP_REASON_UDP_CSUM;
220102c22347SEric Dumazet 	__UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
2202db8dac20SDavid S. Miller drop:
220302c22347SEric Dumazet 	__UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
22048edf19c2SEric Dumazet 	atomic_inc(&sk->sk_drops);
22051379a92dSMenglong Dong 	kfree_skb_reason(skb, drop_reason);
2206db8dac20SDavid S. Miller 	return -1;
2207db8dac20SDavid S. Miller }
2208db8dac20SDavid S. Miller 
2209cf329aa4SPaolo Abeni static int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2210cf329aa4SPaolo Abeni {
2211cf329aa4SPaolo Abeni 	struct sk_buff *next, *segs;
2212cf329aa4SPaolo Abeni 	int ret;
2213cf329aa4SPaolo Abeni 
2214cf329aa4SPaolo Abeni 	if (likely(!udp_unexpected_gso(sk, skb)))
2215cf329aa4SPaolo Abeni 		return udp_queue_rcv_one_skb(sk, skb);
2216cf329aa4SPaolo Abeni 
2217a08e7fd9SCambda Zhu 	BUILD_BUG_ON(sizeof(struct udp_skb_cb) > SKB_GSO_CB_OFFSET);
2218cf329aa4SPaolo Abeni 	__skb_push(skb, -skb_mac_offset(skb));
2219cf329aa4SPaolo Abeni 	segs = udp_rcv_segment(sk, skb, true);
22201a186c14SJason A. Donenfeld 	skb_list_walk_safe(segs, skb, next) {
2221cf329aa4SPaolo Abeni 		__skb_pull(skb, skb_transport_offset(skb));
2222000ac44dSPaolo Abeni 
2223000ac44dSPaolo Abeni 		udp_post_segment_fix_csum(skb);
2224cf329aa4SPaolo Abeni 		ret = udp_queue_rcv_one_skb(sk, skb);
2225cf329aa4SPaolo Abeni 		if (ret > 0)
222610c678bdSXin Long 			ip_protocol_deliver_rcu(dev_net(skb->dev), skb, ret);
2227cf329aa4SPaolo Abeni 	}
2228cf329aa4SPaolo Abeni 	return 0;
2229cf329aa4SPaolo Abeni }
2230cf329aa4SPaolo Abeni 
223197502231SEric Dumazet /* For TCP sockets, sk_rx_dst is protected by socket lock
2232e47eb5dfSEric Dumazet  * For UDP, we use xchg() to guard against concurrent changes.
223397502231SEric Dumazet  */
223464f0f5d1SPaolo Abeni bool udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
2235421b3885SShawn Bohrer {
223697502231SEric Dumazet 	struct dst_entry *old;
2237421b3885SShawn Bohrer 
2238d24406c8SWei Wang 	if (dst_hold_safe(dst)) {
22398f905c0eSEric Dumazet 		old = xchg((__force struct dst_entry **)&sk->sk_rx_dst, dst);
224097502231SEric Dumazet 		dst_release(old);
224164f0f5d1SPaolo Abeni 		return old != dst;
224297502231SEric Dumazet 	}
224364f0f5d1SPaolo Abeni 	return false;
2244d24406c8SWei Wang }
2245c9f2c1aeSPaolo Abeni EXPORT_SYMBOL(udp_sk_rx_dst_set);
2246421b3885SShawn Bohrer 
2247db8dac20SDavid S. Miller /*
2248db8dac20SDavid S. Miller  *	Multicasts and broadcasts go to each listener.
2249db8dac20SDavid S. Miller  *
22501240d137SEric Dumazet  *	Note: called only from the BH handler context.
2251db8dac20SDavid S. Miller  */
2252e3163493SPavel Emelyanov static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
2253db8dac20SDavid S. Miller 				    struct udphdr  *uh,
2254db8dac20SDavid S. Miller 				    __be32 saddr, __be32 daddr,
225536cbb245SRick Jones 				    struct udp_table *udptable,
225636cbb245SRick Jones 				    int proto)
2257db8dac20SDavid S. Miller {
2258ca065d0cSEric Dumazet 	struct sock *sk, *first = NULL;
22595cf3d461SDavid Held 	unsigned short hnum = ntohs(uh->dest);
22605cf3d461SDavid Held 	struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum);
22612dc41cffSDavid Held 	unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10);
2262ca065d0cSEric Dumazet 	unsigned int offset = offsetof(typeof(*sk), sk_node);
2263ca065d0cSEric Dumazet 	int dif = skb->dev->ifindex;
2264fb74c277SDavid Ahern 	int sdif = inet_sdif(skb);
2265ca065d0cSEric Dumazet 	struct hlist_node *node;
2266ca065d0cSEric Dumazet 	struct sk_buff *nskb;
22672dc41cffSDavid Held 
22682dc41cffSDavid Held 	if (use_hash2) {
2269f0b1e64cSMartin KaFai Lau 		hash2_any = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum) &
227073e2d5e3SPablo Neira 			    udptable->mask;
2271f0b1e64cSMartin KaFai Lau 		hash2 = ipv4_portaddr_hash(net, daddr, hnum) & udptable->mask;
22722dc41cffSDavid Held start_lookup:
227373e2d5e3SPablo Neira 		hslot = &udptable->hash2[hash2];
22742dc41cffSDavid Held 		offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
22752dc41cffSDavid Held 	}
2276db8dac20SDavid S. Miller 
2277ca065d0cSEric Dumazet 	sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
2278ca065d0cSEric Dumazet 		if (!__udp_is_mcast_sock(net, sk, uh->dest, daddr,
2279fb74c277SDavid Ahern 					 uh->source, saddr, dif, sdif, hnum))
2280ca065d0cSEric Dumazet 			continue;
22811240d137SEric Dumazet 
2282ca065d0cSEric Dumazet 		if (!first) {
2283ca065d0cSEric Dumazet 			first = sk;
2284ca065d0cSEric Dumazet 			continue;
2285ca065d0cSEric Dumazet 		}
2286ca065d0cSEric Dumazet 		nskb = skb_clone(skb, GFP_ATOMIC);
2287ca065d0cSEric Dumazet 
2288ca065d0cSEric Dumazet 		if (unlikely(!nskb)) {
2289ca065d0cSEric Dumazet 			atomic_inc(&sk->sk_drops);
229002c22347SEric Dumazet 			__UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS,
2291ca065d0cSEric Dumazet 					IS_UDPLITE(sk));
229202c22347SEric Dumazet 			__UDP_INC_STATS(net, UDP_MIB_INERRORS,
2293ca065d0cSEric Dumazet 					IS_UDPLITE(sk));
2294ca065d0cSEric Dumazet 			continue;
2295ca065d0cSEric Dumazet 		}
2296ca065d0cSEric Dumazet 		if (udp_queue_rcv_skb(sk, nskb) > 0)
2297ca065d0cSEric Dumazet 			consume_skb(nskb);
2298ca065d0cSEric Dumazet 	}
22991240d137SEric Dumazet 
23002dc41cffSDavid Held 	/* Also lookup *:port if we are using hash2 and haven't done so yet. */
23012dc41cffSDavid Held 	if (use_hash2 && hash2 != hash2_any) {
23022dc41cffSDavid Held 		hash2 = hash2_any;
23032dc41cffSDavid Held 		goto start_lookup;
23042dc41cffSDavid Held 	}
23052dc41cffSDavid Held 
2306ca065d0cSEric Dumazet 	if (first) {
2307ca065d0cSEric Dumazet 		if (udp_queue_rcv_skb(first, skb) > 0)
2308ca065d0cSEric Dumazet 			consume_skb(skb);
23091240d137SEric Dumazet 	} else {
2310ca065d0cSEric Dumazet 		kfree_skb(skb);
231102c22347SEric Dumazet 		__UDP_INC_STATS(net, UDP_MIB_IGNOREDMULTI,
231236cbb245SRick Jones 				proto == IPPROTO_UDPLITE);
23131240d137SEric Dumazet 	}
2314db8dac20SDavid S. Miller 	return 0;
2315db8dac20SDavid S. Miller }
2316db8dac20SDavid S. Miller 
2317db8dac20SDavid S. Miller /* Initialize UDP checksum. If exited with zero value (success),
2318db8dac20SDavid S. Miller  * CHECKSUM_UNNECESSARY means, that no more checks are required.
2319666a3d6eSSu Yanjun  * Otherwise, csum completion requires checksumming packet body,
2320db8dac20SDavid S. Miller  * including udp header and folding it to skb->csum.
2321db8dac20SDavid S. Miller  */
2322db8dac20SDavid S. Miller static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
2323db8dac20SDavid S. Miller 				 int proto)
2324db8dac20SDavid S. Miller {
2325db8dac20SDavid S. Miller 	int err;
2326db8dac20SDavid S. Miller 
2327db8dac20SDavid S. Miller 	UDP_SKB_CB(skb)->partial_cov = 0;
2328db8dac20SDavid S. Miller 	UDP_SKB_CB(skb)->cscov = skb->len;
2329db8dac20SDavid S. Miller 
2330db8dac20SDavid S. Miller 	if (proto == IPPROTO_UDPLITE) {
2331db8dac20SDavid S. Miller 		err = udplite_checksum_init(skb, uh);
2332db8dac20SDavid S. Miller 		if (err)
2333db8dac20SDavid S. Miller 			return err;
233415f35d49SAlexey Kodanev 
233515f35d49SAlexey Kodanev 		if (UDP_SKB_CB(skb)->partial_cov) {
233615f35d49SAlexey Kodanev 			skb->csum = inet_compute_pseudo(skb, proto);
233715f35d49SAlexey Kodanev 			return 0;
233815f35d49SAlexey Kodanev 		}
2339db8dac20SDavid S. Miller 	}
2340db8dac20SDavid S. Miller 
2341b46d9f62SHannes Frederic Sowa 	/* Note, we are only interested in != 0 or == 0, thus the
2342b46d9f62SHannes Frederic Sowa 	 * force to int.
2343b46d9f62SHannes Frederic Sowa 	 */
2344db4f1be3SSean Tranchetti 	err = (__force int)skb_checksum_init_zero_check(skb, proto, uh->check,
2345ed70fcfcSTom Herbert 							inet_compute_pseudo);
2346db4f1be3SSean Tranchetti 	if (err)
2347db4f1be3SSean Tranchetti 		return err;
2348db4f1be3SSean Tranchetti 
2349db4f1be3SSean Tranchetti 	if (skb->ip_summed == CHECKSUM_COMPLETE && !skb->csum_valid) {
2350db4f1be3SSean Tranchetti 		/* If SW calculated the value, we know it's bad */
2351db4f1be3SSean Tranchetti 		if (skb->csum_complete_sw)
2352db4f1be3SSean Tranchetti 			return 1;
2353db4f1be3SSean Tranchetti 
2354db4f1be3SSean Tranchetti 		/* HW says the value is bad. Let's validate that.
2355db4f1be3SSean Tranchetti 		 * skb->csum is no longer the full packet checksum,
2356db4f1be3SSean Tranchetti 		 * so don't treat it as such.
2357db4f1be3SSean Tranchetti 		 */
2358db4f1be3SSean Tranchetti 		skb_checksum_complete_unset(skb);
2359db4f1be3SSean Tranchetti 	}
2360db4f1be3SSean Tranchetti 
2361db4f1be3SSean Tranchetti 	return 0;
2362db8dac20SDavid S. Miller }
2363db8dac20SDavid S. Miller 
23642b5a9217SPaolo Abeni /* wrapper for udp_queue_rcv_skb tacking care of csum conversion and
23652b5a9217SPaolo Abeni  * return code conversion for ip layer consumption
23662b5a9217SPaolo Abeni  */
23672b5a9217SPaolo Abeni static int udp_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb,
23682b5a9217SPaolo Abeni 			       struct udphdr *uh)
23692b5a9217SPaolo Abeni {
23702b5a9217SPaolo Abeni 	int ret;
23712b5a9217SPaolo Abeni 
23722b5a9217SPaolo Abeni 	if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk))
2373e4aa33adSLi RongQing 		skb_checksum_try_convert(skb, IPPROTO_UDP, inet_compute_pseudo);
23742b5a9217SPaolo Abeni 
23752b5a9217SPaolo Abeni 	ret = udp_queue_rcv_skb(sk, skb);
23762b5a9217SPaolo Abeni 
23772b5a9217SPaolo Abeni 	/* a return value > 0 means to resubmit the input, but
23782b5a9217SPaolo Abeni 	 * it wants the return to be -protocol, or 0
23792b5a9217SPaolo Abeni 	 */
23802b5a9217SPaolo Abeni 	if (ret > 0)
23812b5a9217SPaolo Abeni 		return -ret;
23822b5a9217SPaolo Abeni 	return 0;
23832b5a9217SPaolo Abeni }
23842b5a9217SPaolo Abeni 
2385db8dac20SDavid S. Miller /*
2386db8dac20SDavid S. Miller  *	All we need to do is get the socket, and then do a checksum.
2387db8dac20SDavid S. Miller  */
2388db8dac20SDavid S. Miller 
2389645ca708SEric Dumazet int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
2390db8dac20SDavid S. Miller 		   int proto)
2391db8dac20SDavid S. Miller {
2392db8dac20SDavid S. Miller 	struct sock *sk;
23937b5e56f9SJesper Dangaard Brouer 	struct udphdr *uh;
2394db8dac20SDavid S. Miller 	unsigned short ulen;
2395adf30907SEric Dumazet 	struct rtable *rt = skb_rtable(skb);
23962783ef23SJesper Dangaard Brouer 	__be32 saddr, daddr;
23970283328eSPavel Emelyanov 	struct net *net = dev_net(skb->dev);
239871489e21SJoe Stringer 	bool refcounted;
23991c7fab70SMenglong Dong 	int drop_reason;
24001c7fab70SMenglong Dong 
24011c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2402db8dac20SDavid S. Miller 
2403db8dac20SDavid S. Miller 	/*
2404db8dac20SDavid S. Miller 	 *  Validate the packet.
2405db8dac20SDavid S. Miller 	 */
2406db8dac20SDavid S. Miller 	if (!pskb_may_pull(skb, sizeof(struct udphdr)))
2407db8dac20SDavid S. Miller 		goto drop;		/* No space for header. */
2408db8dac20SDavid S. Miller 
24097b5e56f9SJesper Dangaard Brouer 	uh   = udp_hdr(skb);
2410db8dac20SDavid S. Miller 	ulen = ntohs(uh->len);
2411ccc2d97cSBjørn Mork 	saddr = ip_hdr(skb)->saddr;
2412ccc2d97cSBjørn Mork 	daddr = ip_hdr(skb)->daddr;
2413ccc2d97cSBjørn Mork 
2414db8dac20SDavid S. Miller 	if (ulen > skb->len)
2415db8dac20SDavid S. Miller 		goto short_packet;
2416db8dac20SDavid S. Miller 
2417db8dac20SDavid S. Miller 	if (proto == IPPROTO_UDP) {
2418db8dac20SDavid S. Miller 		/* UDP validates ulen. */
2419db8dac20SDavid S. Miller 		if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
2420db8dac20SDavid S. Miller 			goto short_packet;
2421db8dac20SDavid S. Miller 		uh = udp_hdr(skb);
2422db8dac20SDavid S. Miller 	}
2423db8dac20SDavid S. Miller 
2424db8dac20SDavid S. Miller 	if (udp4_csum_init(skb, uh, proto))
2425db8dac20SDavid S. Miller 		goto csum_error;
2426db8dac20SDavid S. Miller 
242771489e21SJoe Stringer 	sk = skb_steal_sock(skb, &refcounted);
24288afdd99aSEric Dumazet 	if (sk) {
242997502231SEric Dumazet 		struct dst_entry *dst = skb_dst(skb);
2430421b3885SShawn Bohrer 		int ret;
2431421b3885SShawn Bohrer 
24328f905c0eSEric Dumazet 		if (unlikely(rcu_dereference(sk->sk_rx_dst) != dst))
243397502231SEric Dumazet 			udp_sk_rx_dst_set(sk, dst);
2434421b3885SShawn Bohrer 
24352b5a9217SPaolo Abeni 		ret = udp_unicast_rcv_skb(sk, skb, uh);
243671489e21SJoe Stringer 		if (refcounted)
24378afdd99aSEric Dumazet 			sock_put(sk);
24382b5a9217SPaolo Abeni 		return ret;
2439c18450a5SFabian Frederick 	}
2440c18450a5SFabian Frederick 
2441db8dac20SDavid S. Miller 	if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
2442e3163493SPavel Emelyanov 		return __udp4_lib_mcast_deliver(net, skb, uh,
244336cbb245SRick Jones 						saddr, daddr, udptable, proto);
2444db8dac20SDavid S. Miller 
2445607c4aafSKOVACS Krisztian 	sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
24462b5a9217SPaolo Abeni 	if (sk)
24472b5a9217SPaolo Abeni 		return udp_unicast_rcv_skb(sk, skb, uh);
2448db8dac20SDavid S. Miller 
2449db8dac20SDavid S. Miller 	if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
2450db8dac20SDavid S. Miller 		goto drop;
2451895b5c9fSFlorian Westphal 	nf_reset_ct(skb);
2452db8dac20SDavid S. Miller 
2453db8dac20SDavid S. Miller 	/* No socket. Drop packet silently, if checksum is wrong */
2454db8dac20SDavid S. Miller 	if (udp_lib_checksum_complete(skb))
2455db8dac20SDavid S. Miller 		goto csum_error;
2456db8dac20SDavid S. Miller 
24571c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_NO_SOCKET;
245802c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
2459db8dac20SDavid S. Miller 	icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
2460db8dac20SDavid S. Miller 
2461db8dac20SDavid S. Miller 	/*
2462db8dac20SDavid S. Miller 	 * Hmm.  We got an UDP packet to a port to which we
2463db8dac20SDavid S. Miller 	 * don't wanna listen.  Ignore it.
2464db8dac20SDavid S. Miller 	 */
24651c7fab70SMenglong Dong 	kfree_skb_reason(skb, drop_reason);
2466db8dac20SDavid S. Miller 	return 0;
2467db8dac20SDavid S. Miller 
2468db8dac20SDavid S. Miller short_packet:
24691c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_PKT_TOO_SMALL;
2470ba7a46f1SJoe Perches 	net_dbg_ratelimited("UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
2471afd46503SJoe Perches 			    proto == IPPROTO_UDPLITE ? "Lite" : "",
2472afd46503SJoe Perches 			    &saddr, ntohs(uh->source),
2473afd46503SJoe Perches 			    ulen, skb->len,
2474afd46503SJoe Perches 			    &daddr, ntohs(uh->dest));
2475db8dac20SDavid S. Miller 	goto drop;
2476db8dac20SDavid S. Miller 
2477db8dac20SDavid S. Miller csum_error:
2478db8dac20SDavid S. Miller 	/*
2479db8dac20SDavid S. Miller 	 * RFC1122: OK.  Discards the bad packet silently (as far as
2480db8dac20SDavid S. Miller 	 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
2481db8dac20SDavid S. Miller 	 */
24821c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_UDP_CSUM;
2483ba7a46f1SJoe Perches 	net_dbg_ratelimited("UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
2484afd46503SJoe Perches 			    proto == IPPROTO_UDPLITE ? "Lite" : "",
2485afd46503SJoe Perches 			    &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
2486db8dac20SDavid S. Miller 			    ulen);
248702c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
2488db8dac20SDavid S. Miller drop:
248902c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
24901c7fab70SMenglong Dong 	kfree_skb_reason(skb, drop_reason);
2491db8dac20SDavid S. Miller 	return 0;
2492db8dac20SDavid S. Miller }
2493db8dac20SDavid S. Miller 
2494421b3885SShawn Bohrer /* We can only early demux multicast if there is a single matching socket.
2495421b3885SShawn Bohrer  * If more than one socket found returns NULL
2496421b3885SShawn Bohrer  */
2497421b3885SShawn Bohrer static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net,
2498421b3885SShawn Bohrer 						  __be16 loc_port, __be32 loc_addr,
2499421b3885SShawn Bohrer 						  __be16 rmt_port, __be32 rmt_addr,
2500fb74c277SDavid Ahern 						  int dif, int sdif)
2501421b3885SShawn Bohrer {
2502ba6aac15SKuniyuki Iwashima 	struct udp_table *udptable = net->ipv4.udp_table;
2503421b3885SShawn Bohrer 	unsigned short hnum = ntohs(loc_port);
2504919dfa0bSKuniyuki Iwashima 	struct sock *sk, *result;
2505919dfa0bSKuniyuki Iwashima 	struct udp_hslot *hslot;
2506919dfa0bSKuniyuki Iwashima 	unsigned int slot;
2507919dfa0bSKuniyuki Iwashima 
2508ba6aac15SKuniyuki Iwashima 	slot = udp_hashfn(net, hnum, udptable->mask);
2509ba6aac15SKuniyuki Iwashima 	hslot = &udptable->hash[slot];
2510421b3885SShawn Bohrer 
251163c6f81cSEric Dumazet 	/* Do not bother scanning a too big list */
251263c6f81cSEric Dumazet 	if (hslot->count > 10)
251363c6f81cSEric Dumazet 		return NULL;
251463c6f81cSEric Dumazet 
2515421b3885SShawn Bohrer 	result = NULL;
2516ca065d0cSEric Dumazet 	sk_for_each_rcu(sk, &hslot->head) {
2517ca065d0cSEric Dumazet 		if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr,
2518fb74c277SDavid Ahern 					rmt_port, rmt_addr, dif, sdif, hnum)) {
2519ca065d0cSEric Dumazet 			if (result)
2520ca065d0cSEric Dumazet 				return NULL;
2521421b3885SShawn Bohrer 			result = sk;
2522421b3885SShawn Bohrer 		}
2523421b3885SShawn Bohrer 	}
2524421b3885SShawn Bohrer 
2525421b3885SShawn Bohrer 	return result;
2526421b3885SShawn Bohrer }
2527421b3885SShawn Bohrer 
2528421b3885SShawn Bohrer /* For unicast we should only early demux connected sockets or we can
2529421b3885SShawn Bohrer  * break forwarding setups.  The chains here can be long so only check
2530421b3885SShawn Bohrer  * if the first socket is an exact match and if not move on.
2531421b3885SShawn Bohrer  */
2532421b3885SShawn Bohrer static struct sock *__udp4_lib_demux_lookup(struct net *net,
2533421b3885SShawn Bohrer 					    __be16 loc_port, __be32 loc_addr,
2534421b3885SShawn Bohrer 					    __be16 rmt_port, __be32 rmt_addr,
25353fa6f616SDavid Ahern 					    int dif, int sdif)
2536421b3885SShawn Bohrer {
2537ba6aac15SKuniyuki Iwashima 	struct udp_table *udptable = net->ipv4.udp_table;
2538c7228317SJoe Perches 	INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr);
2539919dfa0bSKuniyuki Iwashima 	unsigned short hnum = ntohs(loc_port);
2540919dfa0bSKuniyuki Iwashima 	unsigned int hash2, slot2;
2541919dfa0bSKuniyuki Iwashima 	struct udp_hslot *hslot2;
2542919dfa0bSKuniyuki Iwashima 	__portpair ports;
2543ca065d0cSEric Dumazet 	struct sock *sk;
2544421b3885SShawn Bohrer 
2545919dfa0bSKuniyuki Iwashima 	hash2 = ipv4_portaddr_hash(net, loc_addr, hnum);
2546ba6aac15SKuniyuki Iwashima 	slot2 = hash2 & udptable->mask;
2547ba6aac15SKuniyuki Iwashima 	hslot2 = &udptable->hash2[slot2];
2548919dfa0bSKuniyuki Iwashima 	ports = INET_COMBINED_PORTS(rmt_port, hnum);
2549919dfa0bSKuniyuki Iwashima 
2550ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
2551eda090c3SEric Dumazet 		if (inet_match(net, sk, acookie, ports, dif, sdif))
2552ca065d0cSEric Dumazet 			return sk;
2553421b3885SShawn Bohrer 		/* Only check first socket in chain */
2554421b3885SShawn Bohrer 		break;
2555421b3885SShawn Bohrer 	}
2556ca065d0cSEric Dumazet 	return NULL;
2557421b3885SShawn Bohrer }
2558421b3885SShawn Bohrer 
25597487449cSPaolo Abeni int udp_v4_early_demux(struct sk_buff *skb)
2560421b3885SShawn Bohrer {
2561610438b7SEric Dumazet 	struct net *net = dev_net(skb->dev);
2562bc044e8dSPaolo Abeni 	struct in_device *in_dev = NULL;
2563610438b7SEric Dumazet 	const struct iphdr *iph;
2564610438b7SEric Dumazet 	const struct udphdr *uh;
2565ca065d0cSEric Dumazet 	struct sock *sk = NULL;
2566421b3885SShawn Bohrer 	struct dst_entry *dst;
2567421b3885SShawn Bohrer 	int dif = skb->dev->ifindex;
2568fb74c277SDavid Ahern 	int sdif = inet_sdif(skb);
25696e540309SShawn Bohrer 	int ours;
2570421b3885SShawn Bohrer 
2571421b3885SShawn Bohrer 	/* validate the packet */
2572421b3885SShawn Bohrer 	if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)))
25737487449cSPaolo Abeni 		return 0;
2574421b3885SShawn Bohrer 
2575610438b7SEric Dumazet 	iph = ip_hdr(skb);
2576610438b7SEric Dumazet 	uh = udp_hdr(skb);
2577610438b7SEric Dumazet 
2578996b44fcSPaolo Abeni 	if (skb->pkt_type == PACKET_MULTICAST) {
2579bc044e8dSPaolo Abeni 		in_dev = __in_dev_get_rcu(skb->dev);
25806e540309SShawn Bohrer 
25816e540309SShawn Bohrer 		if (!in_dev)
25827487449cSPaolo Abeni 			return 0;
25836e540309SShawn Bohrer 
25846e540309SShawn Bohrer 		ours = ip_check_mc_rcu(in_dev, iph->daddr, iph->saddr,
25856e540309SShawn Bohrer 				       iph->protocol);
25866e540309SShawn Bohrer 		if (!ours)
25877487449cSPaolo Abeni 			return 0;
2588ad0ea198SPaolo Abeni 
2589421b3885SShawn Bohrer 		sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr,
2590fb74c277SDavid Ahern 						   uh->source, iph->saddr,
2591fb74c277SDavid Ahern 						   dif, sdif);
25926e540309SShawn Bohrer 	} else if (skb->pkt_type == PACKET_HOST) {
2593421b3885SShawn Bohrer 		sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr,
25943fa6f616SDavid Ahern 					     uh->source, iph->saddr, dif, sdif);
25956e540309SShawn Bohrer 	}
2596421b3885SShawn Bohrer 
259741c6d650SReshetova, Elena 	if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
25987487449cSPaolo Abeni 		return 0;
2599421b3885SShawn Bohrer 
2600421b3885SShawn Bohrer 	skb->sk = sk;
260182eabd9eSAlexander Duyck 	skb->destructor = sock_efree;
26028f905c0eSEric Dumazet 	dst = rcu_dereference(sk->sk_rx_dst);
2603421b3885SShawn Bohrer 
2604421b3885SShawn Bohrer 	if (dst)
2605421b3885SShawn Bohrer 		dst = dst_check(dst, 0);
260610e2eb87SEric Dumazet 	if (dst) {
2607bc044e8dSPaolo Abeni 		u32 itag = 0;
2608bc044e8dSPaolo Abeni 
2609d24406c8SWei Wang 		/* set noref for now.
2610d24406c8SWei Wang 		 * any place which wants to hold dst has to call
2611d24406c8SWei Wang 		 * dst_hold_safe()
2612d24406c8SWei Wang 		 */
2613421b3885SShawn Bohrer 		skb_dst_set_noref(skb, dst);
2614bc044e8dSPaolo Abeni 
2615bc044e8dSPaolo Abeni 		/* for unconnected multicast sockets we need to validate
2616bc044e8dSPaolo Abeni 		 * the source on each packet
2617bc044e8dSPaolo Abeni 		 */
2618bc044e8dSPaolo Abeni 		if (!inet_sk(sk)->inet_daddr && in_dev)
2619bc044e8dSPaolo Abeni 			return ip_mc_validate_source(skb, iph->daddr,
26208d2b51b0SGuillaume Nault 						     iph->saddr,
26218d2b51b0SGuillaume Nault 						     iph->tos & IPTOS_RT_MASK,
2622bc044e8dSPaolo Abeni 						     skb->dev, in_dev, &itag);
2623421b3885SShawn Bohrer 	}
26247487449cSPaolo Abeni 	return 0;
262510e2eb87SEric Dumazet }
2626421b3885SShawn Bohrer 
2627db8dac20SDavid S. Miller int udp_rcv(struct sk_buff *skb)
2628db8dac20SDavid S. Miller {
2629ba6aac15SKuniyuki Iwashima 	return __udp4_lib_rcv(skb, dev_net(skb->dev)->ipv4.udp_table, IPPROTO_UDP);
2630db8dac20SDavid S. Miller }
2631db8dac20SDavid S. Miller 
26327d06b2e0SBrian Haley void udp_destroy_sock(struct sock *sk)
2633db8dac20SDavid S. Miller {
263444046a59STom Parkin 	struct udp_sock *up = udp_sk(sk);
26358a74ad60SEric Dumazet 	bool slow = lock_sock_fast(sk);
2636a8b897c7SPaolo Abeni 
2637a8b897c7SPaolo Abeni 	/* protects from races with udp_abort() */
2638a8b897c7SPaolo Abeni 	sock_set_flag(sk, SOCK_DEAD);
2639db8dac20SDavid S. Miller 	udp_flush_pending_frames(sk);
26408a74ad60SEric Dumazet 	unlock_sock_fast(sk, slow);
264160fb9567SPaolo Abeni 	if (static_branch_unlikely(&udp_encap_needed_key)) {
264260fb9567SPaolo Abeni 		if (up->encap_type) {
264344046a59STom Parkin 			void (*encap_destroy)(struct sock *sk);
26446aa7de05SMark Rutland 			encap_destroy = READ_ONCE(up->encap_destroy);
264544046a59STom Parkin 			if (encap_destroy)
264644046a59STom Parkin 				encap_destroy(sk);
264744046a59STom Parkin 		}
264860fb9567SPaolo Abeni 		if (up->encap_enabled)
26499c480601SPaolo Abeni 			static_branch_dec(&udp_encap_needed_key);
265060fb9567SPaolo Abeni 	}
2651db8dac20SDavid S. Miller }
2652db8dac20SDavid S. Miller 
26531da177e4SLinus Torvalds /*
26541da177e4SLinus Torvalds  *	Socket option code for UDP
26551da177e4SLinus Torvalds  */
26564c0a6cb0SGerrit Renker int udp_lib_setsockopt(struct sock *sk, int level, int optname,
265791ac1ccaSChristoph Hellwig 		       sockptr_t optval, unsigned int optlen,
26584c0a6cb0SGerrit Renker 		       int (*push_pending_frames)(struct sock *))
26591da177e4SLinus Torvalds {
26601da177e4SLinus Torvalds 	struct udp_sock *up = udp_sk(sk);
26611c19448cSTom Herbert 	int val, valbool;
26621da177e4SLinus Torvalds 	int err = 0;
2663b2bf1e26SWang Chen 	int is_udplite = IS_UDPLITE(sk);
26641da177e4SLinus Torvalds 
26658a3854c7SPaolo Abeni 	if (level == SOL_SOCKET) {
26668a3854c7SPaolo Abeni 		err = sk_setsockopt(sk, level, optname, optval, optlen);
26678a3854c7SPaolo Abeni 
26688a3854c7SPaolo Abeni 		if (optname == SO_RCVBUF || optname == SO_RCVBUFFORCE) {
26698a3854c7SPaolo Abeni 			sockopt_lock_sock(sk);
26708a3854c7SPaolo Abeni 			/* paired with READ_ONCE in udp_rmem_release() */
26718a3854c7SPaolo Abeni 			WRITE_ONCE(up->forward_threshold, sk->sk_rcvbuf >> 2);
26728a3854c7SPaolo Abeni 			sockopt_release_sock(sk);
26738a3854c7SPaolo Abeni 		}
26748a3854c7SPaolo Abeni 		return err;
26758a3854c7SPaolo Abeni 	}
26768a3854c7SPaolo Abeni 
26771da177e4SLinus Torvalds 	if (optlen < sizeof(int))
26781da177e4SLinus Torvalds 		return -EINVAL;
26791da177e4SLinus Torvalds 
268091ac1ccaSChristoph Hellwig 	if (copy_from_sockptr(&val, optval, sizeof(val)))
26811da177e4SLinus Torvalds 		return -EFAULT;
26821da177e4SLinus Torvalds 
26831c19448cSTom Herbert 	valbool = val ? 1 : 0;
26841c19448cSTom Herbert 
26851da177e4SLinus Torvalds 	switch (optname) {
26861da177e4SLinus Torvalds 	case UDP_CORK:
26871da177e4SLinus Torvalds 		if (val != 0) {
2688a9f59707SEric Dumazet 			WRITE_ONCE(up->corkflag, 1);
26891da177e4SLinus Torvalds 		} else {
2690a9f59707SEric Dumazet 			WRITE_ONCE(up->corkflag, 0);
26911da177e4SLinus Torvalds 			lock_sock(sk);
26924243cdc2SJoe Perches 			push_pending_frames(sk);
26931da177e4SLinus Torvalds 			release_sock(sk);
26941da177e4SLinus Torvalds 		}
26951da177e4SLinus Torvalds 		break;
26961da177e4SLinus Torvalds 
26971da177e4SLinus Torvalds 	case UDP_ENCAP:
26981da177e4SLinus Torvalds 		switch (val) {
26991da177e4SLinus Torvalds 		case 0:
2700fd1ac07fSAlexey Dobriyan #ifdef CONFIG_XFRM
27011da177e4SLinus Torvalds 		case UDP_ENCAP_ESPINUDP:
27021da177e4SLinus Torvalds 		case UDP_ENCAP_ESPINUDP_NON_IKE:
27030146dca7SSabrina Dubroca #if IS_ENABLED(CONFIG_IPV6)
27040146dca7SSabrina Dubroca 			if (sk->sk_family == AF_INET6)
27050146dca7SSabrina Dubroca 				up->encap_rcv = ipv6_stub->xfrm6_udp_encap_rcv;
27060146dca7SSabrina Dubroca 			else
27070146dca7SSabrina Dubroca #endif
2708067b207bSJames Chapman 				up->encap_rcv = xfrm4_udp_encap_rcv;
2709fd1ac07fSAlexey Dobriyan #endif
2710a8eceea8SJoe Perches 			fallthrough;
2711342f0234SJames Chapman 		case UDP_ENCAP_L2TPINUDP:
27121da177e4SLinus Torvalds 			up->encap_type = val;
271360fb9567SPaolo Abeni 			lock_sock(sk);
271460fb9567SPaolo Abeni 			udp_tunnel_encap_enable(sk->sk_socket);
271560fb9567SPaolo Abeni 			release_sock(sk);
27161da177e4SLinus Torvalds 			break;
27171da177e4SLinus Torvalds 		default:
27181da177e4SLinus Torvalds 			err = -ENOPROTOOPT;
27191da177e4SLinus Torvalds 			break;
27201da177e4SLinus Torvalds 		}
27211da177e4SLinus Torvalds 		break;
27221da177e4SLinus Torvalds 
27231c19448cSTom Herbert 	case UDP_NO_CHECK6_TX:
27241c19448cSTom Herbert 		up->no_check6_tx = valbool;
27251c19448cSTom Herbert 		break;
27261c19448cSTom Herbert 
27271c19448cSTom Herbert 	case UDP_NO_CHECK6_RX:
27281c19448cSTom Herbert 		up->no_check6_rx = valbool;
27291c19448cSTom Herbert 		break;
27301c19448cSTom Herbert 
2731bec1f6f6SWillem de Bruijn 	case UDP_SEGMENT:
2732bec1f6f6SWillem de Bruijn 		if (val < 0 || val > USHRT_MAX)
2733bec1f6f6SWillem de Bruijn 			return -EINVAL;
273418a419baSEric Dumazet 		WRITE_ONCE(up->gso_size, val);
2735bec1f6f6SWillem de Bruijn 		break;
2736bec1f6f6SWillem de Bruijn 
2737e20cf8d3SPaolo Abeni 	case UDP_GRO:
2738e20cf8d3SPaolo Abeni 		lock_sock(sk);
273978352f73SPaolo Abeni 
274078352f73SPaolo Abeni 		/* when enabling GRO, accept the related GSO packet type */
2741e20cf8d3SPaolo Abeni 		if (valbool)
2742e20cf8d3SPaolo Abeni 			udp_tunnel_encap_enable(sk->sk_socket);
2743e20cf8d3SPaolo Abeni 		up->gro_enabled = valbool;
274478352f73SPaolo Abeni 		up->accept_udp_l4 = valbool;
2745e20cf8d3SPaolo Abeni 		release_sock(sk);
2746e20cf8d3SPaolo Abeni 		break;
2747e20cf8d3SPaolo Abeni 
2748ba4e58ecSGerrit Renker 	/*
2749ba4e58ecSGerrit Renker 	 * 	UDP-Lite's partial checksum coverage (RFC 3828).
2750ba4e58ecSGerrit Renker 	 */
2751ba4e58ecSGerrit Renker 	/* The sender sets actual checksum coverage length via this option.
2752ba4e58ecSGerrit Renker 	 * The case coverage > packet length is handled by send module. */
2753ba4e58ecSGerrit Renker 	case UDPLITE_SEND_CSCOV:
2754b2bf1e26SWang Chen 		if (!is_udplite)         /* Disable the option on UDP sockets */
2755ba4e58ecSGerrit Renker 			return -ENOPROTOOPT;
2756ba4e58ecSGerrit Renker 		if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
2757ba4e58ecSGerrit Renker 			val = 8;
27584be929beSAlexey Dobriyan 		else if (val > USHRT_MAX)
27594be929beSAlexey Dobriyan 			val = USHRT_MAX;
2760ba4e58ecSGerrit Renker 		up->pcslen = val;
2761ba4e58ecSGerrit Renker 		up->pcflag |= UDPLITE_SEND_CC;
2762ba4e58ecSGerrit Renker 		break;
2763ba4e58ecSGerrit Renker 
2764ba4e58ecSGerrit Renker 	/* The receiver specifies a minimum checksum coverage value. To make
2765ba4e58ecSGerrit Renker 	 * sense, this should be set to at least 8 (as done below). If zero is
2766ba4e58ecSGerrit Renker 	 * used, this again means full checksum coverage.                     */
2767ba4e58ecSGerrit Renker 	case UDPLITE_RECV_CSCOV:
2768b2bf1e26SWang Chen 		if (!is_udplite)         /* Disable the option on UDP sockets */
2769ba4e58ecSGerrit Renker 			return -ENOPROTOOPT;
2770ba4e58ecSGerrit Renker 		if (val != 0 && val < 8) /* Avoid silly minimal values.       */
2771ba4e58ecSGerrit Renker 			val = 8;
27724be929beSAlexey Dobriyan 		else if (val > USHRT_MAX)
27734be929beSAlexey Dobriyan 			val = USHRT_MAX;
2774ba4e58ecSGerrit Renker 		up->pcrlen = val;
2775ba4e58ecSGerrit Renker 		up->pcflag |= UDPLITE_RECV_CC;
2776ba4e58ecSGerrit Renker 		break;
2777ba4e58ecSGerrit Renker 
27781da177e4SLinus Torvalds 	default:
27791da177e4SLinus Torvalds 		err = -ENOPROTOOPT;
27801da177e4SLinus Torvalds 		break;
27816516c655SStephen Hemminger 	}
27821da177e4SLinus Torvalds 
27831da177e4SLinus Torvalds 	return err;
27841da177e4SLinus Torvalds }
2785c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_setsockopt);
27861da177e4SLinus Torvalds 
2787a7b75c5aSChristoph Hellwig int udp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
2788a7b75c5aSChristoph Hellwig 		   unsigned int optlen)
2789db8dac20SDavid S. Miller {
27908a3854c7SPaolo Abeni 	if (level == SOL_UDP  ||  level == SOL_UDPLITE || level == SOL_SOCKET)
279191ac1ccaSChristoph Hellwig 		return udp_lib_setsockopt(sk, level, optname,
2792a7b75c5aSChristoph Hellwig 					  optval, optlen,
2793db8dac20SDavid S. Miller 					  udp_push_pending_frames);
2794db8dac20SDavid S. Miller 	return ip_setsockopt(sk, level, optname, optval, optlen);
2795db8dac20SDavid S. Miller }
2796db8dac20SDavid S. Miller 
27974c0a6cb0SGerrit Renker int udp_lib_getsockopt(struct sock *sk, int level, int optname,
27981da177e4SLinus Torvalds 		       char __user *optval, int __user *optlen)
27991da177e4SLinus Torvalds {
28001da177e4SLinus Torvalds 	struct udp_sock *up = udp_sk(sk);
28011da177e4SLinus Torvalds 	int val, len;
28021da177e4SLinus Torvalds 
28031da177e4SLinus Torvalds 	if (get_user(len, optlen))
28041da177e4SLinus Torvalds 		return -EFAULT;
28051da177e4SLinus Torvalds 
28061da177e4SLinus Torvalds 	len = min_t(unsigned int, len, sizeof(int));
28071da177e4SLinus Torvalds 
28081da177e4SLinus Torvalds 	if (len < 0)
28091da177e4SLinus Torvalds 		return -EINVAL;
28101da177e4SLinus Torvalds 
28111da177e4SLinus Torvalds 	switch (optname) {
28121da177e4SLinus Torvalds 	case UDP_CORK:
2813a9f59707SEric Dumazet 		val = READ_ONCE(up->corkflag);
28141da177e4SLinus Torvalds 		break;
28151da177e4SLinus Torvalds 
28161da177e4SLinus Torvalds 	case UDP_ENCAP:
28171da177e4SLinus Torvalds 		val = up->encap_type;
28181da177e4SLinus Torvalds 		break;
28191da177e4SLinus Torvalds 
28201c19448cSTom Herbert 	case UDP_NO_CHECK6_TX:
28211c19448cSTom Herbert 		val = up->no_check6_tx;
28221c19448cSTom Herbert 		break;
28231c19448cSTom Herbert 
28241c19448cSTom Herbert 	case UDP_NO_CHECK6_RX:
28251c19448cSTom Herbert 		val = up->no_check6_rx;
28261c19448cSTom Herbert 		break;
28271c19448cSTom Herbert 
2828bec1f6f6SWillem de Bruijn 	case UDP_SEGMENT:
282918a419baSEric Dumazet 		val = READ_ONCE(up->gso_size);
2830bec1f6f6SWillem de Bruijn 		break;
2831bec1f6f6SWillem de Bruijn 
283298184612SNorman Maurer 	case UDP_GRO:
283398184612SNorman Maurer 		val = up->gro_enabled;
283498184612SNorman Maurer 		break;
283598184612SNorman Maurer 
2836ba4e58ecSGerrit Renker 	/* The following two cannot be changed on UDP sockets, the return is
2837ba4e58ecSGerrit Renker 	 * always 0 (which corresponds to the full checksum coverage of UDP). */
2838ba4e58ecSGerrit Renker 	case UDPLITE_SEND_CSCOV:
2839ba4e58ecSGerrit Renker 		val = up->pcslen;
2840ba4e58ecSGerrit Renker 		break;
2841ba4e58ecSGerrit Renker 
2842ba4e58ecSGerrit Renker 	case UDPLITE_RECV_CSCOV:
2843ba4e58ecSGerrit Renker 		val = up->pcrlen;
2844ba4e58ecSGerrit Renker 		break;
2845ba4e58ecSGerrit Renker 
28461da177e4SLinus Torvalds 	default:
28471da177e4SLinus Torvalds 		return -ENOPROTOOPT;
28486516c655SStephen Hemminger 	}
28491da177e4SLinus Torvalds 
28501da177e4SLinus Torvalds 	if (put_user(len, optlen))
28511da177e4SLinus Torvalds 		return -EFAULT;
28521da177e4SLinus Torvalds 	if (copy_to_user(optval, &val, len))
28531da177e4SLinus Torvalds 		return -EFAULT;
28541da177e4SLinus Torvalds 	return 0;
28551da177e4SLinus Torvalds }
2856c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_getsockopt);
28571da177e4SLinus Torvalds 
2858db8dac20SDavid S. Miller int udp_getsockopt(struct sock *sk, int level, int optname,
2859db8dac20SDavid S. Miller 		   char __user *optval, int __user *optlen)
2860db8dac20SDavid S. Miller {
2861db8dac20SDavid S. Miller 	if (level == SOL_UDP  ||  level == SOL_UDPLITE)
2862db8dac20SDavid S. Miller 		return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2863db8dac20SDavid S. Miller 	return ip_getsockopt(sk, level, optname, optval, optlen);
2864db8dac20SDavid S. Miller }
2865db8dac20SDavid S. Miller 
28661da177e4SLinus Torvalds /**
28671da177e4SLinus Torvalds  * 	udp_poll - wait for a UDP event.
28683628e3cbSAndrew Lunn  *	@file: - file struct
28693628e3cbSAndrew Lunn  *	@sock: - socket
28703628e3cbSAndrew Lunn  *	@wait: - poll table
28711da177e4SLinus Torvalds  *
28721da177e4SLinus Torvalds  *	This is same as datagram poll, except for the special case of
28731da177e4SLinus Torvalds  *	blocking sockets. If application is using a blocking fd
28741da177e4SLinus Torvalds  *	and a packet with checksum error is in the queue;
28751da177e4SLinus Torvalds  *	then it could get return from select indicating data available
28761da177e4SLinus Torvalds  *	but then block when reading it. Add special case code
28771da177e4SLinus Torvalds  *	to work around these arguably broken applications.
28781da177e4SLinus Torvalds  */
2879a11e1d43SLinus Torvalds __poll_t udp_poll(struct file *file, struct socket *sock, poll_table *wait)
28801da177e4SLinus Torvalds {
2881a11e1d43SLinus Torvalds 	__poll_t mask = datagram_poll(file, sock, wait);
28821da177e4SLinus Torvalds 	struct sock *sk = sock->sk;
28831da177e4SLinus Torvalds 
28843ef7cf57SEric Dumazet 	if (!skb_queue_empty_lockless(&udp_sk(sk)->reader_queue))
2885a9a08845SLinus Torvalds 		mask |= EPOLLIN | EPOLLRDNORM;
28862276f58aSPaolo Abeni 
28871da177e4SLinus Torvalds 	/* Check for false positives due to checksum errors */
2888a11e1d43SLinus Torvalds 	if ((mask & EPOLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
2889e83c6744SEric Dumazet 	    !(sk->sk_shutdown & RCV_SHUTDOWN) && first_packet_length(sk) == -1)
2890a9a08845SLinus Torvalds 		mask &= ~(EPOLLIN | EPOLLRDNORM);
28911da177e4SLinus Torvalds 
2892af493388SCong Wang 	/* psock ingress_msg queue should not contain any bad checksum frames */
2893af493388SCong Wang 	if (sk_is_readable(sk))
2894af493388SCong Wang 		mask |= EPOLLIN | EPOLLRDNORM;
28951da177e4SLinus Torvalds 	return mask;
28961da177e4SLinus Torvalds 
28971da177e4SLinus Torvalds }
2898a11e1d43SLinus Torvalds EXPORT_SYMBOL(udp_poll);
28991da177e4SLinus Torvalds 
29005d77dca8SDavid Ahern int udp_abort(struct sock *sk, int err)
29015d77dca8SDavid Ahern {
29024ddbcb88SAditi Ghag 	if (!has_current_bpf_ctx())
29035d77dca8SDavid Ahern 		lock_sock(sk);
29045d77dca8SDavid Ahern 
2905a8b897c7SPaolo Abeni 	/* udp{v6}_destroy_sock() sets it under the sk lock, avoid racing
2906a8b897c7SPaolo Abeni 	 * with close()
2907a8b897c7SPaolo Abeni 	 */
2908a8b897c7SPaolo Abeni 	if (sock_flag(sk, SOCK_DEAD))
2909a8b897c7SPaolo Abeni 		goto out;
2910a8b897c7SPaolo Abeni 
29115d77dca8SDavid Ahern 	sk->sk_err = err;
2912e3ae2365SAlexander Aring 	sk_error_report(sk);
2913286c72deSEric Dumazet 	__udp_disconnect(sk, 0);
29145d77dca8SDavid Ahern 
2915a8b897c7SPaolo Abeni out:
29164ddbcb88SAditi Ghag 	if (!has_current_bpf_ctx())
29175d77dca8SDavid Ahern 		release_sock(sk);
29185d77dca8SDavid Ahern 
29195d77dca8SDavid Ahern 	return 0;
29205d77dca8SDavid Ahern }
29215d77dca8SDavid Ahern EXPORT_SYMBOL_GPL(udp_abort);
29225d77dca8SDavid Ahern 
2923db8dac20SDavid S. Miller struct proto udp_prot = {
2924db8dac20SDavid S. Miller 	.name			= "UDP",
2925db8dac20SDavid S. Miller 	.owner			= THIS_MODULE,
2926db8dac20SDavid S. Miller 	.close			= udp_lib_close,
2927d74bad4eSAndrey Ignatov 	.pre_connect		= udp_pre_connect,
2928db8dac20SDavid S. Miller 	.connect		= ip4_datagram_connect,
2929db8dac20SDavid S. Miller 	.disconnect		= udp_disconnect,
2930db8dac20SDavid S. Miller 	.ioctl			= udp_ioctl,
2931850cbaddSPaolo Abeni 	.init			= udp_init_sock,
2932db8dac20SDavid S. Miller 	.destroy		= udp_destroy_sock,
2933db8dac20SDavid S. Miller 	.setsockopt		= udp_setsockopt,
2934db8dac20SDavid S. Miller 	.getsockopt		= udp_getsockopt,
2935db8dac20SDavid S. Miller 	.sendmsg		= udp_sendmsg,
2936db8dac20SDavid S. Miller 	.recvmsg		= udp_recvmsg,
29371d7e4538SDavid Howells 	.splice_eof		= udp_splice_eof,
2938db8dac20SDavid S. Miller 	.sendpage		= udp_sendpage,
29398141ed9fSSteffen Klassert 	.release_cb		= ip4_datagram_release_cb,
2940db8dac20SDavid S. Miller 	.hash			= udp_lib_hash,
2941db8dac20SDavid S. Miller 	.unhash			= udp_lib_unhash,
2942719f8358SEric Dumazet 	.rehash			= udp_v4_rehash,
2943db8dac20SDavid S. Miller 	.get_port		= udp_v4_get_port,
294491a760b2SMenglong Dong 	.put_port		= udp_lib_unhash,
29458a59f9d1SCong Wang #ifdef CONFIG_BPF_SYSCALL
29468a59f9d1SCong Wang 	.psock_update_sk_prot	= udp_bpf_update_proto,
29478a59f9d1SCong Wang #endif
2948db8dac20SDavid S. Miller 	.memory_allocated	= &udp_memory_allocated,
29490defbb0aSEric Dumazet 	.per_cpu_fw_alloc	= &udp_memory_per_cpu_fw_alloc,
29500defbb0aSEric Dumazet 
2951db8dac20SDavid S. Miller 	.sysctl_mem		= sysctl_udp_mem,
29521e802951STonghao Zhang 	.sysctl_wmem_offset	= offsetof(struct net, ipv4.sysctl_udp_wmem_min),
29531e802951STonghao Zhang 	.sysctl_rmem_offset	= offsetof(struct net, ipv4.sysctl_udp_rmem_min),
2954db8dac20SDavid S. Miller 	.obj_size		= sizeof(struct udp_sock),
295567fb4330SKuniyuki Iwashima 	.h.udp_table		= NULL,
29565d77dca8SDavid Ahern 	.diag_destroy		= udp_abort,
2957db8dac20SDavid S. Miller };
2958c482c568SEric Dumazet EXPORT_SYMBOL(udp_prot);
29591da177e4SLinus Torvalds 
29601da177e4SLinus Torvalds /* ------------------------------------------------------------------------ */
29611da177e4SLinus Torvalds #ifdef CONFIG_PROC_FS
29621da177e4SLinus Torvalds 
2963f44b1c51SAditi Ghag static unsigned short seq_file_family(const struct seq_file *seq);
2964f44b1c51SAditi Ghag static bool seq_sk_match(struct seq_file *seq, const struct sock *sk)
2965f44b1c51SAditi Ghag {
2966f44b1c51SAditi Ghag 	unsigned short family = seq_file_family(seq);
2967f44b1c51SAditi Ghag 
2968f44b1c51SAditi Ghag 	/* AF_UNSPEC is used as a match all */
2969f44b1c51SAditi Ghag 	return ((family == AF_UNSPEC || family == sk->sk_family) &&
2970f44b1c51SAditi Ghag 		net_eq(sock_net(sk), seq_file_net(seq)));
2971f44b1c51SAditi Ghag }
2972f44b1c51SAditi Ghag 
2973e4fe1bf1SAditi Ghag #ifdef CONFIG_BPF_SYSCALL
2974e4fe1bf1SAditi Ghag static const struct seq_operations bpf_iter_udp_seq_ops;
2975e4fe1bf1SAditi Ghag #endif
29767625d2e9SAditi Ghag static struct udp_table *udp_get_table_seq(struct seq_file *seq,
2977478aee5dSKuniyuki Iwashima 					   struct net *net)
2978478aee5dSKuniyuki Iwashima {
29797625d2e9SAditi Ghag 	const struct udp_seq_afinfo *afinfo;
29807625d2e9SAditi Ghag 
2981e4fe1bf1SAditi Ghag #ifdef CONFIG_BPF_SYSCALL
2982e4fe1bf1SAditi Ghag 	if (seq->op == &bpf_iter_udp_seq_ops)
29837625d2e9SAditi Ghag 		return net->ipv4.udp_table;
2984e4fe1bf1SAditi Ghag #endif
29857625d2e9SAditi Ghag 
29867625d2e9SAditi Ghag 	afinfo = pde_data(file_inode(seq->file));
2987478aee5dSKuniyuki Iwashima 	return afinfo->udp_table ? : net->ipv4.udp_table;
2988478aee5dSKuniyuki Iwashima }
2989478aee5dSKuniyuki Iwashima 
2990645ca708SEric Dumazet static struct sock *udp_get_first(struct seq_file *seq, int start)
29911da177e4SLinus Torvalds {
29921da177e4SLinus Torvalds 	struct udp_iter_state *state = seq->private;
29936f191efeSDenis V. Lunev 	struct net *net = seq_file_net(seq);
2994478aee5dSKuniyuki Iwashima 	struct udp_table *udptable;
2995919dfa0bSKuniyuki Iwashima 	struct sock *sk;
29961da177e4SLinus Torvalds 
29977625d2e9SAditi Ghag 	udptable = udp_get_table_seq(seq, net);
2998478aee5dSKuniyuki Iwashima 
2999478aee5dSKuniyuki Iwashima 	for (state->bucket = start; state->bucket <= udptable->mask;
3000f86dcc5aSEric Dumazet 	     ++state->bucket) {
3001478aee5dSKuniyuki Iwashima 		struct udp_hslot *hslot = &udptable->hash[state->bucket];
3002f86dcc5aSEric Dumazet 
3003ca065d0cSEric Dumazet 		if (hlist_empty(&hslot->head))
3004f86dcc5aSEric Dumazet 			continue;
3005f86dcc5aSEric Dumazet 
3006645ca708SEric Dumazet 		spin_lock_bh(&hslot->lock);
3007ca065d0cSEric Dumazet 		sk_for_each(sk, &hslot->head) {
3008f44b1c51SAditi Ghag 			if (seq_sk_match(seq, sk))
30091da177e4SLinus Torvalds 				goto found;
30101da177e4SLinus Torvalds 		}
3011645ca708SEric Dumazet 		spin_unlock_bh(&hslot->lock);
30121da177e4SLinus Torvalds 	}
30131da177e4SLinus Torvalds 	sk = NULL;
30141da177e4SLinus Torvalds found:
30151da177e4SLinus Torvalds 	return sk;
30161da177e4SLinus Torvalds }
30171da177e4SLinus Torvalds 
30181da177e4SLinus Torvalds static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
30191da177e4SLinus Torvalds {
30201da177e4SLinus Torvalds 	struct udp_iter_state *state = seq->private;
30216f191efeSDenis V. Lunev 	struct net *net = seq_file_net(seq);
3022478aee5dSKuniyuki Iwashima 	struct udp_table *udptable;
30231da177e4SLinus Torvalds 
30241da177e4SLinus Torvalds 	do {
3025ca065d0cSEric Dumazet 		sk = sk_next(sk);
3026f44b1c51SAditi Ghag 	} while (sk && !seq_sk_match(seq, sk));
30271da177e4SLinus Torvalds 
3028645ca708SEric Dumazet 	if (!sk) {
30297625d2e9SAditi Ghag 		udptable = udp_get_table_seq(seq, net);
3030478aee5dSKuniyuki Iwashima 
3031478aee5dSKuniyuki Iwashima 		if (state->bucket <= udptable->mask)
3032478aee5dSKuniyuki Iwashima 			spin_unlock_bh(&udptable->hash[state->bucket].lock);
3033478aee5dSKuniyuki Iwashima 
3034645ca708SEric Dumazet 		return udp_get_first(seq, state->bucket + 1);
30351da177e4SLinus Torvalds 	}
30361da177e4SLinus Torvalds 	return sk;
30371da177e4SLinus Torvalds }
30381da177e4SLinus Torvalds 
30391da177e4SLinus Torvalds static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
30401da177e4SLinus Torvalds {
3041645ca708SEric Dumazet 	struct sock *sk = udp_get_first(seq, 0);
30421da177e4SLinus Torvalds 
30431da177e4SLinus Torvalds 	if (sk)
30441da177e4SLinus Torvalds 		while (pos && (sk = udp_get_next(seq, sk)) != NULL)
30451da177e4SLinus Torvalds 			--pos;
30461da177e4SLinus Torvalds 	return pos ? NULL : sk;
30471da177e4SLinus Torvalds }
30481da177e4SLinus Torvalds 
3049a3d2599bSChristoph Hellwig void *udp_seq_start(struct seq_file *seq, loff_t *pos)
30501da177e4SLinus Torvalds {
305130842f29SVitaly Mayatskikh 	struct udp_iter_state *state = seq->private;
3052f86dcc5aSEric Dumazet 	state->bucket = MAX_UDP_PORTS;
305330842f29SVitaly Mayatskikh 
3054b50660f1SYOSHIFUJI Hideaki 	return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
30551da177e4SLinus Torvalds }
3056a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_start);
30571da177e4SLinus Torvalds 
3058a3d2599bSChristoph Hellwig void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
30591da177e4SLinus Torvalds {
30601da177e4SLinus Torvalds 	struct sock *sk;
30611da177e4SLinus Torvalds 
3062b50660f1SYOSHIFUJI Hideaki 	if (v == SEQ_START_TOKEN)
30631da177e4SLinus Torvalds 		sk = udp_get_idx(seq, 0);
30641da177e4SLinus Torvalds 	else
30651da177e4SLinus Torvalds 		sk = udp_get_next(seq, v);
30661da177e4SLinus Torvalds 
30671da177e4SLinus Torvalds 	++*pos;
30681da177e4SLinus Torvalds 	return sk;
30691da177e4SLinus Torvalds }
3070a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_next);
30711da177e4SLinus Torvalds 
3072a3d2599bSChristoph Hellwig void udp_seq_stop(struct seq_file *seq, void *v)
30731da177e4SLinus Torvalds {
3074645ca708SEric Dumazet 	struct udp_iter_state *state = seq->private;
3075478aee5dSKuniyuki Iwashima 	struct udp_table *udptable;
3076645ca708SEric Dumazet 
30777625d2e9SAditi Ghag 	udptable = udp_get_table_seq(seq, seq_file_net(seq));
3078478aee5dSKuniyuki Iwashima 
3079478aee5dSKuniyuki Iwashima 	if (state->bucket <= udptable->mask)
3080478aee5dSKuniyuki Iwashima 		spin_unlock_bh(&udptable->hash[state->bucket].lock);
30811da177e4SLinus Torvalds }
3082a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_stop);
3083db8dac20SDavid S. Miller 
3084db8dac20SDavid S. Miller /* ------------------------------------------------------------------------ */
30855e659e4cSPavel Emelyanov static void udp4_format_sock(struct sock *sp, struct seq_file *f,
3086652586dfSTetsuo Handa 		int bucket)
3087db8dac20SDavid S. Miller {
3088db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sp);
3089c720c7e8SEric Dumazet 	__be32 dest = inet->inet_daddr;
3090c720c7e8SEric Dumazet 	__be32 src  = inet->inet_rcv_saddr;
3091c720c7e8SEric Dumazet 	__u16 destp	  = ntohs(inet->inet_dport);
3092c720c7e8SEric Dumazet 	__u16 srcp	  = ntohs(inet->inet_sport);
3093db8dac20SDavid S. Miller 
3094f86dcc5aSEric Dumazet 	seq_printf(f, "%5d: %08X:%04X %08X:%04X"
3095ea9a0379SPatrick Talbert 		" %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %u",
3096db8dac20SDavid S. Miller 		bucket, src, srcp, dest, destp, sp->sk_state,
309731e6d363SEric Dumazet 		sk_wmem_alloc_get(sp),
30986c206b20SPaolo Abeni 		udp_rqueue_get(sp),
3099a7cb5a49SEric W. Biederman 		0, 0L, 0,
3100a7cb5a49SEric W. Biederman 		from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
3101a7cb5a49SEric W. Biederman 		0, sock_i_ino(sp),
310241c6d650SReshetova, Elena 		refcount_read(&sp->sk_refcnt), sp,
3103652586dfSTetsuo Handa 		atomic_read(&sp->sk_drops));
3104db8dac20SDavid S. Miller }
3105db8dac20SDavid S. Miller 
3106db8dac20SDavid S. Miller int udp4_seq_show(struct seq_file *seq, void *v)
3107db8dac20SDavid S. Miller {
3108652586dfSTetsuo Handa 	seq_setwidth(seq, 127);
3109db8dac20SDavid S. Miller 	if (v == SEQ_START_TOKEN)
3110652586dfSTetsuo Handa 		seq_puts(seq, "   sl  local_address rem_address   st tx_queue "
3111db8dac20SDavid S. Miller 			   "rx_queue tr tm->when retrnsmt   uid  timeout "
3112cb61cb9bSEric Dumazet 			   "inode ref pointer drops");
3113db8dac20SDavid S. Miller 	else {
3114db8dac20SDavid S. Miller 		struct udp_iter_state *state = seq->private;
3115db8dac20SDavid S. Miller 
3116652586dfSTetsuo Handa 		udp4_format_sock(v, seq, state->bucket);
3117db8dac20SDavid S. Miller 	}
3118652586dfSTetsuo Handa 	seq_pad(seq, '\n');
3119db8dac20SDavid S. Miller 	return 0;
3120db8dac20SDavid S. Miller }
3121db8dac20SDavid S. Miller 
31225788b3a0SYonghong Song #ifdef CONFIG_BPF_SYSCALL
31235788b3a0SYonghong Song struct bpf_iter__udp {
31245788b3a0SYonghong Song 	__bpf_md_ptr(struct bpf_iter_meta *, meta);
31255788b3a0SYonghong Song 	__bpf_md_ptr(struct udp_sock *, udp_sk);
31265788b3a0SYonghong Song 	uid_t uid __aligned(8);
31275788b3a0SYonghong Song 	int bucket __aligned(8);
31285788b3a0SYonghong Song };
31295788b3a0SYonghong Song 
3130c96dac8dSAditi Ghag struct bpf_udp_iter_state {
3131c96dac8dSAditi Ghag 	struct udp_iter_state state;
3132c96dac8dSAditi Ghag 	unsigned int cur_sk;
3133c96dac8dSAditi Ghag 	unsigned int end_sk;
3134c96dac8dSAditi Ghag 	unsigned int max_sk;
3135c96dac8dSAditi Ghag 	int offset;
3136c96dac8dSAditi Ghag 	struct sock **batch;
3137c96dac8dSAditi Ghag 	bool st_bucket_done;
3138c96dac8dSAditi Ghag };
3139c96dac8dSAditi Ghag 
3140c96dac8dSAditi Ghag static int bpf_iter_udp_realloc_batch(struct bpf_udp_iter_state *iter,
3141c96dac8dSAditi Ghag 				      unsigned int new_batch_sz);
3142c96dac8dSAditi Ghag static struct sock *bpf_iter_udp_batch(struct seq_file *seq)
3143c96dac8dSAditi Ghag {
3144c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = seq->private;
3145c96dac8dSAditi Ghag 	struct udp_iter_state *state = &iter->state;
3146c96dac8dSAditi Ghag 	struct net *net = seq_file_net(seq);
3147c96dac8dSAditi Ghag 	struct udp_table *udptable;
3148c96dac8dSAditi Ghag 	unsigned int batch_sks = 0;
3149c96dac8dSAditi Ghag 	bool resized = false;
3150c96dac8dSAditi Ghag 	struct sock *sk;
3151c96dac8dSAditi Ghag 
3152c96dac8dSAditi Ghag 	/* The current batch is done, so advance the bucket. */
3153c96dac8dSAditi Ghag 	if (iter->st_bucket_done) {
3154c96dac8dSAditi Ghag 		state->bucket++;
3155c96dac8dSAditi Ghag 		iter->offset = 0;
3156c96dac8dSAditi Ghag 	}
3157c96dac8dSAditi Ghag 
3158c96dac8dSAditi Ghag 	udptable = udp_get_table_seq(seq, net);
3159c96dac8dSAditi Ghag 
3160c96dac8dSAditi Ghag again:
3161c96dac8dSAditi Ghag 	/* New batch for the next bucket.
3162c96dac8dSAditi Ghag 	 * Iterate over the hash table to find a bucket with sockets matching
3163c96dac8dSAditi Ghag 	 * the iterator attributes, and return the first matching socket from
3164c96dac8dSAditi Ghag 	 * the bucket. The remaining matched sockets from the bucket are batched
3165c96dac8dSAditi Ghag 	 * before releasing the bucket lock. This allows BPF programs that are
3166c96dac8dSAditi Ghag 	 * called in seq_show to acquire the bucket lock if needed.
3167c96dac8dSAditi Ghag 	 */
3168c96dac8dSAditi Ghag 	iter->cur_sk = 0;
3169c96dac8dSAditi Ghag 	iter->end_sk = 0;
3170c96dac8dSAditi Ghag 	iter->st_bucket_done = false;
3171c96dac8dSAditi Ghag 	batch_sks = 0;
3172c96dac8dSAditi Ghag 
3173c96dac8dSAditi Ghag 	for (; state->bucket <= udptable->mask; state->bucket++) {
3174c96dac8dSAditi Ghag 		struct udp_hslot *hslot2 = &udptable->hash2[state->bucket];
3175c96dac8dSAditi Ghag 
3176c96dac8dSAditi Ghag 		if (hlist_empty(&hslot2->head)) {
3177c96dac8dSAditi Ghag 			iter->offset = 0;
3178c96dac8dSAditi Ghag 			continue;
3179c96dac8dSAditi Ghag 		}
3180c96dac8dSAditi Ghag 
3181c96dac8dSAditi Ghag 		spin_lock_bh(&hslot2->lock);
3182c96dac8dSAditi Ghag 		udp_portaddr_for_each_entry(sk, &hslot2->head) {
3183c96dac8dSAditi Ghag 			if (seq_sk_match(seq, sk)) {
3184c96dac8dSAditi Ghag 				/* Resume from the last iterated socket at the
3185c96dac8dSAditi Ghag 				 * offset in the bucket before iterator was stopped.
3186c96dac8dSAditi Ghag 				 */
3187c96dac8dSAditi Ghag 				if (iter->offset) {
3188c96dac8dSAditi Ghag 					--iter->offset;
3189c96dac8dSAditi Ghag 					continue;
3190c96dac8dSAditi Ghag 				}
3191c96dac8dSAditi Ghag 				if (iter->end_sk < iter->max_sk) {
3192c96dac8dSAditi Ghag 					sock_hold(sk);
3193c96dac8dSAditi Ghag 					iter->batch[iter->end_sk++] = sk;
3194c96dac8dSAditi Ghag 				}
3195c96dac8dSAditi Ghag 				batch_sks++;
3196c96dac8dSAditi Ghag 			}
3197c96dac8dSAditi Ghag 		}
3198c96dac8dSAditi Ghag 		spin_unlock_bh(&hslot2->lock);
3199c96dac8dSAditi Ghag 
3200c96dac8dSAditi Ghag 		if (iter->end_sk)
3201c96dac8dSAditi Ghag 			break;
3202c96dac8dSAditi Ghag 
3203c96dac8dSAditi Ghag 		/* Reset the current bucket's offset before moving to the next bucket. */
3204c96dac8dSAditi Ghag 		iter->offset = 0;
3205c96dac8dSAditi Ghag 	}
3206c96dac8dSAditi Ghag 
3207c96dac8dSAditi Ghag 	/* All done: no batch made. */
3208c96dac8dSAditi Ghag 	if (!iter->end_sk)
3209c96dac8dSAditi Ghag 		return NULL;
3210c96dac8dSAditi Ghag 
3211c96dac8dSAditi Ghag 	if (iter->end_sk == batch_sks) {
3212c96dac8dSAditi Ghag 		/* Batching is done for the current bucket; return the first
3213c96dac8dSAditi Ghag 		 * socket to be iterated from the batch.
3214c96dac8dSAditi Ghag 		 */
3215c96dac8dSAditi Ghag 		iter->st_bucket_done = true;
3216c96dac8dSAditi Ghag 		goto done;
3217c96dac8dSAditi Ghag 	}
3218c96dac8dSAditi Ghag 	if (!resized && !bpf_iter_udp_realloc_batch(iter, batch_sks * 3 / 2)) {
3219c96dac8dSAditi Ghag 		resized = true;
3220c96dac8dSAditi Ghag 		/* After allocating a larger batch, retry one more time to grab
3221c96dac8dSAditi Ghag 		 * the whole bucket.
3222c96dac8dSAditi Ghag 		 */
3223c96dac8dSAditi Ghag 		state->bucket--;
3224c96dac8dSAditi Ghag 		goto again;
3225c96dac8dSAditi Ghag 	}
3226c96dac8dSAditi Ghag done:
3227c96dac8dSAditi Ghag 	return iter->batch[0];
3228c96dac8dSAditi Ghag }
3229c96dac8dSAditi Ghag 
3230c96dac8dSAditi Ghag static void *bpf_iter_udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3231c96dac8dSAditi Ghag {
3232c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = seq->private;
3233c96dac8dSAditi Ghag 	struct sock *sk;
3234c96dac8dSAditi Ghag 
3235c96dac8dSAditi Ghag 	/* Whenever seq_next() is called, the iter->cur_sk is
3236c96dac8dSAditi Ghag 	 * done with seq_show(), so unref the iter->cur_sk.
3237c96dac8dSAditi Ghag 	 */
3238c96dac8dSAditi Ghag 	if (iter->cur_sk < iter->end_sk) {
3239c96dac8dSAditi Ghag 		sock_put(iter->batch[iter->cur_sk++]);
3240c96dac8dSAditi Ghag 		++iter->offset;
3241c96dac8dSAditi Ghag 	}
3242c96dac8dSAditi Ghag 
3243c96dac8dSAditi Ghag 	/* After updating iter->cur_sk, check if there are more sockets
3244c96dac8dSAditi Ghag 	 * available in the current bucket batch.
3245c96dac8dSAditi Ghag 	 */
3246c96dac8dSAditi Ghag 	if (iter->cur_sk < iter->end_sk)
3247c96dac8dSAditi Ghag 		sk = iter->batch[iter->cur_sk];
3248c96dac8dSAditi Ghag 	else
3249c96dac8dSAditi Ghag 		/* Prepare a new batch. */
3250c96dac8dSAditi Ghag 		sk = bpf_iter_udp_batch(seq);
3251c96dac8dSAditi Ghag 
3252c96dac8dSAditi Ghag 	++*pos;
3253c96dac8dSAditi Ghag 	return sk;
3254c96dac8dSAditi Ghag }
3255c96dac8dSAditi Ghag 
3256c96dac8dSAditi Ghag static void *bpf_iter_udp_seq_start(struct seq_file *seq, loff_t *pos)
3257c96dac8dSAditi Ghag {
3258c96dac8dSAditi Ghag 	/* bpf iter does not support lseek, so it always
3259c96dac8dSAditi Ghag 	 * continue from where it was stop()-ped.
3260c96dac8dSAditi Ghag 	 */
3261c96dac8dSAditi Ghag 	if (*pos)
3262c96dac8dSAditi Ghag 		return bpf_iter_udp_batch(seq);
3263c96dac8dSAditi Ghag 
3264c96dac8dSAditi Ghag 	return SEQ_START_TOKEN;
3265c96dac8dSAditi Ghag }
3266c96dac8dSAditi Ghag 
32675788b3a0SYonghong Song static int udp_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
32685788b3a0SYonghong Song 			     struct udp_sock *udp_sk, uid_t uid, int bucket)
32695788b3a0SYonghong Song {
32705788b3a0SYonghong Song 	struct bpf_iter__udp ctx;
32715788b3a0SYonghong Song 
32725788b3a0SYonghong Song 	meta->seq_num--;  /* skip SEQ_START_TOKEN */
32735788b3a0SYonghong Song 	ctx.meta = meta;
32745788b3a0SYonghong Song 	ctx.udp_sk = udp_sk;
32755788b3a0SYonghong Song 	ctx.uid = uid;
32765788b3a0SYonghong Song 	ctx.bucket = bucket;
32775788b3a0SYonghong Song 	return bpf_iter_run_prog(prog, &ctx);
32785788b3a0SYonghong Song }
32795788b3a0SYonghong Song 
32805788b3a0SYonghong Song static int bpf_iter_udp_seq_show(struct seq_file *seq, void *v)
32815788b3a0SYonghong Song {
32825788b3a0SYonghong Song 	struct udp_iter_state *state = seq->private;
32835788b3a0SYonghong Song 	struct bpf_iter_meta meta;
32845788b3a0SYonghong Song 	struct bpf_prog *prog;
32855788b3a0SYonghong Song 	struct sock *sk = v;
32865788b3a0SYonghong Song 	uid_t uid;
3287c96dac8dSAditi Ghag 	int ret;
32885788b3a0SYonghong Song 
32895788b3a0SYonghong Song 	if (v == SEQ_START_TOKEN)
32905788b3a0SYonghong Song 		return 0;
32915788b3a0SYonghong Song 
3292c96dac8dSAditi Ghag 	lock_sock(sk);
3293c96dac8dSAditi Ghag 
3294c96dac8dSAditi Ghag 	if (unlikely(sk_unhashed(sk))) {
3295c96dac8dSAditi Ghag 		ret = SEQ_SKIP;
3296c96dac8dSAditi Ghag 		goto unlock;
3297c96dac8dSAditi Ghag 	}
3298c96dac8dSAditi Ghag 
32995788b3a0SYonghong Song 	uid = from_kuid_munged(seq_user_ns(seq), sock_i_uid(sk));
33005788b3a0SYonghong Song 	meta.seq = seq;
33015788b3a0SYonghong Song 	prog = bpf_iter_get_info(&meta, false);
3302c96dac8dSAditi Ghag 	ret = udp_prog_seq_show(prog, &meta, v, uid, state->bucket);
3303c96dac8dSAditi Ghag 
3304c96dac8dSAditi Ghag unlock:
3305c96dac8dSAditi Ghag 	release_sock(sk);
3306c96dac8dSAditi Ghag 	return ret;
3307c96dac8dSAditi Ghag }
3308c96dac8dSAditi Ghag 
3309c96dac8dSAditi Ghag static void bpf_iter_udp_put_batch(struct bpf_udp_iter_state *iter)
3310c96dac8dSAditi Ghag {
3311c96dac8dSAditi Ghag 	while (iter->cur_sk < iter->end_sk)
3312c96dac8dSAditi Ghag 		sock_put(iter->batch[iter->cur_sk++]);
33135788b3a0SYonghong Song }
33145788b3a0SYonghong Song 
33155788b3a0SYonghong Song static void bpf_iter_udp_seq_stop(struct seq_file *seq, void *v)
33165788b3a0SYonghong Song {
3317c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = seq->private;
33185788b3a0SYonghong Song 	struct bpf_iter_meta meta;
33195788b3a0SYonghong Song 	struct bpf_prog *prog;
33205788b3a0SYonghong Song 
33215788b3a0SYonghong Song 	if (!v) {
33225788b3a0SYonghong Song 		meta.seq = seq;
33235788b3a0SYonghong Song 		prog = bpf_iter_get_info(&meta, true);
33245788b3a0SYonghong Song 		if (prog)
33255788b3a0SYonghong Song 			(void)udp_prog_seq_show(prog, &meta, v, 0, 0);
33265788b3a0SYonghong Song 	}
33275788b3a0SYonghong Song 
3328c96dac8dSAditi Ghag 	if (iter->cur_sk < iter->end_sk) {
3329c96dac8dSAditi Ghag 		bpf_iter_udp_put_batch(iter);
3330c96dac8dSAditi Ghag 		iter->st_bucket_done = false;
3331c96dac8dSAditi Ghag 	}
33325788b3a0SYonghong Song }
33335788b3a0SYonghong Song 
33345788b3a0SYonghong Song static const struct seq_operations bpf_iter_udp_seq_ops = {
3335c96dac8dSAditi Ghag 	.start		= bpf_iter_udp_seq_start,
3336c96dac8dSAditi Ghag 	.next		= bpf_iter_udp_seq_next,
33375788b3a0SYonghong Song 	.stop		= bpf_iter_udp_seq_stop,
33385788b3a0SYonghong Song 	.show		= bpf_iter_udp_seq_show,
33395788b3a0SYonghong Song };
33405788b3a0SYonghong Song #endif
33415788b3a0SYonghong Song 
3342f44b1c51SAditi Ghag static unsigned short seq_file_family(const struct seq_file *seq)
3343f44b1c51SAditi Ghag {
3344f44b1c51SAditi Ghag 	const struct udp_seq_afinfo *afinfo;
3345f44b1c51SAditi Ghag 
3346f44b1c51SAditi Ghag #ifdef CONFIG_BPF_SYSCALL
3347f44b1c51SAditi Ghag 	/* BPF iterator: bpf programs to filter sockets. */
3348f44b1c51SAditi Ghag 	if (seq->op == &bpf_iter_udp_seq_ops)
3349f44b1c51SAditi Ghag 		return AF_UNSPEC;
3350f44b1c51SAditi Ghag #endif
3351f44b1c51SAditi Ghag 
3352f44b1c51SAditi Ghag 	/* Proc fs iterator */
3353f44b1c51SAditi Ghag 	afinfo = pde_data(file_inode(seq->file));
3354f44b1c51SAditi Ghag 	return afinfo->family;
3355f44b1c51SAditi Ghag }
3356f44b1c51SAditi Ghag 
3357c3506372SChristoph Hellwig const struct seq_operations udp_seq_ops = {
3358a3d2599bSChristoph Hellwig 	.start		= udp_seq_start,
3359a3d2599bSChristoph Hellwig 	.next		= udp_seq_next,
3360a3d2599bSChristoph Hellwig 	.stop		= udp_seq_stop,
3361a3d2599bSChristoph Hellwig 	.show		= udp4_seq_show,
3362a3d2599bSChristoph Hellwig };
3363c3506372SChristoph Hellwig EXPORT_SYMBOL(udp_seq_ops);
336473cb88ecSArjan van de Ven 
3365db8dac20SDavid S. Miller static struct udp_seq_afinfo udp4_seq_afinfo = {
3366db8dac20SDavid S. Miller 	.family		= AF_INET,
3367478aee5dSKuniyuki Iwashima 	.udp_table	= NULL,
3368db8dac20SDavid S. Miller };
3369db8dac20SDavid S. Miller 
33702c8c1e72SAlexey Dobriyan static int __net_init udp4_proc_init_net(struct net *net)
337115439febSPavel Emelyanov {
3372c3506372SChristoph Hellwig 	if (!proc_create_net_data("udp", 0444, net->proc_net, &udp_seq_ops,
3373c3506372SChristoph Hellwig 			sizeof(struct udp_iter_state), &udp4_seq_afinfo))
3374a3d2599bSChristoph Hellwig 		return -ENOMEM;
3375a3d2599bSChristoph Hellwig 	return 0;
337615439febSPavel Emelyanov }
337715439febSPavel Emelyanov 
33782c8c1e72SAlexey Dobriyan static void __net_exit udp4_proc_exit_net(struct net *net)
337915439febSPavel Emelyanov {
3380a3d2599bSChristoph Hellwig 	remove_proc_entry("udp", net->proc_net);
338115439febSPavel Emelyanov }
338215439febSPavel Emelyanov 
338315439febSPavel Emelyanov static struct pernet_operations udp4_net_ops = {
338415439febSPavel Emelyanov 	.init = udp4_proc_init_net,
338515439febSPavel Emelyanov 	.exit = udp4_proc_exit_net,
338615439febSPavel Emelyanov };
338715439febSPavel Emelyanov 
3388db8dac20SDavid S. Miller int __init udp4_proc_init(void)
3389db8dac20SDavid S. Miller {
339015439febSPavel Emelyanov 	return register_pernet_subsys(&udp4_net_ops);
3391db8dac20SDavid S. Miller }
3392db8dac20SDavid S. Miller 
3393db8dac20SDavid S. Miller void udp4_proc_exit(void)
3394db8dac20SDavid S. Miller {
339515439febSPavel Emelyanov 	unregister_pernet_subsys(&udp4_net_ops);
3396db8dac20SDavid S. Miller }
33971da177e4SLinus Torvalds #endif /* CONFIG_PROC_FS */
33981da177e4SLinus Torvalds 
3399f86dcc5aSEric Dumazet static __initdata unsigned long uhash_entries;
3400f86dcc5aSEric Dumazet static int __init set_uhash_entries(char *str)
3401645ca708SEric Dumazet {
3402413c27d8SEldad Zack 	ssize_t ret;
3403413c27d8SEldad Zack 
3404f86dcc5aSEric Dumazet 	if (!str)
3405f86dcc5aSEric Dumazet 		return 0;
3406413c27d8SEldad Zack 
3407413c27d8SEldad Zack 	ret = kstrtoul(str, 0, &uhash_entries);
3408413c27d8SEldad Zack 	if (ret)
3409413c27d8SEldad Zack 		return 0;
3410413c27d8SEldad Zack 
3411f86dcc5aSEric Dumazet 	if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
3412f86dcc5aSEric Dumazet 		uhash_entries = UDP_HTABLE_SIZE_MIN;
3413f86dcc5aSEric Dumazet 	return 1;
3414f86dcc5aSEric Dumazet }
3415f86dcc5aSEric Dumazet __setup("uhash_entries=", set_uhash_entries);
3416645ca708SEric Dumazet 
3417f86dcc5aSEric Dumazet void __init udp_table_init(struct udp_table *table, const char *name)
3418f86dcc5aSEric Dumazet {
3419f86dcc5aSEric Dumazet 	unsigned int i;
3420f86dcc5aSEric Dumazet 
3421f86dcc5aSEric Dumazet 	table->hash = alloc_large_system_hash(name,
3422512615b6SEric Dumazet 					      2 * sizeof(struct udp_hslot),
3423f86dcc5aSEric Dumazet 					      uhash_entries,
3424f86dcc5aSEric Dumazet 					      21, /* one slot per 2 MB */
3425f86dcc5aSEric Dumazet 					      0,
3426f86dcc5aSEric Dumazet 					      &table->log,
3427f86dcc5aSEric Dumazet 					      &table->mask,
342831fe62b9STim Bird 					      UDP_HTABLE_SIZE_MIN,
34299804985bSKuniyuki Iwashima 					      UDP_HTABLE_SIZE_MAX);
343031fe62b9STim Bird 
3431512615b6SEric Dumazet 	table->hash2 = table->hash + (table->mask + 1);
3432f86dcc5aSEric Dumazet 	for (i = 0; i <= table->mask; i++) {
3433ca065d0cSEric Dumazet 		INIT_HLIST_HEAD(&table->hash[i].head);
3434fdcc8aa9SEric Dumazet 		table->hash[i].count = 0;
3435645ca708SEric Dumazet 		spin_lock_init(&table->hash[i].lock);
3436645ca708SEric Dumazet 	}
3437512615b6SEric Dumazet 	for (i = 0; i <= table->mask; i++) {
3438ca065d0cSEric Dumazet 		INIT_HLIST_HEAD(&table->hash2[i].head);
3439512615b6SEric Dumazet 		table->hash2[i].count = 0;
3440512615b6SEric Dumazet 		spin_lock_init(&table->hash2[i].lock);
3441512615b6SEric Dumazet 	}
3442645ca708SEric Dumazet }
3443645ca708SEric Dumazet 
3444723b8e46STom Herbert u32 udp_flow_hashrnd(void)
3445723b8e46STom Herbert {
3446723b8e46STom Herbert 	static u32 hashrnd __read_mostly;
3447723b8e46STom Herbert 
3448723b8e46STom Herbert 	net_get_random_once(&hashrnd, sizeof(hashrnd));
3449723b8e46STom Herbert 
3450723b8e46STom Herbert 	return hashrnd;
3451723b8e46STom Herbert }
3452723b8e46STom Herbert EXPORT_SYMBOL(udp_flow_hashrnd);
3453723b8e46STom Herbert 
34549804985bSKuniyuki Iwashima static void __net_init udp_sysctl_init(struct net *net)
34551e802951STonghao Zhang {
3456100fdd1fSEric Dumazet 	net->ipv4.sysctl_udp_rmem_min = PAGE_SIZE;
3457100fdd1fSEric Dumazet 	net->ipv4.sysctl_udp_wmem_min = PAGE_SIZE;
34581e802951STonghao Zhang 
34591e802951STonghao Zhang #ifdef CONFIG_NET_L3_MASTER_DEV
34601e802951STonghao Zhang 	net->ipv4.sysctl_udp_l3mdev_accept = 0;
34611e802951STonghao Zhang #endif
34629804985bSKuniyuki Iwashima }
34639804985bSKuniyuki Iwashima 
34649804985bSKuniyuki Iwashima static struct udp_table __net_init *udp_pernet_table_alloc(unsigned int hash_entries)
34659804985bSKuniyuki Iwashima {
34669804985bSKuniyuki Iwashima 	struct udp_table *udptable;
34679804985bSKuniyuki Iwashima 	int i;
34689804985bSKuniyuki Iwashima 
34699804985bSKuniyuki Iwashima 	udptable = kmalloc(sizeof(*udptable), GFP_KERNEL);
34709804985bSKuniyuki Iwashima 	if (!udptable)
34719804985bSKuniyuki Iwashima 		goto out;
34729804985bSKuniyuki Iwashima 
34739804985bSKuniyuki Iwashima 	udptable->hash = vmalloc_huge(hash_entries * 2 * sizeof(struct udp_hslot),
34749804985bSKuniyuki Iwashima 				      GFP_KERNEL_ACCOUNT);
34759804985bSKuniyuki Iwashima 	if (!udptable->hash)
34769804985bSKuniyuki Iwashima 		goto free_table;
34779804985bSKuniyuki Iwashima 
34789804985bSKuniyuki Iwashima 	udptable->hash2 = udptable->hash + hash_entries;
34799804985bSKuniyuki Iwashima 	udptable->mask = hash_entries - 1;
34809804985bSKuniyuki Iwashima 	udptable->log = ilog2(hash_entries);
34819804985bSKuniyuki Iwashima 
34829804985bSKuniyuki Iwashima 	for (i = 0; i < hash_entries; i++) {
34839804985bSKuniyuki Iwashima 		INIT_HLIST_HEAD(&udptable->hash[i].head);
34849804985bSKuniyuki Iwashima 		udptable->hash[i].count = 0;
34859804985bSKuniyuki Iwashima 		spin_lock_init(&udptable->hash[i].lock);
34869804985bSKuniyuki Iwashima 
34879804985bSKuniyuki Iwashima 		INIT_HLIST_HEAD(&udptable->hash2[i].head);
34889804985bSKuniyuki Iwashima 		udptable->hash2[i].count = 0;
34899804985bSKuniyuki Iwashima 		spin_lock_init(&udptable->hash2[i].lock);
34909804985bSKuniyuki Iwashima 	}
34919804985bSKuniyuki Iwashima 
34929804985bSKuniyuki Iwashima 	return udptable;
34939804985bSKuniyuki Iwashima 
34949804985bSKuniyuki Iwashima free_table:
34959804985bSKuniyuki Iwashima 	kfree(udptable);
34969804985bSKuniyuki Iwashima out:
34979804985bSKuniyuki Iwashima 	return NULL;
34989804985bSKuniyuki Iwashima }
34999804985bSKuniyuki Iwashima 
35009804985bSKuniyuki Iwashima static void __net_exit udp_pernet_table_free(struct net *net)
35019804985bSKuniyuki Iwashima {
35029804985bSKuniyuki Iwashima 	struct udp_table *udptable = net->ipv4.udp_table;
35039804985bSKuniyuki Iwashima 
35049804985bSKuniyuki Iwashima 	if (udptable == &udp_table)
35059804985bSKuniyuki Iwashima 		return;
35069804985bSKuniyuki Iwashima 
35079804985bSKuniyuki Iwashima 	kvfree(udptable->hash);
35089804985bSKuniyuki Iwashima 	kfree(udptable);
35099804985bSKuniyuki Iwashima }
35109804985bSKuniyuki Iwashima 
35119804985bSKuniyuki Iwashima static void __net_init udp_set_table(struct net *net)
35129804985bSKuniyuki Iwashima {
35139804985bSKuniyuki Iwashima 	struct udp_table *udptable;
35149804985bSKuniyuki Iwashima 	unsigned int hash_entries;
35159804985bSKuniyuki Iwashima 	struct net *old_net;
35169804985bSKuniyuki Iwashima 
35179804985bSKuniyuki Iwashima 	if (net_eq(net, &init_net))
35189804985bSKuniyuki Iwashima 		goto fallback;
35199804985bSKuniyuki Iwashima 
35209804985bSKuniyuki Iwashima 	old_net = current->nsproxy->net_ns;
35219804985bSKuniyuki Iwashima 	hash_entries = READ_ONCE(old_net->ipv4.sysctl_udp_child_hash_entries);
35229804985bSKuniyuki Iwashima 	if (!hash_entries)
35239804985bSKuniyuki Iwashima 		goto fallback;
35249804985bSKuniyuki Iwashima 
35259804985bSKuniyuki Iwashima 	/* Set min to keep the bitmap on stack in udp_lib_get_port() */
35269804985bSKuniyuki Iwashima 	if (hash_entries < UDP_HTABLE_SIZE_MIN_PERNET)
35279804985bSKuniyuki Iwashima 		hash_entries = UDP_HTABLE_SIZE_MIN_PERNET;
35289804985bSKuniyuki Iwashima 	else
35299804985bSKuniyuki Iwashima 		hash_entries = roundup_pow_of_two(hash_entries);
35309804985bSKuniyuki Iwashima 
35319804985bSKuniyuki Iwashima 	udptable = udp_pernet_table_alloc(hash_entries);
35329804985bSKuniyuki Iwashima 	if (udptable) {
35339804985bSKuniyuki Iwashima 		net->ipv4.udp_table = udptable;
35349804985bSKuniyuki Iwashima 	} else {
35359804985bSKuniyuki Iwashima 		pr_warn("Failed to allocate UDP hash table (entries: %u) "
35369804985bSKuniyuki Iwashima 			"for a netns, fallback to the global one\n",
35379804985bSKuniyuki Iwashima 			hash_entries);
35389804985bSKuniyuki Iwashima fallback:
35399804985bSKuniyuki Iwashima 		net->ipv4.udp_table = &udp_table;
35409804985bSKuniyuki Iwashima 	}
35419804985bSKuniyuki Iwashima }
35429804985bSKuniyuki Iwashima 
35439804985bSKuniyuki Iwashima static int __net_init udp_pernet_init(struct net *net)
35449804985bSKuniyuki Iwashima {
35459804985bSKuniyuki Iwashima 	udp_sysctl_init(net);
35469804985bSKuniyuki Iwashima 	udp_set_table(net);
35471e802951STonghao Zhang 
35481e802951STonghao Zhang 	return 0;
35491e802951STonghao Zhang }
35501e802951STonghao Zhang 
35519804985bSKuniyuki Iwashima static void __net_exit udp_pernet_exit(struct net *net)
35529804985bSKuniyuki Iwashima {
35539804985bSKuniyuki Iwashima 	udp_pernet_table_free(net);
35549804985bSKuniyuki Iwashima }
35559804985bSKuniyuki Iwashima 
35561e802951STonghao Zhang static struct pernet_operations __net_initdata udp_sysctl_ops = {
35579804985bSKuniyuki Iwashima 	.init	= udp_pernet_init,
35589804985bSKuniyuki Iwashima 	.exit	= udp_pernet_exit,
35591e802951STonghao Zhang };
35601e802951STonghao Zhang 
35615788b3a0SYonghong Song #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
35625788b3a0SYonghong Song DEFINE_BPF_ITER_FUNC(udp, struct bpf_iter_meta *meta,
35635788b3a0SYonghong Song 		     struct udp_sock *udp_sk, uid_t uid, int bucket)
35645788b3a0SYonghong Song 
3565c96dac8dSAditi Ghag static int bpf_iter_udp_realloc_batch(struct bpf_udp_iter_state *iter,
3566c96dac8dSAditi Ghag 				      unsigned int new_batch_sz)
35675788b3a0SYonghong Song {
3568c96dac8dSAditi Ghag 	struct sock **new_batch;
35695788b3a0SYonghong Song 
3570c96dac8dSAditi Ghag 	new_batch = kvmalloc_array(new_batch_sz, sizeof(*new_batch),
3571c96dac8dSAditi Ghag 				   GFP_USER | __GFP_NOWARN);
3572c96dac8dSAditi Ghag 	if (!new_batch)
35735788b3a0SYonghong Song 		return -ENOMEM;
35745788b3a0SYonghong Song 
3575c96dac8dSAditi Ghag 	bpf_iter_udp_put_batch(iter);
3576c96dac8dSAditi Ghag 	kvfree(iter->batch);
3577c96dac8dSAditi Ghag 	iter->batch = new_batch;
3578c96dac8dSAditi Ghag 	iter->max_sk = new_batch_sz;
3579c96dac8dSAditi Ghag 
3580c96dac8dSAditi Ghag 	return 0;
3581c96dac8dSAditi Ghag }
3582c96dac8dSAditi Ghag 
3583c96dac8dSAditi Ghag #define INIT_BATCH_SZ 16
3584c96dac8dSAditi Ghag 
35855788b3a0SYonghong Song static int bpf_iter_init_udp(void *priv_data, struct bpf_iter_aux_info *aux)
35865788b3a0SYonghong Song {
3587c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = priv_data;
3588c96dac8dSAditi Ghag 	int ret;
3589c96dac8dSAditi Ghag 
3590f9c79272SYonghong Song 	ret = bpf_iter_init_seq_net(priv_data, aux);
35915788b3a0SYonghong Song 	if (ret)
3592c96dac8dSAditi Ghag 		return ret;
3593c96dac8dSAditi Ghag 
3594c96dac8dSAditi Ghag 	ret = bpf_iter_udp_realloc_batch(iter, INIT_BATCH_SZ);
3595c96dac8dSAditi Ghag 	if (ret)
3596c96dac8dSAditi Ghag 		bpf_iter_fini_seq_net(priv_data);
3597c96dac8dSAditi Ghag 
35985788b3a0SYonghong Song 	return ret;
35995788b3a0SYonghong Song }
36005788b3a0SYonghong Song 
36015788b3a0SYonghong Song static void bpf_iter_fini_udp(void *priv_data)
36025788b3a0SYonghong Song {
3603c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = priv_data;
36045788b3a0SYonghong Song 
36055788b3a0SYonghong Song 	bpf_iter_fini_seq_net(priv_data);
3606c96dac8dSAditi Ghag 	kvfree(iter->batch);
36075788b3a0SYonghong Song }
36085788b3a0SYonghong Song 
360914fc6bd6SYonghong Song static const struct bpf_iter_seq_info udp_seq_info = {
36105788b3a0SYonghong Song 	.seq_ops		= &bpf_iter_udp_seq_ops,
36115788b3a0SYonghong Song 	.init_seq_private	= bpf_iter_init_udp,
36125788b3a0SYonghong Song 	.fini_seq_private	= bpf_iter_fini_udp,
3613c96dac8dSAditi Ghag 	.seq_priv_size		= sizeof(struct bpf_udp_iter_state),
361414fc6bd6SYonghong Song };
361514fc6bd6SYonghong Song 
361614fc6bd6SYonghong Song static struct bpf_iter_reg udp_reg_info = {
361714fc6bd6SYonghong Song 	.target			= "udp",
36185788b3a0SYonghong Song 	.ctx_arg_info_size	= 1,
36195788b3a0SYonghong Song 	.ctx_arg_info		= {
36205788b3a0SYonghong Song 		{ offsetof(struct bpf_iter__udp, udp_sk),
36214ddbcb88SAditi Ghag 		  PTR_TO_BTF_ID_OR_NULL | PTR_TRUSTED },
36225788b3a0SYonghong Song 	},
362314fc6bd6SYonghong Song 	.seq_info		= &udp_seq_info,
36245788b3a0SYonghong Song };
36255788b3a0SYonghong Song 
36265788b3a0SYonghong Song static void __init bpf_iter_register(void)
36275788b3a0SYonghong Song {
3628951cf368SYonghong Song 	udp_reg_info.ctx_arg_info[0].btf_id = btf_sock_ids[BTF_SOCK_TYPE_UDP];
36295788b3a0SYonghong Song 	if (bpf_iter_reg_target(&udp_reg_info))
36305788b3a0SYonghong Song 		pr_warn("Warning: could not register bpf iterator udp\n");
36315788b3a0SYonghong Song }
36325788b3a0SYonghong Song #endif
36335788b3a0SYonghong Song 
363495766fffSHideo Aoki void __init udp_init(void)
363595766fffSHideo Aoki {
3636f03d78dbSEric Dumazet 	unsigned long limit;
36374b272750SEric Dumazet 	unsigned int i;
363895766fffSHideo Aoki 
3639f86dcc5aSEric Dumazet 	udp_table_init(&udp_table, "UDP");
3640f03d78dbSEric Dumazet 	limit = nr_free_buffer_pages() / 8;
364195766fffSHideo Aoki 	limit = max(limit, 128UL);
364295766fffSHideo Aoki 	sysctl_udp_mem[0] = limit / 4 * 3;
364395766fffSHideo Aoki 	sysctl_udp_mem[1] = limit;
364495766fffSHideo Aoki 	sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
364595766fffSHideo Aoki 
36464b272750SEric Dumazet 	/* 16 spinlocks per cpu */
36474b272750SEric Dumazet 	udp_busylocks_log = ilog2(nr_cpu_ids) + 4;
36484b272750SEric Dumazet 	udp_busylocks = kmalloc(sizeof(spinlock_t) << udp_busylocks_log,
36494b272750SEric Dumazet 				GFP_KERNEL);
36504b272750SEric Dumazet 	if (!udp_busylocks)
36514b272750SEric Dumazet 		panic("UDP: failed to alloc udp_busylocks\n");
36524b272750SEric Dumazet 	for (i = 0; i < (1U << udp_busylocks_log); i++)
36534b272750SEric Dumazet 		spin_lock_init(udp_busylocks + i);
36541e802951STonghao Zhang 
36551e802951STonghao Zhang 	if (register_pernet_subsys(&udp_sysctl_ops))
36561e802951STonghao Zhang 		panic("UDP: failed to init sysctl parameters.\n");
36575788b3a0SYonghong Song 
36585788b3a0SYonghong Song #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
36595788b3a0SYonghong Song 	bpf_iter_register();
36605788b3a0SYonghong Song #endif
366195766fffSHideo Aoki }
3662