xref: /linux/net/ipv4/udp.c (revision 72f7e9440e9bd06f855b21eba09c1017395f430a)
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 
777c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
781da177e4SLinus Torvalds #include <asm/ioctls.h>
7957c8a661SMike Rapoport #include <linux/memblock.h>
808203efb3SEric Dumazet #include <linux/highmem.h>
818203efb3SEric Dumazet #include <linux/swap.h>
821da177e4SLinus Torvalds #include <linux/types.h>
831da177e4SLinus Torvalds #include <linux/fcntl.h>
841da177e4SLinus Torvalds #include <linux/module.h>
851da177e4SLinus Torvalds #include <linux/socket.h>
861da177e4SLinus Torvalds #include <linux/sockios.h>
8714c85021SArnaldo Carvalho de Melo #include <linux/igmp.h>
886e540309SShawn Bohrer #include <linux/inetdevice.h>
891da177e4SLinus Torvalds #include <linux/in.h>
901da177e4SLinus Torvalds #include <linux/errno.h>
911da177e4SLinus Torvalds #include <linux/timer.h>
921da177e4SLinus Torvalds #include <linux/mm.h>
931da177e4SLinus Torvalds #include <linux/inet.h>
941da177e4SLinus Torvalds #include <linux/netdevice.h>
955a0e3ad6STejun Heo #include <linux/slab.h>
96c752f073SArnaldo Carvalho de Melo #include <net/tcp_states.h>
971da177e4SLinus Torvalds #include <linux/skbuff.h>
981da177e4SLinus Torvalds #include <linux/proc_fs.h>
991da177e4SLinus Torvalds #include <linux/seq_file.h>
100457c4cbcSEric W. Biederman #include <net/net_namespace.h>
1011da177e4SLinus Torvalds #include <net/icmp.h>
102421b3885SShawn Bohrer #include <net/inet_hashtables.h>
103e7cc0824SStefano Brivio #include <net/ip_tunnels.h>
1041da177e4SLinus Torvalds #include <net/route.h>
1051da177e4SLinus Torvalds #include <net/checksum.h>
1061da177e4SLinus Torvalds #include <net/xfrm.h>
107296f7ea7SSatoru Moriya #include <trace/events/udp.h>
108447167bfSEric Dumazet #include <linux/static_key.h>
10922911fc5SEric Dumazet #include <trace/events/skb.h>
110076bb0c8SEliezer Tamir #include <net/busy_poll.h>
111ba4e58ecSGerrit Renker #include "udp_impl.h"
112e32ea7e7SCraig Gallek #include <net/sock_reuseport.h>
113217375a0SEric Dumazet #include <net/addrconf.h>
11460fb9567SPaolo Abeni #include <net/udp_tunnel.h>
1150146dca7SSabrina Dubroca #if IS_ENABLED(CONFIG_IPV6)
1160146dca7SSabrina Dubroca #include <net/ipv6_stubs.h>
1170146dca7SSabrina Dubroca #endif
1181da177e4SLinus Torvalds 
119f86dcc5aSEric Dumazet struct udp_table udp_table __read_mostly;
120645ca708SEric Dumazet EXPORT_SYMBOL(udp_table);
1211da177e4SLinus Torvalds 
1228d987e5cSEric Dumazet long sysctl_udp_mem[3] __read_mostly;
12395766fffSHideo Aoki EXPORT_SYMBOL(sysctl_udp_mem);
124c482c568SEric Dumazet 
1258d987e5cSEric Dumazet atomic_long_t udp_memory_allocated;
12695766fffSHideo Aoki EXPORT_SYMBOL(udp_memory_allocated);
12795766fffSHideo Aoki 
128f86dcc5aSEric Dumazet #define MAX_UDP_PORTS 65536
129f86dcc5aSEric Dumazet #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN)
13098322f22SEric Dumazet 
131f24d43c0SEric Dumazet static int udp_lib_lport_inuse(struct net *net, __u16 num,
132645ca708SEric Dumazet 			       const struct udp_hslot *hslot,
13398322f22SEric Dumazet 			       unsigned long *bitmap,
134fe38d2a1SJosef Bacik 			       struct sock *sk, unsigned int log)
13525030a7fSGerrit Renker {
136f24d43c0SEric Dumazet 	struct sock *sk2;
137ba418fa3STom Herbert 	kuid_t uid = sock_i_uid(sk);
13825030a7fSGerrit Renker 
139ca065d0cSEric Dumazet 	sk_for_each(sk2, &hslot->head) {
140f24d43c0SEric Dumazet 		if (net_eq(sock_net(sk2), net) &&
141f24d43c0SEric Dumazet 		    sk2 != sk &&
142d4cada4aSEric Dumazet 		    (bitmap || udp_sk(sk2)->udp_port_hash == num) &&
143f24d43c0SEric Dumazet 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
1449d4fb27dSJoe Perches 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
1459d4fb27dSJoe Perches 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
146fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, true)) {
147df560056SEric Garver 			if (sk2->sk_reuseport && sk->sk_reuseport &&
148df560056SEric Garver 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
149df560056SEric Garver 			    uid_eq(uid, sock_i_uid(sk2))) {
150df560056SEric Garver 				if (!bitmap)
151df560056SEric Garver 					return 0;
152df560056SEric Garver 			} else {
1534243cdc2SJoe Perches 				if (!bitmap)
154fc038410SDavid S. Miller 					return 1;
155df560056SEric Garver 				__set_bit(udp_sk(sk2)->udp_port_hash >> log,
156df560056SEric Garver 					  bitmap);
157df560056SEric Garver 			}
1584243cdc2SJoe Perches 		}
15998322f22SEric Dumazet 	}
16025030a7fSGerrit Renker 	return 0;
16125030a7fSGerrit Renker }
16225030a7fSGerrit Renker 
16330fff923SEric Dumazet /*
16430fff923SEric Dumazet  * Note: we still hold spinlock of primary hash chain, so no other writer
16530fff923SEric Dumazet  * can insert/delete a socket with local_port == num
16630fff923SEric Dumazet  */
16730fff923SEric Dumazet static int udp_lib_lport_inuse2(struct net *net, __u16 num,
16830fff923SEric Dumazet 				struct udp_hslot *hslot2,
169fe38d2a1SJosef Bacik 				struct sock *sk)
17030fff923SEric Dumazet {
17130fff923SEric Dumazet 	struct sock *sk2;
172ba418fa3STom Herbert 	kuid_t uid = sock_i_uid(sk);
17330fff923SEric Dumazet 	int res = 0;
17430fff923SEric Dumazet 
17530fff923SEric Dumazet 	spin_lock(&hslot2->lock);
176ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry(sk2, &hslot2->head) {
17730fff923SEric Dumazet 		if (net_eq(sock_net(sk2), net) &&
17830fff923SEric Dumazet 		    sk2 != sk &&
17930fff923SEric Dumazet 		    (udp_sk(sk2)->udp_port_hash == num) &&
18030fff923SEric Dumazet 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
1819d4fb27dSJoe Perches 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
1829d4fb27dSJoe Perches 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
183fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, true)) {
184df560056SEric Garver 			if (sk2->sk_reuseport && sk->sk_reuseport &&
185df560056SEric Garver 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
186df560056SEric Garver 			    uid_eq(uid, sock_i_uid(sk2))) {
187df560056SEric Garver 				res = 0;
188df560056SEric Garver 			} else {
18930fff923SEric Dumazet 				res = 1;
190df560056SEric Garver 			}
19130fff923SEric Dumazet 			break;
19230fff923SEric Dumazet 		}
1934243cdc2SJoe Perches 	}
19430fff923SEric Dumazet 	spin_unlock(&hslot2->lock);
19530fff923SEric Dumazet 	return res;
19630fff923SEric Dumazet }
19730fff923SEric Dumazet 
198fe38d2a1SJosef Bacik static int udp_reuseport_add_sock(struct sock *sk, struct udp_hslot *hslot)
199e32ea7e7SCraig Gallek {
200e32ea7e7SCraig Gallek 	struct net *net = sock_net(sk);
201e32ea7e7SCraig Gallek 	kuid_t uid = sock_i_uid(sk);
202e32ea7e7SCraig Gallek 	struct sock *sk2;
203e32ea7e7SCraig Gallek 
204ca065d0cSEric Dumazet 	sk_for_each(sk2, &hslot->head) {
205e32ea7e7SCraig Gallek 		if (net_eq(sock_net(sk2), net) &&
206e32ea7e7SCraig Gallek 		    sk2 != sk &&
207e32ea7e7SCraig Gallek 		    sk2->sk_family == sk->sk_family &&
208e32ea7e7SCraig Gallek 		    ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
209e32ea7e7SCraig Gallek 		    (udp_sk(sk2)->udp_port_hash == udp_sk(sk)->udp_port_hash) &&
210e32ea7e7SCraig Gallek 		    (sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
211e32ea7e7SCraig Gallek 		    sk2->sk_reuseport && uid_eq(uid, sock_i_uid(sk2)) &&
212fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, false)) {
2132dbb9b9eSMartin KaFai Lau 			return reuseport_add_sock(sk, sk2,
2142dbb9b9eSMartin KaFai Lau 						  inet_rcv_saddr_any(sk));
215e32ea7e7SCraig Gallek 		}
216e32ea7e7SCraig Gallek 	}
217e32ea7e7SCraig Gallek 
2182dbb9b9eSMartin KaFai Lau 	return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
219e32ea7e7SCraig Gallek }
220e32ea7e7SCraig Gallek 
22125030a7fSGerrit Renker /**
2226ba5a3c5SPavel Emelyanov  *  udp_lib_get_port  -  UDP/-Lite port lookup for IPv4 and IPv6
22325030a7fSGerrit Renker  *
22425030a7fSGerrit Renker  *  @sk:          socket struct in question
22525030a7fSGerrit Renker  *  @snum:        port number to look up
22625985edcSLucas De Marchi  *  @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
22730fff923SEric Dumazet  *                   with NULL address
22825030a7fSGerrit Renker  */
2296ba5a3c5SPavel Emelyanov int udp_lib_get_port(struct sock *sk, unsigned short snum,
23030fff923SEric Dumazet 		     unsigned int hash2_nulladdr)
2311da177e4SLinus Torvalds {
232512615b6SEric Dumazet 	struct udp_hslot *hslot, *hslot2;
233645ca708SEric Dumazet 	struct udp_table *udptable = sk->sk_prot->h.udp_table;
23425030a7fSGerrit Renker 	int    error = 1;
2353b1e0a65SYOSHIFUJI Hideaki 	struct net *net = sock_net(sk);
2361da177e4SLinus Torvalds 
23732c1da70SStephen Hemminger 	if (!snum) {
2389088c560SEric Dumazet 		int low, high, remaining;
23995c96174SEric Dumazet 		unsigned int rand;
24098322f22SEric Dumazet 		unsigned short first, last;
24198322f22SEric Dumazet 		DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
2421da177e4SLinus Torvalds 
2430bbf87d8SEric W. Biederman 		inet_get_local_port_range(net, &low, &high);
244a25de534SAnton Arapov 		remaining = (high - low) + 1;
245227b60f5SStephen Hemminger 
24663862b5bSAruna-Hewapathirane 		rand = prandom_u32();
2478fc54f68SDaniel Borkmann 		first = reciprocal_scale(rand, remaining) + low;
24898322f22SEric Dumazet 		/*
24998322f22SEric Dumazet 		 * force rand to be an odd multiple of UDP_HTABLE_SIZE
25098322f22SEric Dumazet 		 */
251f86dcc5aSEric Dumazet 		rand = (rand | 1) * (udptable->mask + 1);
2525781b235SEric Dumazet 		last = first + udptable->mask + 1;
2535781b235SEric Dumazet 		do {
254f86dcc5aSEric Dumazet 			hslot = udp_hashslot(udptable, net, first);
25598322f22SEric Dumazet 			bitmap_zero(bitmap, PORTS_PER_CHAIN);
256645ca708SEric Dumazet 			spin_lock_bh(&hslot->lock);
25798322f22SEric Dumazet 			udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
258fe38d2a1SJosef Bacik 					    udptable->log);
25998322f22SEric Dumazet 
26098322f22SEric Dumazet 			snum = first;
26198322f22SEric Dumazet 			/*
26298322f22SEric Dumazet 			 * Iterate on all possible values of snum for this hash.
26398322f22SEric Dumazet 			 * Using steps of an odd multiple of UDP_HTABLE_SIZE
26498322f22SEric Dumazet 			 * give us randomization and full range coverage.
26598322f22SEric Dumazet 			 */
2669088c560SEric Dumazet 			do {
26798322f22SEric Dumazet 				if (low <= snum && snum <= high &&
268e3826f1eSAmerigo Wang 				    !test_bit(snum >> udptable->log, bitmap) &&
269122ff243SWANG Cong 				    !inet_is_local_reserved_port(net, snum))
27098322f22SEric Dumazet 					goto found;
27198322f22SEric Dumazet 				snum += rand;
27298322f22SEric Dumazet 			} while (snum != first);
27398322f22SEric Dumazet 			spin_unlock_bh(&hslot->lock);
274df560056SEric Garver 			cond_resched();
2755781b235SEric Dumazet 		} while (++first != last);
27698322f22SEric Dumazet 		goto fail;
277645ca708SEric Dumazet 	} else {
278f86dcc5aSEric Dumazet 		hslot = udp_hashslot(udptable, net, snum);
279645ca708SEric Dumazet 		spin_lock_bh(&hslot->lock);
28030fff923SEric Dumazet 		if (hslot->count > 10) {
28130fff923SEric Dumazet 			int exist;
28230fff923SEric Dumazet 			unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
28330fff923SEric Dumazet 
28430fff923SEric Dumazet 			slot2          &= udptable->mask;
28530fff923SEric Dumazet 			hash2_nulladdr &= udptable->mask;
28630fff923SEric Dumazet 
28730fff923SEric Dumazet 			hslot2 = udp_hashslot2(udptable, slot2);
28830fff923SEric Dumazet 			if (hslot->count < hslot2->count)
28930fff923SEric Dumazet 				goto scan_primary_hash;
29030fff923SEric Dumazet 
291fe38d2a1SJosef Bacik 			exist = udp_lib_lport_inuse2(net, snum, hslot2, sk);
29230fff923SEric Dumazet 			if (!exist && (hash2_nulladdr != slot2)) {
29330fff923SEric Dumazet 				hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
29430fff923SEric Dumazet 				exist = udp_lib_lport_inuse2(net, snum, hslot2,
295fe38d2a1SJosef Bacik 							     sk);
29630fff923SEric Dumazet 			}
29730fff923SEric Dumazet 			if (exist)
29830fff923SEric Dumazet 				goto fail_unlock;
29930fff923SEric Dumazet 			else
30030fff923SEric Dumazet 				goto found;
30130fff923SEric Dumazet 		}
30230fff923SEric Dumazet scan_primary_hash:
303fe38d2a1SJosef Bacik 		if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, 0))
304645ca708SEric Dumazet 			goto fail_unlock;
305645ca708SEric Dumazet 	}
30698322f22SEric Dumazet found:
307c720c7e8SEric Dumazet 	inet_sk(sk)->inet_num = snum;
308d4cada4aSEric Dumazet 	udp_sk(sk)->udp_port_hash = snum;
309d4cada4aSEric Dumazet 	udp_sk(sk)->udp_portaddr_hash ^= snum;
3101da177e4SLinus Torvalds 	if (sk_unhashed(sk)) {
311e32ea7e7SCraig Gallek 		if (sk->sk_reuseport &&
312fe38d2a1SJosef Bacik 		    udp_reuseport_add_sock(sk, hslot)) {
313e32ea7e7SCraig Gallek 			inet_sk(sk)->inet_num = 0;
314e32ea7e7SCraig Gallek 			udp_sk(sk)->udp_port_hash = 0;
315e32ea7e7SCraig Gallek 			udp_sk(sk)->udp_portaddr_hash ^= snum;
316e32ea7e7SCraig Gallek 			goto fail_unlock;
317e32ea7e7SCraig Gallek 		}
318e32ea7e7SCraig Gallek 
319ca065d0cSEric Dumazet 		sk_add_node_rcu(sk, &hslot->head);
320fdcc8aa9SEric Dumazet 		hslot->count++;
321c29a0bc4SPavel Emelyanov 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
322512615b6SEric Dumazet 
323512615b6SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
324512615b6SEric Dumazet 		spin_lock(&hslot2->lock);
325d894ba18SCraig Gallek 		if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
326d894ba18SCraig Gallek 		    sk->sk_family == AF_INET6)
3271602f49bSDavid S. Miller 			hlist_add_tail_rcu(&udp_sk(sk)->udp_portaddr_node,
328d894ba18SCraig Gallek 					   &hslot2->head);
329d894ba18SCraig Gallek 		else
330ca065d0cSEric Dumazet 			hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
331512615b6SEric Dumazet 					   &hslot2->head);
332512615b6SEric Dumazet 		hslot2->count++;
333512615b6SEric Dumazet 		spin_unlock(&hslot2->lock);
3341da177e4SLinus Torvalds 	}
335ca065d0cSEric Dumazet 	sock_set_flag(sk, SOCK_RCU_FREE);
33625030a7fSGerrit Renker 	error = 0;
337645ca708SEric Dumazet fail_unlock:
338645ca708SEric Dumazet 	spin_unlock_bh(&hslot->lock);
3391da177e4SLinus Torvalds fail:
34025030a7fSGerrit Renker 	return error;
3411da177e4SLinus Torvalds }
342c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_get_port);
3431da177e4SLinus Torvalds 
3446ba5a3c5SPavel Emelyanov int udp_v4_get_port(struct sock *sk, unsigned short snum)
345db8dac20SDavid S. Miller {
34630fff923SEric Dumazet 	unsigned int hash2_nulladdr =
347f0b1e64cSMartin KaFai Lau 		ipv4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
34830fff923SEric Dumazet 	unsigned int hash2_partial =
349f0b1e64cSMartin KaFai Lau 		ipv4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
35030fff923SEric Dumazet 
351d4cada4aSEric Dumazet 	/* precompute partial secondary hash */
35230fff923SEric Dumazet 	udp_sk(sk)->udp_portaddr_hash = hash2_partial;
353fe38d2a1SJosef Bacik 	return udp_lib_get_port(sk, snum, hash2_nulladdr);
354db8dac20SDavid S. Miller }
355db8dac20SDavid S. Miller 
356d1e37288SSu, Xuemin static int compute_score(struct sock *sk, struct net *net,
357d1e37288SSu, Xuemin 			 __be32 saddr, __be16 sport,
358fb74c277SDavid Ahern 			 __be32 daddr, unsigned short hnum,
35973545373STim Beale 			 int dif, int sdif)
360645ca708SEric Dumazet {
36160c04aecSJoe Perches 	int score;
36260c04aecSJoe Perches 	struct inet_sock *inet;
3636da5b0f0SMike Manning 	bool dev_match;
364645ca708SEric Dumazet 
36560c04aecSJoe Perches 	if (!net_eq(sock_net(sk), net) ||
36660c04aecSJoe Perches 	    udp_sk(sk)->udp_port_hash != hnum ||
36760c04aecSJoe Perches 	    ipv6_only_sock(sk))
36860c04aecSJoe Perches 		return -1;
369645ca708SEric Dumazet 
3704cdeeee9SPeter Oskolkov 	if (sk->sk_rcv_saddr != daddr)
371645ca708SEric Dumazet 		return -1;
37260c04aecSJoe Perches 
3734cdeeee9SPeter Oskolkov 	score = (sk->sk_family == PF_INET) ? 2 : 1;
3744cdeeee9SPeter Oskolkov 
3754cdeeee9SPeter Oskolkov 	inet = inet_sk(sk);
376c720c7e8SEric Dumazet 	if (inet->inet_daddr) {
377c720c7e8SEric Dumazet 		if (inet->inet_daddr != saddr)
378645ca708SEric Dumazet 			return -1;
379ba418fa3STom Herbert 		score += 4;
380645ca708SEric Dumazet 	}
38160c04aecSJoe Perches 
382c720c7e8SEric Dumazet 	if (inet->inet_dport) {
383c720c7e8SEric Dumazet 		if (inet->inet_dport != sport)
384645ca708SEric Dumazet 			return -1;
385ba418fa3STom Herbert 		score += 4;
386645ca708SEric Dumazet 	}
38760c04aecSJoe Perches 
3886da5b0f0SMike Manning 	dev_match = udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if,
3896da5b0f0SMike Manning 					dif, sdif);
39069678bcdSPaolo Abeni 	if (!dev_match)
391645ca708SEric Dumazet 		return -1;
392ba418fa3STom Herbert 	score += 4;
393fb74c277SDavid Ahern 
3947170a977SEric Dumazet 	if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
39570da268bSEric Dumazet 		score++;
396645ca708SEric Dumazet 	return score;
397645ca708SEric Dumazet }
398645ca708SEric Dumazet 
3996eada011SEric Dumazet static u32 udp_ehashfn(const struct net *net, const __be32 laddr,
40065cd8033SHannes Frederic Sowa 		       const __u16 lport, const __be32 faddr,
40165cd8033SHannes Frederic Sowa 		       const __be16 fport)
40265cd8033SHannes Frederic Sowa {
4031bbdceefSHannes Frederic Sowa 	static u32 udp_ehash_secret __read_mostly;
4041bbdceefSHannes Frederic Sowa 
4051bbdceefSHannes Frederic Sowa 	net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret));
4061bbdceefSHannes Frederic Sowa 
40765cd8033SHannes Frederic Sowa 	return __inet_ehashfn(laddr, lport, faddr, fport,
4081bbdceefSHannes Frederic Sowa 			      udp_ehash_secret + net_hash_mix(net));
40965cd8033SHannes Frederic Sowa }
41065cd8033SHannes Frederic Sowa 
4117629c73aSJakub Sitnicki static inline struct sock *lookup_reuseport(struct net *net, struct sock *sk,
4127629c73aSJakub Sitnicki 					    struct sk_buff *skb,
4137629c73aSJakub Sitnicki 					    __be32 saddr, __be16 sport,
4147629c73aSJakub Sitnicki 					    __be32 daddr, unsigned short hnum)
4157629c73aSJakub Sitnicki {
4167629c73aSJakub Sitnicki 	struct sock *reuse_sk = NULL;
4177629c73aSJakub Sitnicki 	u32 hash;
4187629c73aSJakub Sitnicki 
4197629c73aSJakub Sitnicki 	if (sk->sk_reuseport && sk->sk_state != TCP_ESTABLISHED) {
4207629c73aSJakub Sitnicki 		hash = udp_ehashfn(net, daddr, hnum, saddr, sport);
4217629c73aSJakub Sitnicki 		reuse_sk = reuseport_select_sock(sk, hash, skb,
4227629c73aSJakub Sitnicki 						 sizeof(struct udphdr));
4237629c73aSJakub Sitnicki 		/* Fall back to scoring if group has connections */
4247629c73aSJakub Sitnicki 		if (reuseport_has_conns(sk, false))
4257629c73aSJakub Sitnicki 			return NULL;
4267629c73aSJakub Sitnicki 	}
4277629c73aSJakub Sitnicki 	return reuse_sk;
4287629c73aSJakub Sitnicki }
4297629c73aSJakub Sitnicki 
430d1e37288SSu, Xuemin /* called with rcu_read_lock() */
4315051ebd2SEric Dumazet static struct sock *udp4_lib_lookup2(struct net *net,
4325051ebd2SEric Dumazet 				     __be32 saddr, __be16 sport,
433fb74c277SDavid Ahern 				     __be32 daddr, unsigned int hnum,
43473545373STim Beale 				     int dif, int sdif,
435d1e37288SSu, Xuemin 				     struct udp_hslot *hslot2,
4361134158bSCraig Gallek 				     struct sk_buff *skb)
4375051ebd2SEric Dumazet {
4385051ebd2SEric Dumazet 	struct sock *sk, *result;
439e94a62f5SPaolo Abeni 	int score, badness;
4405051ebd2SEric Dumazet 
4415051ebd2SEric Dumazet 	result = NULL;
442ba418fa3STom Herbert 	badness = 0;
443ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
444d1e37288SSu, Xuemin 		score = compute_score(sk, net, saddr, sport,
44573545373STim Beale 				      daddr, hnum, dif, sdif);
4465051ebd2SEric Dumazet 		if (score > badness) {
4477629c73aSJakub Sitnicki 			result = lookup_reuseport(net, sk, skb,
4487629c73aSJakub Sitnicki 						  saddr, sport, daddr, hnum);
4497629c73aSJakub Sitnicki 			if (result)
450ca065d0cSEric Dumazet 				return result;
4517629c73aSJakub Sitnicki 
452ca065d0cSEric Dumazet 			badness = score;
453ca065d0cSEric Dumazet 			result = sk;
4545051ebd2SEric Dumazet 		}
4555051ebd2SEric Dumazet 	}
4565051ebd2SEric Dumazet 	return result;
4575051ebd2SEric Dumazet }
4585051ebd2SEric Dumazet 
459*72f7e944SJakub Sitnicki static inline struct sock *udp4_lookup_run_bpf(struct net *net,
460*72f7e944SJakub Sitnicki 					       struct udp_table *udptable,
461*72f7e944SJakub Sitnicki 					       struct sk_buff *skb,
462*72f7e944SJakub Sitnicki 					       __be32 saddr, __be16 sport,
463*72f7e944SJakub Sitnicki 					       __be32 daddr, u16 hnum)
464*72f7e944SJakub Sitnicki {
465*72f7e944SJakub Sitnicki 	struct sock *sk, *reuse_sk;
466*72f7e944SJakub Sitnicki 	bool no_reuseport;
467*72f7e944SJakub Sitnicki 
468*72f7e944SJakub Sitnicki 	if (udptable != &udp_table)
469*72f7e944SJakub Sitnicki 		return NULL; /* only UDP is supported */
470*72f7e944SJakub Sitnicki 
471*72f7e944SJakub Sitnicki 	no_reuseport = bpf_sk_lookup_run_v4(net, IPPROTO_UDP,
472*72f7e944SJakub Sitnicki 					    saddr, sport, daddr, hnum, &sk);
473*72f7e944SJakub Sitnicki 	if (no_reuseport || IS_ERR_OR_NULL(sk))
474*72f7e944SJakub Sitnicki 		return sk;
475*72f7e944SJakub Sitnicki 
476*72f7e944SJakub Sitnicki 	reuse_sk = lookup_reuseport(net, sk, skb, saddr, sport, daddr, hnum);
477*72f7e944SJakub Sitnicki 	if (reuse_sk)
478*72f7e944SJakub Sitnicki 		sk = reuse_sk;
479*72f7e944SJakub Sitnicki 	return sk;
480*72f7e944SJakub Sitnicki }
481*72f7e944SJakub Sitnicki 
482db8dac20SDavid S. Miller /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
483db8dac20SDavid S. Miller  * harder than this. -DaveM
484db8dac20SDavid S. Miller  */
485fce82338SPavel Emelyanov struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
486fb74c277SDavid Ahern 		__be16 sport, __be32 daddr, __be16 dport, int dif,
487fb74c277SDavid Ahern 		int sdif, struct udp_table *udptable, struct sk_buff *skb)
488db8dac20SDavid S. Miller {
489db8dac20SDavid S. Miller 	unsigned short hnum = ntohs(dport);
4904cdeeee9SPeter Oskolkov 	unsigned int hash2, slot2;
4914cdeeee9SPeter Oskolkov 	struct udp_hslot *hslot2;
492*72f7e944SJakub Sitnicki 	struct sock *result, *sk;
493db8dac20SDavid S. Miller 
494f0b1e64cSMartin KaFai Lau 	hash2 = ipv4_portaddr_hash(net, daddr, hnum);
4955051ebd2SEric Dumazet 	slot2 = hash2 & udptable->mask;
4965051ebd2SEric Dumazet 	hslot2 = &udptable->hash2[slot2];
4975051ebd2SEric Dumazet 
498*72f7e944SJakub Sitnicki 	/* Lookup connected or non-wildcard socket */
4995051ebd2SEric Dumazet 	result = udp4_lib_lookup2(net, saddr, sport,
500fb74c277SDavid Ahern 				  daddr, hnum, dif, sdif,
50173545373STim Beale 				  hslot2, skb);
502*72f7e944SJakub Sitnicki 	if (!IS_ERR_OR_NULL(result) && result->sk_state == TCP_ESTABLISHED)
503*72f7e944SJakub Sitnicki 		goto done;
504*72f7e944SJakub Sitnicki 
505*72f7e944SJakub Sitnicki 	/* Lookup redirect from BPF */
506*72f7e944SJakub Sitnicki 	if (static_branch_unlikely(&bpf_sk_lookup_enabled)) {
507*72f7e944SJakub Sitnicki 		sk = udp4_lookup_run_bpf(net, udptable, skb,
508*72f7e944SJakub Sitnicki 					 saddr, sport, daddr, hnum);
509*72f7e944SJakub Sitnicki 		if (sk) {
510*72f7e944SJakub Sitnicki 			result = sk;
511*72f7e944SJakub Sitnicki 			goto done;
512*72f7e944SJakub Sitnicki 		}
513*72f7e944SJakub Sitnicki 	}
514*72f7e944SJakub Sitnicki 
515*72f7e944SJakub Sitnicki 	/* Got non-wildcard socket or error on first lookup */
516*72f7e944SJakub Sitnicki 	if (result)
517*72f7e944SJakub Sitnicki 		goto done;
518*72f7e944SJakub Sitnicki 
519*72f7e944SJakub Sitnicki 	/* Lookup wildcard sockets */
520f0b1e64cSMartin KaFai Lau 	hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
5215051ebd2SEric Dumazet 	slot2 = hash2 & udptable->mask;
5225051ebd2SEric Dumazet 	hslot2 = &udptable->hash2[slot2];
5235051ebd2SEric Dumazet 
5241223c67cSJorge Boncompte [DTI2] 	result = udp4_lib_lookup2(net, saddr, sport,
5254cdeeee9SPeter Oskolkov 				  htonl(INADDR_ANY), hnum, dif, sdif,
52673545373STim Beale 				  hslot2, skb);
527*72f7e944SJakub Sitnicki done:
52888e235b8SEnrico Weigelt 	if (IS_ERR(result))
5298217ca65SMartin KaFai Lau 		return NULL;
5305051ebd2SEric Dumazet 	return result;
5315051ebd2SEric Dumazet }
532fce82338SPavel Emelyanov EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
533db8dac20SDavid S. Miller 
534607c4aafSKOVACS Krisztian static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
535607c4aafSKOVACS Krisztian 						 __be16 sport, __be16 dport,
536645ca708SEric Dumazet 						 struct udp_table *udptable)
537607c4aafSKOVACS Krisztian {
538607c4aafSKOVACS Krisztian 	const struct iphdr *iph = ip_hdr(skb);
539607c4aafSKOVACS Krisztian 
540ed7cbbceSAlexander Duyck 	return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
541607c4aafSKOVACS Krisztian 				 iph->daddr, dport, inet_iif(skb),
542fb74c277SDavid Ahern 				 inet_sdif(skb), udptable, skb);
543607c4aafSKOVACS Krisztian }
544607c4aafSKOVACS Krisztian 
54563058308STom Herbert struct sock *udp4_lib_lookup_skb(struct sk_buff *skb,
54663058308STom Herbert 				 __be16 sport, __be16 dport)
54763058308STom Herbert {
548257a525fSMartin KaFai Lau 	const struct iphdr *iph = ip_hdr(skb);
549257a525fSMartin KaFai Lau 
550257a525fSMartin KaFai Lau 	return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
551257a525fSMartin KaFai Lau 				 iph->daddr, dport, inet_iif(skb),
552257a525fSMartin KaFai Lau 				 inet_sdif(skb), &udp_table, NULL);
55363058308STom Herbert }
55463058308STom Herbert EXPORT_SYMBOL_GPL(udp4_lib_lookup_skb);
55563058308STom Herbert 
556ca065d0cSEric Dumazet /* Must be called under rcu_read_lock().
557ca065d0cSEric Dumazet  * Does increment socket refcount.
558ca065d0cSEric Dumazet  */
5596e86000cSArnd Bergmann #if IS_ENABLED(CONFIG_NF_TPROXY_IPV4) || IS_ENABLED(CONFIG_NF_SOCKET_IPV4)
560bcd41303SKOVACS Krisztian struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
561bcd41303SKOVACS Krisztian 			     __be32 daddr, __be16 dport, int dif)
562bcd41303SKOVACS Krisztian {
563ca065d0cSEric Dumazet 	struct sock *sk;
564ca065d0cSEric Dumazet 
565ca065d0cSEric Dumazet 	sk = __udp4_lib_lookup(net, saddr, sport, daddr, dport,
566fb74c277SDavid Ahern 			       dif, 0, &udp_table, NULL);
56741c6d650SReshetova, Elena 	if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
568ca065d0cSEric Dumazet 		sk = NULL;
569ca065d0cSEric Dumazet 	return sk;
570bcd41303SKOVACS Krisztian }
571bcd41303SKOVACS Krisztian EXPORT_SYMBOL_GPL(udp4_lib_lookup);
572ca065d0cSEric Dumazet #endif
573bcd41303SKOVACS Krisztian 
574421b3885SShawn Bohrer static inline bool __udp_is_mcast_sock(struct net *net, struct sock *sk,
575421b3885SShawn Bohrer 				       __be16 loc_port, __be32 loc_addr,
576421b3885SShawn Bohrer 				       __be16 rmt_port, __be32 rmt_addr,
577fb74c277SDavid Ahern 				       int dif, int sdif, unsigned short hnum)
578421b3885SShawn Bohrer {
579421b3885SShawn Bohrer 	struct inet_sock *inet = inet_sk(sk);
580421b3885SShawn Bohrer 
581421b3885SShawn Bohrer 	if (!net_eq(sock_net(sk), net) ||
582421b3885SShawn Bohrer 	    udp_sk(sk)->udp_port_hash != hnum ||
583421b3885SShawn Bohrer 	    (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
584421b3885SShawn Bohrer 	    (inet->inet_dport != rmt_port && inet->inet_dport) ||
585421b3885SShawn Bohrer 	    (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) ||
586421b3885SShawn Bohrer 	    ipv6_only_sock(sk) ||
58782ba25c6STim Beale 	    !udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif))
588421b3885SShawn Bohrer 		return false;
58960d9b031SDavid Ahern 	if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif, sdif))
590421b3885SShawn Bohrer 		return false;
591421b3885SShawn Bohrer 	return true;
592421b3885SShawn Bohrer }
593421b3885SShawn Bohrer 
594a36e185eSStefano Brivio DEFINE_STATIC_KEY_FALSE(udp_encap_needed_key);
595a36e185eSStefano Brivio void udp_encap_enable(void)
596a36e185eSStefano Brivio {
5979c480601SPaolo Abeni 	static_branch_inc(&udp_encap_needed_key);
598a36e185eSStefano Brivio }
599a36e185eSStefano Brivio EXPORT_SYMBOL(udp_encap_enable);
600a36e185eSStefano Brivio 
601e7cc0824SStefano Brivio /* Handler for tunnels with arbitrary destination ports: no socket lookup, go
602e7cc0824SStefano Brivio  * through error handlers in encapsulations looking for a match.
603e7cc0824SStefano Brivio  */
604e7cc0824SStefano Brivio static int __udp4_lib_err_encap_no_sk(struct sk_buff *skb, u32 info)
605e7cc0824SStefano Brivio {
606e7cc0824SStefano Brivio 	int i;
607e7cc0824SStefano Brivio 
608e7cc0824SStefano Brivio 	for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) {
609e7cc0824SStefano Brivio 		int (*handler)(struct sk_buff *skb, u32 info);
61092b95364SPaolo Abeni 		const struct ip_tunnel_encap_ops *encap;
611e7cc0824SStefano Brivio 
61292b95364SPaolo Abeni 		encap = rcu_dereference(iptun_encaps[i]);
61392b95364SPaolo Abeni 		if (!encap)
614e7cc0824SStefano Brivio 			continue;
61592b95364SPaolo Abeni 		handler = encap->err_handler;
616e7cc0824SStefano Brivio 		if (handler && !handler(skb, info))
617e7cc0824SStefano Brivio 			return 0;
618e7cc0824SStefano Brivio 	}
619e7cc0824SStefano Brivio 
620e7cc0824SStefano Brivio 	return -ENOENT;
621e7cc0824SStefano Brivio }
622e7cc0824SStefano Brivio 
623a36e185eSStefano Brivio /* Try to match ICMP errors to UDP tunnels by looking up a socket without
624a36e185eSStefano Brivio  * reversing source and destination port: this will match tunnels that force the
625a36e185eSStefano Brivio  * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that
626a36e185eSStefano Brivio  * lwtunnels might actually break this assumption by being configured with
627a36e185eSStefano Brivio  * different destination ports on endpoints, in this case we won't be able to
628a36e185eSStefano Brivio  * trace ICMP messages back to them.
629a36e185eSStefano Brivio  *
630e7cc0824SStefano Brivio  * If this doesn't match any socket, probe tunnels with arbitrary destination
631e7cc0824SStefano Brivio  * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port
632e7cc0824SStefano Brivio  * we've sent packets to won't necessarily match the local destination port.
633e7cc0824SStefano Brivio  *
634a36e185eSStefano Brivio  * Then ask the tunnel implementation to match the error against a valid
635a36e185eSStefano Brivio  * association.
636a36e185eSStefano Brivio  *
637e7cc0824SStefano Brivio  * Return an error if we can't find a match, the socket if we need further
638e7cc0824SStefano Brivio  * processing, zero otherwise.
639a36e185eSStefano Brivio  */
640a36e185eSStefano Brivio static struct sock *__udp4_lib_err_encap(struct net *net,
641a36e185eSStefano Brivio 					 const struct iphdr *iph,
642a36e185eSStefano Brivio 					 struct udphdr *uh,
643a36e185eSStefano Brivio 					 struct udp_table *udptable,
644e7cc0824SStefano Brivio 					 struct sk_buff *skb, u32 info)
645a36e185eSStefano Brivio {
646a36e185eSStefano Brivio 	int network_offset, transport_offset;
647a36e185eSStefano Brivio 	struct sock *sk;
648a36e185eSStefano Brivio 
649a36e185eSStefano Brivio 	network_offset = skb_network_offset(skb);
650a36e185eSStefano Brivio 	transport_offset = skb_transport_offset(skb);
651a36e185eSStefano Brivio 
652a36e185eSStefano Brivio 	/* Network header needs to point to the outer IPv4 header inside ICMP */
653a36e185eSStefano Brivio 	skb_reset_network_header(skb);
654a36e185eSStefano Brivio 
655a36e185eSStefano Brivio 	/* Transport header needs to point to the UDP header */
656a36e185eSStefano Brivio 	skb_set_transport_header(skb, iph->ihl << 2);
657a36e185eSStefano Brivio 
658e7cc0824SStefano Brivio 	sk = __udp4_lib_lookup(net, iph->daddr, uh->source,
659e7cc0824SStefano Brivio 			       iph->saddr, uh->dest, skb->dev->ifindex, 0,
660e7cc0824SStefano Brivio 			       udptable, NULL);
661e7cc0824SStefano Brivio 	if (sk) {
662e7cc0824SStefano Brivio 		int (*lookup)(struct sock *sk, struct sk_buff *skb);
663e7cc0824SStefano Brivio 		struct udp_sock *up = udp_sk(sk);
664e7cc0824SStefano Brivio 
665a36e185eSStefano Brivio 		lookup = READ_ONCE(up->encap_err_lookup);
666a36e185eSStefano Brivio 		if (!lookup || lookup(sk, skb))
667a36e185eSStefano Brivio 			sk = NULL;
668e7cc0824SStefano Brivio 	}
669e7cc0824SStefano Brivio 
670e7cc0824SStefano Brivio 	if (!sk)
671e7cc0824SStefano Brivio 		sk = ERR_PTR(__udp4_lib_err_encap_no_sk(skb, info));
672a36e185eSStefano Brivio 
673a36e185eSStefano Brivio 	skb_set_transport_header(skb, transport_offset);
674a36e185eSStefano Brivio 	skb_set_network_header(skb, network_offset);
675a36e185eSStefano Brivio 
676a36e185eSStefano Brivio 	return sk;
677a36e185eSStefano Brivio }
678a36e185eSStefano Brivio 
679db8dac20SDavid S. Miller /*
680db8dac20SDavid S. Miller  * This routine is called by the ICMP module when it gets some
681db8dac20SDavid S. Miller  * sort of error condition.  If err < 0 then the socket should
682db8dac20SDavid S. Miller  * be closed and the error returned to the user.  If err > 0
683db8dac20SDavid S. Miller  * it's just the icmp type << 8 | icmp code.
684db8dac20SDavid S. Miller  * Header points to the ip header of the error packet. We move
685db8dac20SDavid S. Miller  * on past this. Then (as it used to claim before adjustment)
686db8dac20SDavid S. Miller  * header points to the first 8 bytes of the udp header.  We need
687db8dac20SDavid S. Miller  * to find the appropriate port.
688db8dac20SDavid S. Miller  */
689db8dac20SDavid S. Miller 
69032bbd879SStefano Brivio int __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
691db8dac20SDavid S. Miller {
692db8dac20SDavid S. Miller 	struct inet_sock *inet;
693b71d1d42SEric Dumazet 	const struct iphdr *iph = (const struct iphdr *)skb->data;
694db8dac20SDavid S. Miller 	struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
695db8dac20SDavid S. Miller 	const int type = icmp_hdr(skb)->type;
696db8dac20SDavid S. Miller 	const int code = icmp_hdr(skb)->code;
697a36e185eSStefano Brivio 	bool tunnel = false;
698db8dac20SDavid S. Miller 	struct sock *sk;
699db8dac20SDavid S. Miller 	int harderr;
700db8dac20SDavid S. Miller 	int err;
701fd54d716SPavel Emelyanov 	struct net *net = dev_net(skb->dev);
702db8dac20SDavid S. Miller 
703fd54d716SPavel Emelyanov 	sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
704f64bf6b8SMike Manning 			       iph->saddr, uh->source, skb->dev->ifindex,
705f64bf6b8SMike Manning 			       inet_sdif(skb), udptable, NULL);
70651456b29SIan Morris 	if (!sk) {
707a36e185eSStefano Brivio 		/* No socket for error: try tunnels before discarding */
708e7cc0824SStefano Brivio 		sk = ERR_PTR(-ENOENT);
709e7cc0824SStefano Brivio 		if (static_branch_unlikely(&udp_encap_needed_key)) {
710e7cc0824SStefano Brivio 			sk = __udp4_lib_err_encap(net, iph, uh, udptable, skb,
711e7cc0824SStefano Brivio 						  info);
712e7cc0824SStefano Brivio 			if (!sk)
713e7cc0824SStefano Brivio 				return 0;
714a36e185eSStefano Brivio 		}
715e7cc0824SStefano Brivio 
716e7cc0824SStefano Brivio 		if (IS_ERR(sk)) {
717e7cc0824SStefano Brivio 			__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
718e7cc0824SStefano Brivio 			return PTR_ERR(sk);
719e7cc0824SStefano Brivio 		}
720e7cc0824SStefano Brivio 
721a36e185eSStefano Brivio 		tunnel = true;
722db8dac20SDavid S. Miller 	}
723db8dac20SDavid S. Miller 
724db8dac20SDavid S. Miller 	err = 0;
725db8dac20SDavid S. Miller 	harderr = 0;
726db8dac20SDavid S. Miller 	inet = inet_sk(sk);
727db8dac20SDavid S. Miller 
728db8dac20SDavid S. Miller 	switch (type) {
729db8dac20SDavid S. Miller 	default:
730db8dac20SDavid S. Miller 	case ICMP_TIME_EXCEEDED:
731db8dac20SDavid S. Miller 		err = EHOSTUNREACH;
732db8dac20SDavid S. Miller 		break;
733db8dac20SDavid S. Miller 	case ICMP_SOURCE_QUENCH:
734db8dac20SDavid S. Miller 		goto out;
735db8dac20SDavid S. Miller 	case ICMP_PARAMETERPROB:
736db8dac20SDavid S. Miller 		err = EPROTO;
737db8dac20SDavid S. Miller 		harderr = 1;
738db8dac20SDavid S. Miller 		break;
739db8dac20SDavid S. Miller 	case ICMP_DEST_UNREACH:
740db8dac20SDavid S. Miller 		if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
74136393395SDavid S. Miller 			ipv4_sk_update_pmtu(skb, sk, info);
742db8dac20SDavid S. Miller 			if (inet->pmtudisc != IP_PMTUDISC_DONT) {
743db8dac20SDavid S. Miller 				err = EMSGSIZE;
744db8dac20SDavid S. Miller 				harderr = 1;
745db8dac20SDavid S. Miller 				break;
746db8dac20SDavid S. Miller 			}
747db8dac20SDavid S. Miller 			goto out;
748db8dac20SDavid S. Miller 		}
749db8dac20SDavid S. Miller 		err = EHOSTUNREACH;
750db8dac20SDavid S. Miller 		if (code <= NR_ICMP_UNREACH) {
751db8dac20SDavid S. Miller 			harderr = icmp_err_convert[code].fatal;
752db8dac20SDavid S. Miller 			err = icmp_err_convert[code].errno;
753db8dac20SDavid S. Miller 		}
754db8dac20SDavid S. Miller 		break;
75555be7a9cSDavid S. Miller 	case ICMP_REDIRECT:
75655be7a9cSDavid S. Miller 		ipv4_sk_redirect(skb, sk);
7571a462d18SDuan Jiong 		goto out;
758db8dac20SDavid S. Miller 	}
759db8dac20SDavid S. Miller 
760db8dac20SDavid S. Miller 	/*
761db8dac20SDavid S. Miller 	 *      RFC1122: OK.  Passes ICMP errors back to application, as per
762db8dac20SDavid S. Miller 	 *	4.1.3.3.
763db8dac20SDavid S. Miller 	 */
764a36e185eSStefano Brivio 	if (tunnel) {
765a36e185eSStefano Brivio 		/* ...not for tunnels though: we don't have a sending socket */
766a36e185eSStefano Brivio 		goto out;
767a36e185eSStefano Brivio 	}
768db8dac20SDavid S. Miller 	if (!inet->recverr) {
769db8dac20SDavid S. Miller 		if (!harderr || sk->sk_state != TCP_ESTABLISHED)
770db8dac20SDavid S. Miller 			goto out;
771b1faf566SEric Dumazet 	} else
772db8dac20SDavid S. Miller 		ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
773b1faf566SEric Dumazet 
774db8dac20SDavid S. Miller 	sk->sk_err = err;
775db8dac20SDavid S. Miller 	sk->sk_error_report(sk);
776db8dac20SDavid S. Miller out:
77732bbd879SStefano Brivio 	return 0;
778db8dac20SDavid S. Miller }
779db8dac20SDavid S. Miller 
78032bbd879SStefano Brivio int udp_err(struct sk_buff *skb, u32 info)
781db8dac20SDavid S. Miller {
78232bbd879SStefano Brivio 	return __udp4_lib_err(skb, info, &udp_table);
783db8dac20SDavid S. Miller }
784db8dac20SDavid S. Miller 
785db8dac20SDavid S. Miller /*
786db8dac20SDavid S. Miller  * Throw away all pending data and cancel the corking. Socket is locked.
787db8dac20SDavid S. Miller  */
78836d926b9SDenis V. Lunev void udp_flush_pending_frames(struct sock *sk)
789db8dac20SDavid S. Miller {
790db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
791db8dac20SDavid S. Miller 
792db8dac20SDavid S. Miller 	if (up->pending) {
793db8dac20SDavid S. Miller 		up->len = 0;
794db8dac20SDavid S. Miller 		up->pending = 0;
795db8dac20SDavid S. Miller 		ip_flush_pending_frames(sk);
796db8dac20SDavid S. Miller 	}
797db8dac20SDavid S. Miller }
79836d926b9SDenis V. Lunev EXPORT_SYMBOL(udp_flush_pending_frames);
799db8dac20SDavid S. Miller 
800db8dac20SDavid S. Miller /**
801f6b9664fSHerbert Xu  * 	udp4_hwcsum  -  handle outgoing HW checksumming
802db8dac20SDavid S. Miller  * 	@skb: 	sk_buff containing the filled-in UDP header
803db8dac20SDavid S. Miller  * 	        (checksum field must be zeroed out)
804f6b9664fSHerbert Xu  *	@src:	source IP address
805f6b9664fSHerbert Xu  *	@dst:	destination IP address
806db8dac20SDavid S. Miller  */
807c26bf4a5SThomas Graf void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
808db8dac20SDavid S. Miller {
809db8dac20SDavid S. Miller 	struct udphdr *uh = udp_hdr(skb);
810f6b9664fSHerbert Xu 	int offset = skb_transport_offset(skb);
811f6b9664fSHerbert Xu 	int len = skb->len - offset;
812f6b9664fSHerbert Xu 	int hlen = len;
813db8dac20SDavid S. Miller 	__wsum csum = 0;
814db8dac20SDavid S. Miller 
815ebbe495fSWANG Cong 	if (!skb_has_frag_list(skb)) {
816db8dac20SDavid S. Miller 		/*
817db8dac20SDavid S. Miller 		 * Only one fragment on the socket.
818db8dac20SDavid S. Miller 		 */
819db8dac20SDavid S. Miller 		skb->csum_start = skb_transport_header(skb) - skb->head;
820db8dac20SDavid S. Miller 		skb->csum_offset = offsetof(struct udphdr, check);
821f6b9664fSHerbert Xu 		uh->check = ~csum_tcpudp_magic(src, dst, len,
822f6b9664fSHerbert Xu 					       IPPROTO_UDP, 0);
823db8dac20SDavid S. Miller 	} else {
824ebbe495fSWANG Cong 		struct sk_buff *frags;
825ebbe495fSWANG Cong 
826db8dac20SDavid S. Miller 		/*
827db8dac20SDavid S. Miller 		 * HW-checksum won't work as there are two or more
828db8dac20SDavid S. Miller 		 * fragments on the socket so that all csums of sk_buffs
829db8dac20SDavid S. Miller 		 * should be together
830db8dac20SDavid S. Miller 		 */
831ebbe495fSWANG Cong 		skb_walk_frags(skb, frags) {
832f6b9664fSHerbert Xu 			csum = csum_add(csum, frags->csum);
833f6b9664fSHerbert Xu 			hlen -= frags->len;
834ebbe495fSWANG Cong 		}
835db8dac20SDavid S. Miller 
836f6b9664fSHerbert Xu 		csum = skb_checksum(skb, offset, hlen, csum);
837db8dac20SDavid S. Miller 		skb->ip_summed = CHECKSUM_NONE;
838db8dac20SDavid S. Miller 
839db8dac20SDavid S. Miller 		uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
840db8dac20SDavid S. Miller 		if (uh->check == 0)
841db8dac20SDavid S. Miller 			uh->check = CSUM_MANGLED_0;
842db8dac20SDavid S. Miller 	}
843db8dac20SDavid S. Miller }
844c26bf4a5SThomas Graf EXPORT_SYMBOL_GPL(udp4_hwcsum);
845db8dac20SDavid S. Miller 
846af5fcba7STom Herbert /* Function to set UDP checksum for an IPv4 UDP packet. This is intended
847af5fcba7STom Herbert  * for the simple case like when setting the checksum for a UDP tunnel.
848af5fcba7STom Herbert  */
849af5fcba7STom Herbert void udp_set_csum(bool nocheck, struct sk_buff *skb,
850af5fcba7STom Herbert 		  __be32 saddr, __be32 daddr, int len)
851af5fcba7STom Herbert {
852af5fcba7STom Herbert 	struct udphdr *uh = udp_hdr(skb);
853af5fcba7STom Herbert 
854179bc67fSEdward Cree 	if (nocheck) {
855af5fcba7STom Herbert 		uh->check = 0;
856179bc67fSEdward Cree 	} else if (skb_is_gso(skb)) {
857af5fcba7STom Herbert 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
858179bc67fSEdward Cree 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) {
859179bc67fSEdward Cree 		uh->check = 0;
860179bc67fSEdward Cree 		uh->check = udp_v4_check(len, saddr, daddr, lco_csum(skb));
861179bc67fSEdward Cree 		if (uh->check == 0)
862179bc67fSEdward Cree 			uh->check = CSUM_MANGLED_0;
863d75f1306SEdward Cree 	} else {
864af5fcba7STom Herbert 		skb->ip_summed = CHECKSUM_PARTIAL;
865af5fcba7STom Herbert 		skb->csum_start = skb_transport_header(skb) - skb->head;
866af5fcba7STom Herbert 		skb->csum_offset = offsetof(struct udphdr, check);
867af5fcba7STom Herbert 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
868af5fcba7STom Herbert 	}
869af5fcba7STom Herbert }
870af5fcba7STom Herbert EXPORT_SYMBOL(udp_set_csum);
871af5fcba7STom Herbert 
872bec1f6f6SWillem de Bruijn static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4,
873bec1f6f6SWillem de Bruijn 			struct inet_cork *cork)
874f6b9664fSHerbert Xu {
875f6b9664fSHerbert Xu 	struct sock *sk = skb->sk;
876f6b9664fSHerbert Xu 	struct inet_sock *inet = inet_sk(sk);
877f6b9664fSHerbert Xu 	struct udphdr *uh;
878f6b9664fSHerbert Xu 	int err = 0;
879f6b9664fSHerbert Xu 	int is_udplite = IS_UDPLITE(sk);
880f6b9664fSHerbert Xu 	int offset = skb_transport_offset(skb);
881f6b9664fSHerbert Xu 	int len = skb->len - offset;
8824094871dSJosh Hunt 	int datalen = len - sizeof(*uh);
883f6b9664fSHerbert Xu 	__wsum csum = 0;
884f6b9664fSHerbert Xu 
885f6b9664fSHerbert Xu 	/*
886f6b9664fSHerbert Xu 	 * Create a UDP header
887f6b9664fSHerbert Xu 	 */
888f6b9664fSHerbert Xu 	uh = udp_hdr(skb);
889f6b9664fSHerbert Xu 	uh->source = inet->inet_sport;
89079ab0531SDavid S. Miller 	uh->dest = fl4->fl4_dport;
891f6b9664fSHerbert Xu 	uh->len = htons(len);
892f6b9664fSHerbert Xu 	uh->check = 0;
893f6b9664fSHerbert Xu 
894bec1f6f6SWillem de Bruijn 	if (cork->gso_size) {
895bec1f6f6SWillem de Bruijn 		const int hlen = skb_network_header_len(skb) +
896bec1f6f6SWillem de Bruijn 				 sizeof(struct udphdr);
897bec1f6f6SWillem de Bruijn 
8980f149c9fSWillem de Bruijn 		if (hlen + cork->gso_size > cork->fragsize) {
8990f149c9fSWillem de Bruijn 			kfree_skb(skb);
900bec1f6f6SWillem de Bruijn 			return -EINVAL;
9010f149c9fSWillem de Bruijn 		}
9020f149c9fSWillem de Bruijn 		if (skb->len > cork->gso_size * UDP_MAX_SEGMENTS) {
9030f149c9fSWillem de Bruijn 			kfree_skb(skb);
904bec1f6f6SWillem de Bruijn 			return -EINVAL;
9050f149c9fSWillem de Bruijn 		}
9060f149c9fSWillem de Bruijn 		if (sk->sk_no_check_tx) {
9070f149c9fSWillem de Bruijn 			kfree_skb(skb);
908a8c744a8SWillem de Bruijn 			return -EINVAL;
9090f149c9fSWillem de Bruijn 		}
910ff06342cSWillem de Bruijn 		if (skb->ip_summed != CHECKSUM_PARTIAL || is_udplite ||
9110f149c9fSWillem de Bruijn 		    dst_xfrm(skb_dst(skb))) {
9120f149c9fSWillem de Bruijn 			kfree_skb(skb);
913bec1f6f6SWillem de Bruijn 			return -EIO;
9140f149c9fSWillem de Bruijn 		}
915bec1f6f6SWillem de Bruijn 
9164094871dSJosh Hunt 		if (datalen > cork->gso_size) {
917bec1f6f6SWillem de Bruijn 			skb_shinfo(skb)->gso_size = cork->gso_size;
918bec1f6f6SWillem de Bruijn 			skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4;
9194094871dSJosh Hunt 			skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(datalen,
920dfec0ee2SAlexander Duyck 								 cork->gso_size);
9214094871dSJosh Hunt 		}
922a8c744a8SWillem de Bruijn 		goto csum_partial;
923bec1f6f6SWillem de Bruijn 	}
924bec1f6f6SWillem de Bruijn 
925f6b9664fSHerbert Xu 	if (is_udplite)  				 /*     UDP-Lite      */
926f6b9664fSHerbert Xu 		csum = udplite_csum(skb);
927f6b9664fSHerbert Xu 
928ab2fb7e3SWillem de Bruijn 	else if (sk->sk_no_check_tx) {			 /* UDP csum off */
929f6b9664fSHerbert Xu 
930f6b9664fSHerbert Xu 		skb->ip_summed = CHECKSUM_NONE;
931f6b9664fSHerbert Xu 		goto send;
932f6b9664fSHerbert Xu 
933f6b9664fSHerbert Xu 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
934a8c744a8SWillem de Bruijn csum_partial:
935f6b9664fSHerbert Xu 
93679ab0531SDavid S. Miller 		udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
937f6b9664fSHerbert Xu 		goto send;
938f6b9664fSHerbert Xu 
939f6b9664fSHerbert Xu 	} else
940f6b9664fSHerbert Xu 		csum = udp_csum(skb);
941f6b9664fSHerbert Xu 
942f6b9664fSHerbert Xu 	/* add protocol-dependent pseudo-header */
94379ab0531SDavid S. Miller 	uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
944f6b9664fSHerbert Xu 				      sk->sk_protocol, csum);
945f6b9664fSHerbert Xu 	if (uh->check == 0)
946f6b9664fSHerbert Xu 		uh->check = CSUM_MANGLED_0;
947f6b9664fSHerbert Xu 
948f6b9664fSHerbert Xu send:
949b5ec8eeaSEric Dumazet 	err = ip_send_skb(sock_net(sk), skb);
950f6b9664fSHerbert Xu 	if (err) {
951f6b9664fSHerbert Xu 		if (err == -ENOBUFS && !inet->recverr) {
9526aef70a8SEric Dumazet 			UDP_INC_STATS(sock_net(sk),
953f6b9664fSHerbert Xu 				      UDP_MIB_SNDBUFERRORS, is_udplite);
954f6b9664fSHerbert Xu 			err = 0;
955f6b9664fSHerbert Xu 		}
956f6b9664fSHerbert Xu 	} else
9576aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
958f6b9664fSHerbert Xu 			      UDP_MIB_OUTDATAGRAMS, is_udplite);
959f6b9664fSHerbert Xu 	return err;
960f6b9664fSHerbert Xu }
961f6b9664fSHerbert Xu 
962db8dac20SDavid S. Miller /*
963db8dac20SDavid S. Miller  * Push out all pending data as one UDP datagram. Socket is locked.
964db8dac20SDavid S. Miller  */
9658822b64aSHannes Frederic Sowa int udp_push_pending_frames(struct sock *sk)
966db8dac20SDavid S. Miller {
967db8dac20SDavid S. Miller 	struct udp_sock  *up = udp_sk(sk);
968db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
969b6f21b26SDavid S. Miller 	struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
970db8dac20SDavid S. Miller 	struct sk_buff *skb;
971db8dac20SDavid S. Miller 	int err = 0;
972db8dac20SDavid S. Miller 
97377968b78SDavid S. Miller 	skb = ip_finish_skb(sk, fl4);
974f6b9664fSHerbert Xu 	if (!skb)
975db8dac20SDavid S. Miller 		goto out;
976db8dac20SDavid S. Miller 
977bec1f6f6SWillem de Bruijn 	err = udp_send_skb(skb, fl4, &inet->cork.base);
978db8dac20SDavid S. Miller 
979db8dac20SDavid S. Miller out:
980db8dac20SDavid S. Miller 	up->len = 0;
981db8dac20SDavid S. Miller 	up->pending = 0;
982db8dac20SDavid S. Miller 	return err;
983db8dac20SDavid S. Miller }
9848822b64aSHannes Frederic Sowa EXPORT_SYMBOL(udp_push_pending_frames);
985db8dac20SDavid S. Miller 
9862e8de857SWillem de Bruijn static int __udp_cmsg_send(struct cmsghdr *cmsg, u16 *gso_size)
9872e8de857SWillem de Bruijn {
9882e8de857SWillem de Bruijn 	switch (cmsg->cmsg_type) {
9892e8de857SWillem de Bruijn 	case UDP_SEGMENT:
9902e8de857SWillem de Bruijn 		if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u16)))
9912e8de857SWillem de Bruijn 			return -EINVAL;
9922e8de857SWillem de Bruijn 		*gso_size = *(__u16 *)CMSG_DATA(cmsg);
9932e8de857SWillem de Bruijn 		return 0;
9942e8de857SWillem de Bruijn 	default:
9952e8de857SWillem de Bruijn 		return -EINVAL;
9962e8de857SWillem de Bruijn 	}
9972e8de857SWillem de Bruijn }
9982e8de857SWillem de Bruijn 
9992e8de857SWillem de Bruijn int udp_cmsg_send(struct sock *sk, struct msghdr *msg, u16 *gso_size)
10002e8de857SWillem de Bruijn {
10012e8de857SWillem de Bruijn 	struct cmsghdr *cmsg;
10022e8de857SWillem de Bruijn 	bool need_ip = false;
10032e8de857SWillem de Bruijn 	int err;
10042e8de857SWillem de Bruijn 
10052e8de857SWillem de Bruijn 	for_each_cmsghdr(cmsg, msg) {
10062e8de857SWillem de Bruijn 		if (!CMSG_OK(msg, cmsg))
10072e8de857SWillem de Bruijn 			return -EINVAL;
10082e8de857SWillem de Bruijn 
10092e8de857SWillem de Bruijn 		if (cmsg->cmsg_level != SOL_UDP) {
10102e8de857SWillem de Bruijn 			need_ip = true;
10112e8de857SWillem de Bruijn 			continue;
10122e8de857SWillem de Bruijn 		}
10132e8de857SWillem de Bruijn 
10142e8de857SWillem de Bruijn 		err = __udp_cmsg_send(cmsg, gso_size);
10152e8de857SWillem de Bruijn 		if (err)
10162e8de857SWillem de Bruijn 			return err;
10172e8de857SWillem de Bruijn 	}
10182e8de857SWillem de Bruijn 
10192e8de857SWillem de Bruijn 	return need_ip;
10202e8de857SWillem de Bruijn }
10212e8de857SWillem de Bruijn EXPORT_SYMBOL_GPL(udp_cmsg_send);
10222e8de857SWillem de Bruijn 
10231b784140SYing Xue int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1024db8dac20SDavid S. Miller {
1025db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1026db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
10271cedee13SAndrey Ignatov 	DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
1028e474995fSDavid S. Miller 	struct flowi4 fl4_stack;
1029b6f21b26SDavid S. Miller 	struct flowi4 *fl4;
1030db8dac20SDavid S. Miller 	int ulen = len;
1031db8dac20SDavid S. Miller 	struct ipcm_cookie ipc;
1032db8dac20SDavid S. Miller 	struct rtable *rt = NULL;
1033db8dac20SDavid S. Miller 	int free = 0;
1034db8dac20SDavid S. Miller 	int connected = 0;
1035db8dac20SDavid S. Miller 	__be32 daddr, faddr, saddr;
1036db8dac20SDavid S. Miller 	__be16 dport;
1037db8dac20SDavid S. Miller 	u8  tos;
1038db8dac20SDavid S. Miller 	int err, is_udplite = IS_UDPLITE(sk);
1039db8dac20SDavid S. Miller 	int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
1040db8dac20SDavid S. Miller 	int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
1041903ab86dSHerbert Xu 	struct sk_buff *skb;
1042f6d8bd05SEric Dumazet 	struct ip_options_data opt_copy;
1043db8dac20SDavid S. Miller 
1044db8dac20SDavid S. Miller 	if (len > 0xFFFF)
1045db8dac20SDavid S. Miller 		return -EMSGSIZE;
1046db8dac20SDavid S. Miller 
1047db8dac20SDavid S. Miller 	/*
1048db8dac20SDavid S. Miller 	 *	Check the flags.
1049db8dac20SDavid S. Miller 	 */
1050db8dac20SDavid S. Miller 
1051db8dac20SDavid S. Miller 	if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
1052db8dac20SDavid S. Miller 		return -EOPNOTSUPP;
1053db8dac20SDavid S. Miller 
1054903ab86dSHerbert Xu 	getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
1055903ab86dSHerbert Xu 
1056f5fca608SDavid S. Miller 	fl4 = &inet->cork.fl.u.ip4;
1057db8dac20SDavid S. Miller 	if (up->pending) {
1058db8dac20SDavid S. Miller 		/*
1059db8dac20SDavid S. Miller 		 * There are pending frames.
1060db8dac20SDavid S. Miller 		 * The socket lock must be held while it's corked.
1061db8dac20SDavid S. Miller 		 */
1062db8dac20SDavid S. Miller 		lock_sock(sk);
1063db8dac20SDavid S. Miller 		if (likely(up->pending)) {
1064db8dac20SDavid S. Miller 			if (unlikely(up->pending != AF_INET)) {
1065db8dac20SDavid S. Miller 				release_sock(sk);
1066db8dac20SDavid S. Miller 				return -EINVAL;
1067db8dac20SDavid S. Miller 			}
1068db8dac20SDavid S. Miller 			goto do_append_data;
1069db8dac20SDavid S. Miller 		}
1070db8dac20SDavid S. Miller 		release_sock(sk);
1071db8dac20SDavid S. Miller 	}
1072db8dac20SDavid S. Miller 	ulen += sizeof(struct udphdr);
1073db8dac20SDavid S. Miller 
1074db8dac20SDavid S. Miller 	/*
1075db8dac20SDavid S. Miller 	 *	Get and verify the address.
1076db8dac20SDavid S. Miller 	 */
10771cedee13SAndrey Ignatov 	if (usin) {
1078db8dac20SDavid S. Miller 		if (msg->msg_namelen < sizeof(*usin))
1079db8dac20SDavid S. Miller 			return -EINVAL;
1080db8dac20SDavid S. Miller 		if (usin->sin_family != AF_INET) {
1081db8dac20SDavid S. Miller 			if (usin->sin_family != AF_UNSPEC)
1082db8dac20SDavid S. Miller 				return -EAFNOSUPPORT;
1083db8dac20SDavid S. Miller 		}
1084db8dac20SDavid S. Miller 
1085db8dac20SDavid S. Miller 		daddr = usin->sin_addr.s_addr;
1086db8dac20SDavid S. Miller 		dport = usin->sin_port;
1087db8dac20SDavid S. Miller 		if (dport == 0)
1088db8dac20SDavid S. Miller 			return -EINVAL;
1089db8dac20SDavid S. Miller 	} else {
1090db8dac20SDavid S. Miller 		if (sk->sk_state != TCP_ESTABLISHED)
1091db8dac20SDavid S. Miller 			return -EDESTADDRREQ;
1092c720c7e8SEric Dumazet 		daddr = inet->inet_daddr;
1093c720c7e8SEric Dumazet 		dport = inet->inet_dport;
1094db8dac20SDavid S. Miller 		/* Open fast path for connected socket.
1095db8dac20SDavid S. Miller 		   Route will not be used, if at least one option is set.
1096db8dac20SDavid S. Miller 		 */
1097db8dac20SDavid S. Miller 		connected = 1;
1098db8dac20SDavid S. Miller 	}
1099c14ac945SSoheil Hassas Yeganeh 
110035178206SWillem de Bruijn 	ipcm_init_sk(&ipc, inet);
1101bec1f6f6SWillem de Bruijn 	ipc.gso_size = up->gso_size;
1102bf84a010SDaniel Borkmann 
1103db8dac20SDavid S. Miller 	if (msg->msg_controllen) {
11042e8de857SWillem de Bruijn 		err = udp_cmsg_send(sk, msg, &ipc.gso_size);
11052e8de857SWillem de Bruijn 		if (err > 0)
11062e8de857SWillem de Bruijn 			err = ip_cmsg_send(sk, msg, &ipc,
11072e8de857SWillem de Bruijn 					   sk->sk_family == AF_INET6);
11082e8de857SWillem de Bruijn 		if (unlikely(err < 0)) {
110991948309SEric Dumazet 			kfree(ipc.opt);
1110db8dac20SDavid S. Miller 			return err;
111191948309SEric Dumazet 		}
1112db8dac20SDavid S. Miller 		if (ipc.opt)
1113db8dac20SDavid S. Miller 			free = 1;
1114db8dac20SDavid S. Miller 		connected = 0;
1115db8dac20SDavid S. Miller 	}
1116f6d8bd05SEric Dumazet 	if (!ipc.opt) {
1117f6d8bd05SEric Dumazet 		struct ip_options_rcu *inet_opt;
1118f6d8bd05SEric Dumazet 
1119f6d8bd05SEric Dumazet 		rcu_read_lock();
1120f6d8bd05SEric Dumazet 		inet_opt = rcu_dereference(inet->inet_opt);
1121f6d8bd05SEric Dumazet 		if (inet_opt) {
1122f6d8bd05SEric Dumazet 			memcpy(&opt_copy, inet_opt,
1123f6d8bd05SEric Dumazet 			       sizeof(*inet_opt) + inet_opt->opt.optlen);
1124f6d8bd05SEric Dumazet 			ipc.opt = &opt_copy.opt;
1125f6d8bd05SEric Dumazet 		}
1126f6d8bd05SEric Dumazet 		rcu_read_unlock();
1127f6d8bd05SEric Dumazet 	}
1128db8dac20SDavid S. Miller 
11291cedee13SAndrey Ignatov 	if (cgroup_bpf_enabled && !connected) {
11301cedee13SAndrey Ignatov 		err = BPF_CGROUP_RUN_PROG_UDP4_SENDMSG_LOCK(sk,
11311cedee13SAndrey Ignatov 					    (struct sockaddr *)usin, &ipc.addr);
11321cedee13SAndrey Ignatov 		if (err)
11331cedee13SAndrey Ignatov 			goto out_free;
11341cedee13SAndrey Ignatov 		if (usin) {
11351cedee13SAndrey Ignatov 			if (usin->sin_port == 0) {
11361cedee13SAndrey Ignatov 				/* BPF program set invalid port. Reject it. */
11371cedee13SAndrey Ignatov 				err = -EINVAL;
11381cedee13SAndrey Ignatov 				goto out_free;
11391cedee13SAndrey Ignatov 			}
11401cedee13SAndrey Ignatov 			daddr = usin->sin_addr.s_addr;
11411cedee13SAndrey Ignatov 			dport = usin->sin_port;
11421cedee13SAndrey Ignatov 		}
11431cedee13SAndrey Ignatov 	}
11441cedee13SAndrey Ignatov 
1145db8dac20SDavid S. Miller 	saddr = ipc.addr;
1146db8dac20SDavid S. Miller 	ipc.addr = faddr = daddr;
1147db8dac20SDavid S. Miller 
1148f6d8bd05SEric Dumazet 	if (ipc.opt && ipc.opt->opt.srr) {
11491b97013bSAndrey Ignatov 		if (!daddr) {
11501b97013bSAndrey Ignatov 			err = -EINVAL;
11511b97013bSAndrey Ignatov 			goto out_free;
11521b97013bSAndrey Ignatov 		}
1153f6d8bd05SEric Dumazet 		faddr = ipc.opt->opt.faddr;
1154db8dac20SDavid S. Miller 		connected = 0;
1155db8dac20SDavid S. Miller 	}
1156aa661581SFrancesco Fusco 	tos = get_rttos(&ipc, inet);
1157db8dac20SDavid S. Miller 	if (sock_flag(sk, SOCK_LOCALROUTE) ||
1158db8dac20SDavid S. Miller 	    (msg->msg_flags & MSG_DONTROUTE) ||
1159f6d8bd05SEric Dumazet 	    (ipc.opt && ipc.opt->opt.is_strictroute)) {
1160db8dac20SDavid S. Miller 		tos |= RTO_ONLINK;
1161db8dac20SDavid S. Miller 		connected = 0;
1162db8dac20SDavid S. Miller 	}
1163db8dac20SDavid S. Miller 
1164db8dac20SDavid S. Miller 	if (ipv4_is_multicast(daddr)) {
1165854da991SRobert Shearman 		if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif))
1166db8dac20SDavid S. Miller 			ipc.oif = inet->mc_index;
1167db8dac20SDavid S. Miller 		if (!saddr)
1168db8dac20SDavid S. Miller 			saddr = inet->mc_addr;
1169db8dac20SDavid S. Miller 		connected = 0;
11709515a2e0SDavid Ahern 	} else if (!ipc.oif) {
117176e21053SErich E. Hoover 		ipc.oif = inet->uc_index;
11729515a2e0SDavid Ahern 	} else if (ipv4_is_lbcast(daddr) && inet->uc_index) {
11739515a2e0SDavid Ahern 		/* oif is set, packet is to local broadcast and
11749515a2e0SDavid Ahern 		 * and uc_index is set. oif is most likely set
11759515a2e0SDavid Ahern 		 * by sk_bound_dev_if. If uc_index != oif check if the
11769515a2e0SDavid Ahern 		 * oif is an L3 master and uc_index is an L3 slave.
11779515a2e0SDavid Ahern 		 * If so, we want to allow the send using the uc_index.
11789515a2e0SDavid Ahern 		 */
11799515a2e0SDavid Ahern 		if (ipc.oif != inet->uc_index &&
11809515a2e0SDavid Ahern 		    ipc.oif == l3mdev_master_ifindex_by_index(sock_net(sk),
11819515a2e0SDavid Ahern 							      inet->uc_index)) {
11829515a2e0SDavid Ahern 			ipc.oif = inet->uc_index;
11839515a2e0SDavid Ahern 		}
11849515a2e0SDavid Ahern 	}
1185db8dac20SDavid S. Miller 
1186db8dac20SDavid S. Miller 	if (connected)
1187db8dac20SDavid S. Miller 		rt = (struct rtable *)sk_dst_check(sk, 0);
1188db8dac20SDavid S. Miller 
118951456b29SIan Morris 	if (!rt) {
119084a3aa00SPavel Emelyanov 		struct net *net = sock_net(sk);
11919a24abfaSDavid Ahern 		__u8 flow_flags = inet_sk_flowi_flags(sk);
119284a3aa00SPavel Emelyanov 
1193e474995fSDavid S. Miller 		fl4 = &fl4_stack;
11949a24abfaSDavid Ahern 
1195c6af0c22SWillem de Bruijn 		flowi4_init_output(fl4, ipc.oif, ipc.sockc.mark, tos,
11969a24abfaSDavid Ahern 				   RT_SCOPE_UNIVERSE, sk->sk_protocol,
11979a24abfaSDavid Ahern 				   flow_flags,
1198e2d118a1SLorenzo Colitti 				   faddr, saddr, dport, inet->inet_sport,
1199e2d118a1SLorenzo Colitti 				   sk->sk_uid);
1200c0951cbcSDavid S. Miller 
1201e474995fSDavid S. Miller 		security_sk_classify_flow(sk, flowi4_to_flowi(fl4));
1202e474995fSDavid S. Miller 		rt = ip_route_output_flow(net, fl4, sk);
1203b23dd4feSDavid S. Miller 		if (IS_ERR(rt)) {
1204b23dd4feSDavid S. Miller 			err = PTR_ERR(rt);
120506dc94b1SDavid S. Miller 			rt = NULL;
1206db8dac20SDavid S. Miller 			if (err == -ENETUNREACH)
1207f1d8cba6SEric Dumazet 				IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
1208db8dac20SDavid S. Miller 			goto out;
1209db8dac20SDavid S. Miller 		}
1210db8dac20SDavid S. Miller 
1211db8dac20SDavid S. Miller 		err = -EACCES;
1212db8dac20SDavid S. Miller 		if ((rt->rt_flags & RTCF_BROADCAST) &&
1213db8dac20SDavid S. Miller 		    !sock_flag(sk, SOCK_BROADCAST))
1214db8dac20SDavid S. Miller 			goto out;
1215db8dac20SDavid S. Miller 		if (connected)
1216d8d1f30bSChangli Gao 			sk_dst_set(sk, dst_clone(&rt->dst));
1217db8dac20SDavid S. Miller 	}
1218db8dac20SDavid S. Miller 
1219db8dac20SDavid S. Miller 	if (msg->msg_flags&MSG_CONFIRM)
1220db8dac20SDavid S. Miller 		goto do_confirm;
1221db8dac20SDavid S. Miller back_from_confirm:
1222db8dac20SDavid S. Miller 
1223e474995fSDavid S. Miller 	saddr = fl4->saddr;
1224db8dac20SDavid S. Miller 	if (!ipc.addr)
1225e474995fSDavid S. Miller 		daddr = ipc.addr = fl4->daddr;
1226db8dac20SDavid S. Miller 
1227903ab86dSHerbert Xu 	/* Lockless fast path for the non-corking case. */
1228903ab86dSHerbert Xu 	if (!corkreq) {
12291cd7884dSWillem de Bruijn 		struct inet_cork cork;
12301cd7884dSWillem de Bruijn 
1231f69e6d13SAl Viro 		skb = ip_make_skb(sk, fl4, getfrag, msg, ulen,
1232903ab86dSHerbert Xu 				  sizeof(struct udphdr), &ipc, &rt,
12331cd7884dSWillem de Bruijn 				  &cork, msg->msg_flags);
1234903ab86dSHerbert Xu 		err = PTR_ERR(skb);
123550c3a487SYOSHIFUJI Hideaki / 吉藤英明 		if (!IS_ERR_OR_NULL(skb))
1236bec1f6f6SWillem de Bruijn 			err = udp_send_skb(skb, fl4, &cork);
1237903ab86dSHerbert Xu 		goto out;
1238903ab86dSHerbert Xu 	}
1239903ab86dSHerbert Xu 
1240db8dac20SDavid S. Miller 	lock_sock(sk);
1241db8dac20SDavid S. Miller 	if (unlikely(up->pending)) {
1242db8dac20SDavid S. Miller 		/* The socket is already corked while preparing it. */
1243db8dac20SDavid S. Miller 		/* ... which is an evident application bug. --ANK */
1244db8dac20SDavid S. Miller 		release_sock(sk);
1245db8dac20SDavid S. Miller 
1246197df02cSMatteo Croce 		net_dbg_ratelimited("socket already corked\n");
1247db8dac20SDavid S. Miller 		err = -EINVAL;
1248db8dac20SDavid S. Miller 		goto out;
1249db8dac20SDavid S. Miller 	}
1250db8dac20SDavid S. Miller 	/*
1251db8dac20SDavid S. Miller 	 *	Now cork the socket to pend data.
1252db8dac20SDavid S. Miller 	 */
1253b6f21b26SDavid S. Miller 	fl4 = &inet->cork.fl.u.ip4;
1254b6f21b26SDavid S. Miller 	fl4->daddr = daddr;
1255b6f21b26SDavid S. Miller 	fl4->saddr = saddr;
12569cce96dfSDavid S. Miller 	fl4->fl4_dport = dport;
12579cce96dfSDavid S. Miller 	fl4->fl4_sport = inet->inet_sport;
1258db8dac20SDavid S. Miller 	up->pending = AF_INET;
1259db8dac20SDavid S. Miller 
1260db8dac20SDavid S. Miller do_append_data:
1261db8dac20SDavid S. Miller 	up->len += ulen;
1262f69e6d13SAl Viro 	err = ip_append_data(sk, fl4, getfrag, msg, ulen,
12632e77d89bSEric Dumazet 			     sizeof(struct udphdr), &ipc, &rt,
1264db8dac20SDavid S. Miller 			     corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
1265db8dac20SDavid S. Miller 	if (err)
1266db8dac20SDavid S. Miller 		udp_flush_pending_frames(sk);
1267db8dac20SDavid S. Miller 	else if (!corkreq)
1268db8dac20SDavid S. Miller 		err = udp_push_pending_frames(sk);
1269db8dac20SDavid S. Miller 	else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
1270db8dac20SDavid S. Miller 		up->pending = 0;
1271db8dac20SDavid S. Miller 	release_sock(sk);
1272db8dac20SDavid S. Miller 
1273db8dac20SDavid S. Miller out:
1274db8dac20SDavid S. Miller 	ip_rt_put(rt);
12751b97013bSAndrey Ignatov out_free:
1276db8dac20SDavid S. Miller 	if (free)
1277db8dac20SDavid S. Miller 		kfree(ipc.opt);
1278db8dac20SDavid S. Miller 	if (!err)
1279db8dac20SDavid S. Miller 		return len;
1280db8dac20SDavid S. Miller 	/*
1281db8dac20SDavid S. Miller 	 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space.  Reporting
1282db8dac20SDavid S. Miller 	 * ENOBUFS might not be good (it's not tunable per se), but otherwise
1283db8dac20SDavid S. Miller 	 * we don't have a good statistic (IpOutDiscards but it can be too many
1284db8dac20SDavid S. Miller 	 * things).  We could add another new stat but at least for now that
1285db8dac20SDavid S. Miller 	 * seems like overkill.
1286db8dac20SDavid S. Miller 	 */
1287db8dac20SDavid S. Miller 	if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
12886aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
1289629ca23cSPavel Emelyanov 			      UDP_MIB_SNDBUFERRORS, is_udplite);
1290db8dac20SDavid S. Miller 	}
1291db8dac20SDavid S. Miller 	return err;
1292db8dac20SDavid S. Miller 
1293db8dac20SDavid S. Miller do_confirm:
12940dec879fSJulian Anastasov 	if (msg->msg_flags & MSG_PROBE)
12950dec879fSJulian Anastasov 		dst_confirm_neigh(&rt->dst, &fl4->daddr);
1296db8dac20SDavid S. Miller 	if (!(msg->msg_flags&MSG_PROBE) || len)
1297db8dac20SDavid S. Miller 		goto back_from_confirm;
1298db8dac20SDavid S. Miller 	err = 0;
1299db8dac20SDavid S. Miller 	goto out;
1300db8dac20SDavid S. Miller }
1301c482c568SEric Dumazet EXPORT_SYMBOL(udp_sendmsg);
1302db8dac20SDavid S. Miller 
1303db8dac20SDavid S. Miller int udp_sendpage(struct sock *sk, struct page *page, int offset,
1304db8dac20SDavid S. Miller 		 size_t size, int flags)
1305db8dac20SDavid S. Miller {
1306f5fca608SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1307db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
1308db8dac20SDavid S. Miller 	int ret;
1309db8dac20SDavid S. Miller 
1310d3f7d56aSShawn Landden 	if (flags & MSG_SENDPAGE_NOTLAST)
1311d3f7d56aSShawn Landden 		flags |= MSG_MORE;
1312d3f7d56aSShawn Landden 
1313db8dac20SDavid S. Miller 	if (!up->pending) {
1314db8dac20SDavid S. Miller 		struct msghdr msg = {	.msg_flags = flags|MSG_MORE };
1315db8dac20SDavid S. Miller 
1316db8dac20SDavid S. Miller 		/* Call udp_sendmsg to specify destination address which
1317db8dac20SDavid S. Miller 		 * sendpage interface can't pass.
1318db8dac20SDavid S. Miller 		 * This will succeed only when the socket is connected.
1319db8dac20SDavid S. Miller 		 */
13201b784140SYing Xue 		ret = udp_sendmsg(sk, &msg, 0);
1321db8dac20SDavid S. Miller 		if (ret < 0)
1322db8dac20SDavid S. Miller 			return ret;
1323db8dac20SDavid S. Miller 	}
1324db8dac20SDavid S. Miller 
1325db8dac20SDavid S. Miller 	lock_sock(sk);
1326db8dac20SDavid S. Miller 
1327db8dac20SDavid S. Miller 	if (unlikely(!up->pending)) {
1328db8dac20SDavid S. Miller 		release_sock(sk);
1329db8dac20SDavid S. Miller 
1330197df02cSMatteo Croce 		net_dbg_ratelimited("cork failed\n");
1331db8dac20SDavid S. Miller 		return -EINVAL;
1332db8dac20SDavid S. Miller 	}
1333db8dac20SDavid S. Miller 
1334f5fca608SDavid S. Miller 	ret = ip_append_page(sk, &inet->cork.fl.u.ip4,
1335f5fca608SDavid S. Miller 			     page, offset, size, flags);
1336db8dac20SDavid S. Miller 	if (ret == -EOPNOTSUPP) {
1337db8dac20SDavid S. Miller 		release_sock(sk);
1338db8dac20SDavid S. Miller 		return sock_no_sendpage(sk->sk_socket, page, offset,
1339db8dac20SDavid S. Miller 					size, flags);
1340db8dac20SDavid S. Miller 	}
1341db8dac20SDavid S. Miller 	if (ret < 0) {
1342db8dac20SDavid S. Miller 		udp_flush_pending_frames(sk);
1343db8dac20SDavid S. Miller 		goto out;
1344db8dac20SDavid S. Miller 	}
1345db8dac20SDavid S. Miller 
1346db8dac20SDavid S. Miller 	up->len += size;
1347db8dac20SDavid S. Miller 	if (!(up->corkflag || (flags&MSG_MORE)))
1348db8dac20SDavid S. Miller 		ret = udp_push_pending_frames(sk);
1349db8dac20SDavid S. Miller 	if (!ret)
1350db8dac20SDavid S. Miller 		ret = size;
1351db8dac20SDavid S. Miller out:
1352db8dac20SDavid S. Miller 	release_sock(sk);
1353db8dac20SDavid S. Miller 	return ret;
1354db8dac20SDavid S. Miller }
1355db8dac20SDavid S. Miller 
1356dce4551cSPaolo Abeni #define UDP_SKB_IS_STATELESS 0x80000000
1357dce4551cSPaolo Abeni 
1358677bf08cSFlorian Westphal /* all head states (dst, sk, nf conntrack) except skb extensions are
1359677bf08cSFlorian Westphal  * cleared by udp_rcv().
1360677bf08cSFlorian Westphal  *
1361677bf08cSFlorian Westphal  * We need to preserve secpath, if present, to eventually process
1362677bf08cSFlorian Westphal  * IP_CMSG_PASSSEC at recvmsg() time.
1363677bf08cSFlorian Westphal  *
1364677bf08cSFlorian Westphal  * Other extensions can be cleared.
1365677bf08cSFlorian Westphal  */
1366677bf08cSFlorian Westphal static bool udp_try_make_stateless(struct sk_buff *skb)
1367677bf08cSFlorian Westphal {
1368677bf08cSFlorian Westphal 	if (!skb_has_extensions(skb))
1369677bf08cSFlorian Westphal 		return true;
1370677bf08cSFlorian Westphal 
1371677bf08cSFlorian Westphal 	if (!secpath_exists(skb)) {
1372677bf08cSFlorian Westphal 		skb_ext_reset(skb);
1373677bf08cSFlorian Westphal 		return true;
1374677bf08cSFlorian Westphal 	}
1375677bf08cSFlorian Westphal 
1376677bf08cSFlorian Westphal 	return false;
1377677bf08cSFlorian Westphal }
1378677bf08cSFlorian Westphal 
1379b65ac446SPaolo Abeni static void udp_set_dev_scratch(struct sk_buff *skb)
1380b65ac446SPaolo Abeni {
1381dce4551cSPaolo Abeni 	struct udp_dev_scratch *scratch = udp_skb_scratch(skb);
1382b65ac446SPaolo Abeni 
1383b65ac446SPaolo Abeni 	BUILD_BUG_ON(sizeof(struct udp_dev_scratch) > sizeof(long));
1384dce4551cSPaolo Abeni 	scratch->_tsize_state = skb->truesize;
1385dce4551cSPaolo Abeni #if BITS_PER_LONG == 64
1386b65ac446SPaolo Abeni 	scratch->len = skb->len;
1387b65ac446SPaolo Abeni 	scratch->csum_unnecessary = !!skb_csum_unnecessary(skb);
1388b65ac446SPaolo Abeni 	scratch->is_linear = !skb_is_nonlinear(skb);
1389b65ac446SPaolo Abeni #endif
1390677bf08cSFlorian Westphal 	if (udp_try_make_stateless(skb))
1391dce4551cSPaolo Abeni 		scratch->_tsize_state |= UDP_SKB_IS_STATELESS;
1392dce4551cSPaolo Abeni }
1393dce4551cSPaolo Abeni 
1394a793183cSEric Dumazet static void udp_skb_csum_unnecessary_set(struct sk_buff *skb)
1395a793183cSEric Dumazet {
1396a793183cSEric Dumazet 	/* We come here after udp_lib_checksum_complete() returned 0.
1397a793183cSEric Dumazet 	 * This means that __skb_checksum_complete() might have
1398a793183cSEric Dumazet 	 * set skb->csum_valid to 1.
1399a793183cSEric Dumazet 	 * On 64bit platforms, we can set csum_unnecessary
1400a793183cSEric Dumazet 	 * to true, but only if the skb is not shared.
1401a793183cSEric Dumazet 	 */
1402a793183cSEric Dumazet #if BITS_PER_LONG == 64
1403a793183cSEric Dumazet 	if (!skb_shared(skb))
1404a793183cSEric Dumazet 		udp_skb_scratch(skb)->csum_unnecessary = true;
1405a793183cSEric Dumazet #endif
1406a793183cSEric Dumazet }
1407a793183cSEric Dumazet 
1408dce4551cSPaolo Abeni static int udp_skb_truesize(struct sk_buff *skb)
1409dce4551cSPaolo Abeni {
1410dce4551cSPaolo Abeni 	return udp_skb_scratch(skb)->_tsize_state & ~UDP_SKB_IS_STATELESS;
1411dce4551cSPaolo Abeni }
1412dce4551cSPaolo Abeni 
1413dce4551cSPaolo Abeni static bool udp_skb_has_head_state(struct sk_buff *skb)
1414dce4551cSPaolo Abeni {
1415dce4551cSPaolo Abeni 	return !(udp_skb_scratch(skb)->_tsize_state & UDP_SKB_IS_STATELESS);
1416dce4551cSPaolo Abeni }
1417b65ac446SPaolo Abeni 
14187c13f97fSPaolo Abeni /* fully reclaim rmem/fwd memory allocated for skb */
14196dfb4367SPaolo Abeni static void udp_rmem_release(struct sock *sk, int size, int partial,
14206dfb4367SPaolo Abeni 			     bool rx_queue_lock_held)
1421f970bd9eSPaolo Abeni {
14226b229cf7SEric Dumazet 	struct udp_sock *up = udp_sk(sk);
14232276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue;
1424f970bd9eSPaolo Abeni 	int amt;
1425f970bd9eSPaolo Abeni 
14266b229cf7SEric Dumazet 	if (likely(partial)) {
14276b229cf7SEric Dumazet 		up->forward_deficit += size;
14286b229cf7SEric Dumazet 		size = up->forward_deficit;
1429d39ca259SPaolo Abeni 		if (size < (sk->sk_rcvbuf >> 2) &&
1430d39ca259SPaolo Abeni 		    !skb_queue_empty(&up->reader_queue))
14316b229cf7SEric Dumazet 			return;
14326b229cf7SEric Dumazet 	} else {
14336b229cf7SEric Dumazet 		size += up->forward_deficit;
14346b229cf7SEric Dumazet 	}
14356b229cf7SEric Dumazet 	up->forward_deficit = 0;
14366b229cf7SEric Dumazet 
14376dfb4367SPaolo Abeni 	/* acquire the sk_receive_queue for fwd allocated memory scheduling,
14386dfb4367SPaolo Abeni 	 * if the called don't held it already
14396dfb4367SPaolo Abeni 	 */
14402276f58aSPaolo Abeni 	sk_queue = &sk->sk_receive_queue;
14416dfb4367SPaolo Abeni 	if (!rx_queue_lock_held)
14422276f58aSPaolo Abeni 		spin_lock(&sk_queue->lock);
14432276f58aSPaolo Abeni 
14446dfb4367SPaolo Abeni 
1445f970bd9eSPaolo Abeni 	sk->sk_forward_alloc += size;
1446f970bd9eSPaolo Abeni 	amt = (sk->sk_forward_alloc - partial) & ~(SK_MEM_QUANTUM - 1);
1447f970bd9eSPaolo Abeni 	sk->sk_forward_alloc -= amt;
1448f970bd9eSPaolo Abeni 
1449f970bd9eSPaolo Abeni 	if (amt)
1450f970bd9eSPaolo Abeni 		__sk_mem_reduce_allocated(sk, amt >> SK_MEM_QUANTUM_SHIFT);
145102ab0d13SEric Dumazet 
145202ab0d13SEric Dumazet 	atomic_sub(size, &sk->sk_rmem_alloc);
14532276f58aSPaolo Abeni 
14542276f58aSPaolo Abeni 	/* this can save us from acquiring the rx queue lock on next receive */
14552276f58aSPaolo Abeni 	skb_queue_splice_tail_init(sk_queue, &up->reader_queue);
14562276f58aSPaolo Abeni 
14576dfb4367SPaolo Abeni 	if (!rx_queue_lock_held)
14582276f58aSPaolo Abeni 		spin_unlock(&sk_queue->lock);
1459f970bd9eSPaolo Abeni }
1460f970bd9eSPaolo Abeni 
14612276f58aSPaolo Abeni /* Note: called with reader_queue.lock held.
1462c84d9490SEric Dumazet  * Instead of using skb->truesize here, find a copy of it in skb->dev_scratch
1463c84d9490SEric Dumazet  * This avoids a cache line miss while receive_queue lock is held.
1464c84d9490SEric Dumazet  * Look at __udp_enqueue_schedule_skb() to find where this copy is done.
1465c84d9490SEric Dumazet  */
14667c13f97fSPaolo Abeni void udp_skb_destructor(struct sock *sk, struct sk_buff *skb)
1467f970bd9eSPaolo Abeni {
1468b65ac446SPaolo Abeni 	prefetch(&skb->data);
1469b65ac446SPaolo Abeni 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, false);
1470f970bd9eSPaolo Abeni }
14717c13f97fSPaolo Abeni EXPORT_SYMBOL(udp_skb_destructor);
1472f970bd9eSPaolo Abeni 
14736dfb4367SPaolo Abeni /* as above, but the caller held the rx queue lock, too */
147464f5102dSColin Ian King static void udp_skb_dtor_locked(struct sock *sk, struct sk_buff *skb)
14756dfb4367SPaolo Abeni {
1476b65ac446SPaolo Abeni 	prefetch(&skb->data);
1477b65ac446SPaolo Abeni 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, true);
14786dfb4367SPaolo Abeni }
14796dfb4367SPaolo Abeni 
14804b272750SEric Dumazet /* Idea of busylocks is to let producers grab an extra spinlock
14814b272750SEric Dumazet  * to relieve pressure on the receive_queue spinlock shared by consumer.
14824b272750SEric Dumazet  * Under flood, this means that only one producer can be in line
14834b272750SEric Dumazet  * trying to acquire the receive_queue spinlock.
14844b272750SEric Dumazet  * These busylock can be allocated on a per cpu manner, instead of a
14854b272750SEric Dumazet  * per socket one (that would consume a cache line per socket)
14864b272750SEric Dumazet  */
14874b272750SEric Dumazet static int udp_busylocks_log __read_mostly;
14884b272750SEric Dumazet static spinlock_t *udp_busylocks __read_mostly;
14894b272750SEric Dumazet 
14904b272750SEric Dumazet static spinlock_t *busylock_acquire(void *ptr)
14914b272750SEric Dumazet {
14924b272750SEric Dumazet 	spinlock_t *busy;
14934b272750SEric Dumazet 
14944b272750SEric Dumazet 	busy = udp_busylocks + hash_ptr(ptr, udp_busylocks_log);
14954b272750SEric Dumazet 	spin_lock(busy);
14964b272750SEric Dumazet 	return busy;
14974b272750SEric Dumazet }
14984b272750SEric Dumazet 
14994b272750SEric Dumazet static void busylock_release(spinlock_t *busy)
15004b272750SEric Dumazet {
15014b272750SEric Dumazet 	if (busy)
15024b272750SEric Dumazet 		spin_unlock(busy);
15034b272750SEric Dumazet }
15044b272750SEric Dumazet 
1505f970bd9eSPaolo Abeni int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb)
1506f970bd9eSPaolo Abeni {
1507f970bd9eSPaolo Abeni 	struct sk_buff_head *list = &sk->sk_receive_queue;
1508f970bd9eSPaolo Abeni 	int rmem, delta, amt, err = -ENOMEM;
15094b272750SEric Dumazet 	spinlock_t *busy = NULL;
1510c8c8b127SEric Dumazet 	int size;
1511f970bd9eSPaolo Abeni 
1512f970bd9eSPaolo Abeni 	/* try to avoid the costly atomic add/sub pair when the receive
1513f970bd9eSPaolo Abeni 	 * queue is full; always allow at least a packet
1514f970bd9eSPaolo Abeni 	 */
1515f970bd9eSPaolo Abeni 	rmem = atomic_read(&sk->sk_rmem_alloc);
1516363dc73aSPaolo Abeni 	if (rmem > sk->sk_rcvbuf)
1517f970bd9eSPaolo Abeni 		goto drop;
1518f970bd9eSPaolo Abeni 
1519c8c8b127SEric Dumazet 	/* Under mem pressure, it might be helpful to help udp_recvmsg()
1520c8c8b127SEric Dumazet 	 * having linear skbs :
1521c8c8b127SEric Dumazet 	 * - Reduce memory overhead and thus increase receive queue capacity
1522c8c8b127SEric Dumazet 	 * - Less cache line misses at copyout() time
1523c8c8b127SEric Dumazet 	 * - Less work at consume_skb() (less alien page frag freeing)
1524c8c8b127SEric Dumazet 	 */
15254b272750SEric Dumazet 	if (rmem > (sk->sk_rcvbuf >> 1)) {
1526c8c8b127SEric Dumazet 		skb_condense(skb);
15274b272750SEric Dumazet 
15284b272750SEric Dumazet 		busy = busylock_acquire(sk);
15294b272750SEric Dumazet 	}
1530c8c8b127SEric Dumazet 	size = skb->truesize;
1531b65ac446SPaolo Abeni 	udp_set_dev_scratch(skb);
1532c8c8b127SEric Dumazet 
1533f970bd9eSPaolo Abeni 	/* we drop only if the receive buf is full and the receive
1534f970bd9eSPaolo Abeni 	 * queue contains some other skb
1535f970bd9eSPaolo Abeni 	 */
1536f970bd9eSPaolo Abeni 	rmem = atomic_add_return(size, &sk->sk_rmem_alloc);
1537feed8a4fSAntonio Messina 	if (rmem > (size + (unsigned int)sk->sk_rcvbuf))
1538f970bd9eSPaolo Abeni 		goto uncharge_drop;
1539f970bd9eSPaolo Abeni 
1540f970bd9eSPaolo Abeni 	spin_lock(&list->lock);
1541f970bd9eSPaolo Abeni 	if (size >= sk->sk_forward_alloc) {
1542f970bd9eSPaolo Abeni 		amt = sk_mem_pages(size);
1543f970bd9eSPaolo Abeni 		delta = amt << SK_MEM_QUANTUM_SHIFT;
1544f970bd9eSPaolo Abeni 		if (!__sk_mem_raise_allocated(sk, delta, amt, SK_MEM_RECV)) {
1545f970bd9eSPaolo Abeni 			err = -ENOBUFS;
1546f970bd9eSPaolo Abeni 			spin_unlock(&list->lock);
1547f970bd9eSPaolo Abeni 			goto uncharge_drop;
1548f970bd9eSPaolo Abeni 		}
1549f970bd9eSPaolo Abeni 
1550f970bd9eSPaolo Abeni 		sk->sk_forward_alloc += delta;
1551f970bd9eSPaolo Abeni 	}
1552f970bd9eSPaolo Abeni 
1553f970bd9eSPaolo Abeni 	sk->sk_forward_alloc -= size;
1554f970bd9eSPaolo Abeni 
15557c13f97fSPaolo Abeni 	/* no need to setup a destructor, we will explicitly release the
15567c13f97fSPaolo Abeni 	 * forward allocated memory on dequeue
15577c13f97fSPaolo Abeni 	 */
1558f970bd9eSPaolo Abeni 	sock_skb_set_dropcount(sk, skb);
1559f970bd9eSPaolo Abeni 
1560f970bd9eSPaolo Abeni 	__skb_queue_tail(list, skb);
1561f970bd9eSPaolo Abeni 	spin_unlock(&list->lock);
1562f970bd9eSPaolo Abeni 
1563f970bd9eSPaolo Abeni 	if (!sock_flag(sk, SOCK_DEAD))
1564f970bd9eSPaolo Abeni 		sk->sk_data_ready(sk);
1565f970bd9eSPaolo Abeni 
15664b272750SEric Dumazet 	busylock_release(busy);
1567f970bd9eSPaolo Abeni 	return 0;
1568f970bd9eSPaolo Abeni 
1569f970bd9eSPaolo Abeni uncharge_drop:
1570f970bd9eSPaolo Abeni 	atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
1571f970bd9eSPaolo Abeni 
1572f970bd9eSPaolo Abeni drop:
1573f970bd9eSPaolo Abeni 	atomic_inc(&sk->sk_drops);
15744b272750SEric Dumazet 	busylock_release(busy);
1575f970bd9eSPaolo Abeni 	return err;
1576f970bd9eSPaolo Abeni }
1577f970bd9eSPaolo Abeni EXPORT_SYMBOL_GPL(__udp_enqueue_schedule_skb);
1578f970bd9eSPaolo Abeni 
1579c915fe13SPaolo Abeni void udp_destruct_sock(struct sock *sk)
1580f970bd9eSPaolo Abeni {
1581f970bd9eSPaolo Abeni 	/* reclaim completely the forward allocated memory */
15822276f58aSPaolo Abeni 	struct udp_sock *up = udp_sk(sk);
15837c13f97fSPaolo Abeni 	unsigned int total = 0;
15847c13f97fSPaolo Abeni 	struct sk_buff *skb;
15857c13f97fSPaolo Abeni 
15862276f58aSPaolo Abeni 	skb_queue_splice_tail_init(&sk->sk_receive_queue, &up->reader_queue);
15872276f58aSPaolo Abeni 	while ((skb = __skb_dequeue(&up->reader_queue)) != NULL) {
15887c13f97fSPaolo Abeni 		total += skb->truesize;
15897c13f97fSPaolo Abeni 		kfree_skb(skb);
15907c13f97fSPaolo Abeni 	}
15916dfb4367SPaolo Abeni 	udp_rmem_release(sk, total, 0, true);
15927c13f97fSPaolo Abeni 
1593f970bd9eSPaolo Abeni 	inet_sock_destruct(sk);
1594f970bd9eSPaolo Abeni }
1595c915fe13SPaolo Abeni EXPORT_SYMBOL_GPL(udp_destruct_sock);
1596f970bd9eSPaolo Abeni 
1597f970bd9eSPaolo Abeni int udp_init_sock(struct sock *sk)
1598f970bd9eSPaolo Abeni {
15992276f58aSPaolo Abeni 	skb_queue_head_init(&udp_sk(sk)->reader_queue);
1600f970bd9eSPaolo Abeni 	sk->sk_destruct = udp_destruct_sock;
1601f970bd9eSPaolo Abeni 	return 0;
1602f970bd9eSPaolo Abeni }
1603f970bd9eSPaolo Abeni EXPORT_SYMBOL_GPL(udp_init_sock);
1604f970bd9eSPaolo Abeni 
1605f970bd9eSPaolo Abeni void skb_consume_udp(struct sock *sk, struct sk_buff *skb, int len)
1606f970bd9eSPaolo Abeni {
1607f970bd9eSPaolo Abeni 	if (unlikely(READ_ONCE(sk->sk_peek_off) >= 0)) {
1608f970bd9eSPaolo Abeni 		bool slow = lock_sock_fast(sk);
1609f970bd9eSPaolo Abeni 
1610f970bd9eSPaolo Abeni 		sk_peek_offset_bwd(sk, len);
1611f970bd9eSPaolo Abeni 		unlock_sock_fast(sk, slow);
1612f970bd9eSPaolo Abeni 	}
16130a463c78SPaolo Abeni 
1614ca2c1418SPaolo Abeni 	if (!skb_unref(skb))
1615ca2c1418SPaolo Abeni 		return;
1616ca2c1418SPaolo Abeni 
1617dce4551cSPaolo Abeni 	/* In the more common cases we cleared the head states previously,
1618dce4551cSPaolo Abeni 	 * see __udp_queue_rcv_skb().
16190ddf3fb2SPaolo Abeni 	 */
1620dce4551cSPaolo Abeni 	if (unlikely(udp_skb_has_head_state(skb)))
16210ddf3fb2SPaolo Abeni 		skb_release_head_state(skb);
1622ca2c1418SPaolo Abeni 	__consume_stateless_skb(skb);
1623f970bd9eSPaolo Abeni }
1624f970bd9eSPaolo Abeni EXPORT_SYMBOL_GPL(skb_consume_udp);
1625f970bd9eSPaolo Abeni 
16262276f58aSPaolo Abeni static struct sk_buff *__first_packet_length(struct sock *sk,
16272276f58aSPaolo Abeni 					     struct sk_buff_head *rcvq,
16282276f58aSPaolo Abeni 					     int *total)
16292276f58aSPaolo Abeni {
16302276f58aSPaolo Abeni 	struct sk_buff *skb;
16312276f58aSPaolo Abeni 
16329bd780f5SPaolo Abeni 	while ((skb = skb_peek(rcvq)) != NULL) {
16339bd780f5SPaolo Abeni 		if (udp_lib_checksum_complete(skb)) {
16342276f58aSPaolo Abeni 			__UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS,
16352276f58aSPaolo Abeni 					IS_UDPLITE(sk));
16362276f58aSPaolo Abeni 			__UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS,
16372276f58aSPaolo Abeni 					IS_UDPLITE(sk));
16382276f58aSPaolo Abeni 			atomic_inc(&sk->sk_drops);
16392276f58aSPaolo Abeni 			__skb_unlink(skb, rcvq);
16402276f58aSPaolo Abeni 			*total += skb->truesize;
16412276f58aSPaolo Abeni 			kfree_skb(skb);
16429bd780f5SPaolo Abeni 		} else {
1643a793183cSEric Dumazet 			udp_skb_csum_unnecessary_set(skb);
16449bd780f5SPaolo Abeni 			break;
16459bd780f5SPaolo Abeni 		}
16462276f58aSPaolo Abeni 	}
16472276f58aSPaolo Abeni 	return skb;
16482276f58aSPaolo Abeni }
16492276f58aSPaolo Abeni 
165085584672SEric Dumazet /**
165185584672SEric Dumazet  *	first_packet_length	- return length of first packet in receive queue
165285584672SEric Dumazet  *	@sk: socket
165385584672SEric Dumazet  *
165485584672SEric Dumazet  *	Drops all bad checksum frames, until a valid one is found.
1655e83c6744SEric Dumazet  *	Returns the length of found skb, or -1 if none is found.
165685584672SEric Dumazet  */
1657e83c6744SEric Dumazet static int first_packet_length(struct sock *sk)
165885584672SEric Dumazet {
16592276f58aSPaolo Abeni 	struct sk_buff_head *rcvq = &udp_sk(sk)->reader_queue;
16602276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
166185584672SEric Dumazet 	struct sk_buff *skb;
16627c13f97fSPaolo Abeni 	int total = 0;
1663e83c6744SEric Dumazet 	int res;
166485584672SEric Dumazet 
166585584672SEric Dumazet 	spin_lock_bh(&rcvq->lock);
16662276f58aSPaolo Abeni 	skb = __first_packet_length(sk, rcvq, &total);
1667137a0dbeSEric Dumazet 	if (!skb && !skb_queue_empty_lockless(sk_queue)) {
16682276f58aSPaolo Abeni 		spin_lock(&sk_queue->lock);
16692276f58aSPaolo Abeni 		skb_queue_splice_tail_init(sk_queue, rcvq);
16702276f58aSPaolo Abeni 		spin_unlock(&sk_queue->lock);
16712276f58aSPaolo Abeni 
16722276f58aSPaolo Abeni 		skb = __first_packet_length(sk, rcvq, &total);
167385584672SEric Dumazet 	}
1674e83c6744SEric Dumazet 	res = skb ? skb->len : -1;
16757c13f97fSPaolo Abeni 	if (total)
16766dfb4367SPaolo Abeni 		udp_rmem_release(sk, total, 1, false);
167785584672SEric Dumazet 	spin_unlock_bh(&rcvq->lock);
167885584672SEric Dumazet 	return res;
167985584672SEric Dumazet }
168085584672SEric Dumazet 
16811da177e4SLinus Torvalds /*
16821da177e4SLinus Torvalds  *	IOCTL requests applicable to the UDP protocol
16831da177e4SLinus Torvalds  */
16841da177e4SLinus Torvalds 
16851da177e4SLinus Torvalds int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
16861da177e4SLinus Torvalds {
16876516c655SStephen Hemminger 	switch (cmd) {
16881da177e4SLinus Torvalds 	case SIOCOUTQ:
16891da177e4SLinus Torvalds 	{
169031e6d363SEric Dumazet 		int amount = sk_wmem_alloc_get(sk);
169131e6d363SEric Dumazet 
16921da177e4SLinus Torvalds 		return put_user(amount, (int __user *)arg);
16931da177e4SLinus Torvalds 	}
16941da177e4SLinus Torvalds 
16951da177e4SLinus Torvalds 	case SIOCINQ:
16961da177e4SLinus Torvalds 	{
1697e83c6744SEric Dumazet 		int amount = max_t(int, 0, first_packet_length(sk));
16981da177e4SLinus Torvalds 
16991da177e4SLinus Torvalds 		return put_user(amount, (int __user *)arg);
17001da177e4SLinus Torvalds 	}
17011da177e4SLinus Torvalds 
17021da177e4SLinus Torvalds 	default:
17031da177e4SLinus Torvalds 		return -ENOIOCTLCMD;
17041da177e4SLinus Torvalds 	}
17056516c655SStephen Hemminger 
17066516c655SStephen Hemminger 	return 0;
17071da177e4SLinus Torvalds }
1708c482c568SEric Dumazet EXPORT_SYMBOL(udp_ioctl);
17091da177e4SLinus Torvalds 
17102276f58aSPaolo Abeni struct sk_buff *__skb_recv_udp(struct sock *sk, unsigned int flags,
1711fd69c399SPaolo Abeni 			       int noblock, int *off, int *err)
17122276f58aSPaolo Abeni {
17132276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
17142276f58aSPaolo Abeni 	struct sk_buff_head *queue;
17152276f58aSPaolo Abeni 	struct sk_buff *last;
17162276f58aSPaolo Abeni 	long timeo;
17172276f58aSPaolo Abeni 	int error;
17182276f58aSPaolo Abeni 
17192276f58aSPaolo Abeni 	queue = &udp_sk(sk)->reader_queue;
17202276f58aSPaolo Abeni 	flags |= noblock ? MSG_DONTWAIT : 0;
17212276f58aSPaolo Abeni 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
17222276f58aSPaolo Abeni 	do {
17232276f58aSPaolo Abeni 		struct sk_buff *skb;
17242276f58aSPaolo Abeni 
17252276f58aSPaolo Abeni 		error = sock_error(sk);
17262276f58aSPaolo Abeni 		if (error)
17272276f58aSPaolo Abeni 			break;
17282276f58aSPaolo Abeni 
17292276f58aSPaolo Abeni 		error = -EAGAIN;
17302276f58aSPaolo Abeni 		do {
17312276f58aSPaolo Abeni 			spin_lock_bh(&queue->lock);
1732e427cad6SPaolo Abeni 			skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1733e427cad6SPaolo Abeni 							err, &last);
17342276f58aSPaolo Abeni 			if (skb) {
1735e427cad6SPaolo Abeni 				if (!(flags & MSG_PEEK))
1736e427cad6SPaolo Abeni 					udp_skb_destructor(sk, skb);
17372276f58aSPaolo Abeni 				spin_unlock_bh(&queue->lock);
17382276f58aSPaolo Abeni 				return skb;
17392276f58aSPaolo Abeni 			}
17402276f58aSPaolo Abeni 
1741137a0dbeSEric Dumazet 			if (skb_queue_empty_lockless(sk_queue)) {
17422276f58aSPaolo Abeni 				spin_unlock_bh(&queue->lock);
17432276f58aSPaolo Abeni 				goto busy_check;
17442276f58aSPaolo Abeni 			}
17452276f58aSPaolo Abeni 
17466dfb4367SPaolo Abeni 			/* refill the reader queue and walk it again
17476dfb4367SPaolo Abeni 			 * keep both queues locked to avoid re-acquiring
17486dfb4367SPaolo Abeni 			 * the sk_receive_queue lock if fwd memory scheduling
17496dfb4367SPaolo Abeni 			 * is needed.
17506dfb4367SPaolo Abeni 			 */
17512276f58aSPaolo Abeni 			spin_lock(&sk_queue->lock);
17522276f58aSPaolo Abeni 			skb_queue_splice_tail_init(sk_queue, queue);
17532276f58aSPaolo Abeni 
1754e427cad6SPaolo Abeni 			skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1755e427cad6SPaolo Abeni 							err, &last);
1756e427cad6SPaolo Abeni 			if (skb && !(flags & MSG_PEEK))
1757e427cad6SPaolo Abeni 				udp_skb_dtor_locked(sk, skb);
17586dfb4367SPaolo Abeni 			spin_unlock(&sk_queue->lock);
17592276f58aSPaolo Abeni 			spin_unlock_bh(&queue->lock);
1760de321ed3SAndrey Vagin 			if (skb)
17612276f58aSPaolo Abeni 				return skb;
17622276f58aSPaolo Abeni 
17632276f58aSPaolo Abeni busy_check:
17642276f58aSPaolo Abeni 			if (!sk_can_busy_loop(sk))
17652276f58aSPaolo Abeni 				break;
17662276f58aSPaolo Abeni 
17672276f58aSPaolo Abeni 			sk_busy_loop(sk, flags & MSG_DONTWAIT);
1768137a0dbeSEric Dumazet 		} while (!skb_queue_empty_lockless(sk_queue));
17692276f58aSPaolo Abeni 
17702276f58aSPaolo Abeni 		/* sk_queue is empty, reader_queue may contain peeked packets */
17712276f58aSPaolo Abeni 	} while (timeo &&
1772b50b0580SSabrina Dubroca 		 !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,
1773b50b0580SSabrina Dubroca 					      &error, &timeo,
17742276f58aSPaolo Abeni 					      (struct sk_buff *)sk_queue));
17752276f58aSPaolo Abeni 
17762276f58aSPaolo Abeni 	*err = error;
17772276f58aSPaolo Abeni 	return NULL;
17782276f58aSPaolo Abeni }
17797e823644SJiri Kosina EXPORT_SYMBOL(__skb_recv_udp);
17802276f58aSPaolo Abeni 
1781db8dac20SDavid S. Miller /*
1782db8dac20SDavid S. Miller  * 	This should be easy, if there is something there we
1783db8dac20SDavid S. Miller  * 	return it, otherwise we block.
1784db8dac20SDavid S. Miller  */
1785db8dac20SDavid S. Miller 
17861b784140SYing Xue int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock,
17871b784140SYing Xue 		int flags, int *addr_len)
1788db8dac20SDavid S. Miller {
1789db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1790342dfc30SSteffen Hurrle 	DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
1791db8dac20SDavid S. Miller 	struct sk_buff *skb;
179259c2cdaeSDavid S. Miller 	unsigned int ulen, copied;
1793fd69c399SPaolo Abeni 	int off, err, peeking = flags & MSG_PEEK;
1794db8dac20SDavid S. Miller 	int is_udplite = IS_UDPLITE(sk);
1795197c949eSEric Dumazet 	bool checksum_valid = false;
1796db8dac20SDavid S. Miller 
1797db8dac20SDavid S. Miller 	if (flags & MSG_ERRQUEUE)
179885fbaa75SHannes Frederic Sowa 		return ip_recv_error(sk, msg, len, addr_len);
1799db8dac20SDavid S. Miller 
1800db8dac20SDavid S. Miller try_again:
1801a0917e0bSMatthew Dawson 	off = sk_peek_offset(sk, flags);
1802fd69c399SPaolo Abeni 	skb = __skb_recv_udp(sk, flags, noblock, &off, &err);
1803db8dac20SDavid S. Miller 	if (!skb)
1804627d2d6bSsamanthakumar 		return err;
1805db8dac20SDavid S. Miller 
1806b65ac446SPaolo Abeni 	ulen = udp_skb_len(skb);
180759c2cdaeSDavid S. Miller 	copied = len;
1808627d2d6bSsamanthakumar 	if (copied > ulen - off)
1809627d2d6bSsamanthakumar 		copied = ulen - off;
181059c2cdaeSDavid S. Miller 	else if (copied < ulen)
1811db8dac20SDavid S. Miller 		msg->msg_flags |= MSG_TRUNC;
1812db8dac20SDavid S. Miller 
1813db8dac20SDavid S. Miller 	/*
1814db8dac20SDavid S. Miller 	 * If checksum is needed at all, try to do it while copying the
1815db8dac20SDavid S. Miller 	 * data.  If the data is truncated, or if we only want a partial
1816db8dac20SDavid S. Miller 	 * coverage checksum (UDP-Lite), do it before the copy.
1817db8dac20SDavid S. Miller 	 */
1818db8dac20SDavid S. Miller 
1819d21dbdfeSEric Dumazet 	if (copied < ulen || peeking ||
1820d21dbdfeSEric Dumazet 	    (is_udplite && UDP_SKB_CB(skb)->partial_cov)) {
1821b65ac446SPaolo Abeni 		checksum_valid = udp_skb_csum_unnecessary(skb) ||
1822b65ac446SPaolo Abeni 				!__udp_lib_checksum_complete(skb);
1823197c949eSEric Dumazet 		if (!checksum_valid)
1824db8dac20SDavid S. Miller 			goto csum_copy_err;
1825db8dac20SDavid S. Miller 	}
1826db8dac20SDavid S. Miller 
1827b65ac446SPaolo Abeni 	if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
1828b65ac446SPaolo Abeni 		if (udp_skb_is_linear(skb))
1829b65ac446SPaolo Abeni 			err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
1830b65ac446SPaolo Abeni 		else
1831627d2d6bSsamanthakumar 			err = skb_copy_datagram_msg(skb, off, msg, copied);
1832b65ac446SPaolo Abeni 	} else {
1833627d2d6bSsamanthakumar 		err = skb_copy_and_csum_datagram_msg(skb, off, msg);
1834db8dac20SDavid S. Miller 
1835db8dac20SDavid S. Miller 		if (err == -EINVAL)
1836db8dac20SDavid S. Miller 			goto csum_copy_err;
1837db8dac20SDavid S. Miller 	}
1838db8dac20SDavid S. Miller 
183922911fc5SEric Dumazet 	if (unlikely(err)) {
1840fd69c399SPaolo Abeni 		if (!peeking) {
1841979402b1SEric Dumazet 			atomic_inc(&sk->sk_drops);
18426aef70a8SEric Dumazet 			UDP_INC_STATS(sock_net(sk),
1843979402b1SEric Dumazet 				      UDP_MIB_INERRORS, is_udplite);
1844979402b1SEric Dumazet 		}
1845850cbaddSPaolo Abeni 		kfree_skb(skb);
1846627d2d6bSsamanthakumar 		return err;
184722911fc5SEric Dumazet 	}
1848db8dac20SDavid S. Miller 
1849fd69c399SPaolo Abeni 	if (!peeking)
18506aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
1851629ca23cSPavel Emelyanov 			      UDP_MIB_INDATAGRAMS, is_udplite);
1852db8dac20SDavid S. Miller 
18533b885787SNeil Horman 	sock_recv_ts_and_drops(msg, sk, skb);
1854db8dac20SDavid S. Miller 
1855db8dac20SDavid S. Miller 	/* Copy the address. */
1856c482c568SEric Dumazet 	if (sin) {
1857db8dac20SDavid S. Miller 		sin->sin_family = AF_INET;
1858db8dac20SDavid S. Miller 		sin->sin_port = udp_hdr(skb)->source;
1859db8dac20SDavid S. Miller 		sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
1860db8dac20SDavid S. Miller 		memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
1861bceaa902SHannes Frederic Sowa 		*addr_len = sizeof(*sin);
1862983695faSDaniel Borkmann 
1863983695faSDaniel Borkmann 		if (cgroup_bpf_enabled)
1864983695faSDaniel Borkmann 			BPF_CGROUP_RUN_PROG_UDP4_RECVMSG_LOCK(sk,
1865983695faSDaniel Borkmann 							(struct sockaddr *)sin);
1866db8dac20SDavid S. Miller 	}
1867bcd1665eSPaolo Abeni 
1868bcd1665eSPaolo Abeni 	if (udp_sk(sk)->gro_enabled)
1869bcd1665eSPaolo Abeni 		udp_cmsg_recv(msg, sk, skb);
1870bcd1665eSPaolo Abeni 
1871db8dac20SDavid S. Miller 	if (inet->cmsg_flags)
1872ad959036SPaolo Abeni 		ip_cmsg_recv_offset(msg, sk, skb, sizeof(struct udphdr), off);
1873db8dac20SDavid S. Miller 
187459c2cdaeSDavid S. Miller 	err = copied;
1875db8dac20SDavid S. Miller 	if (flags & MSG_TRUNC)
1876db8dac20SDavid S. Miller 		err = ulen;
1877db8dac20SDavid S. Miller 
1878850cbaddSPaolo Abeni 	skb_consume_udp(sk, skb, peeking ? -err : err);
1879db8dac20SDavid S. Miller 	return err;
1880db8dac20SDavid S. Miller 
1881db8dac20SDavid S. Miller csum_copy_err:
18822276f58aSPaolo Abeni 	if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags,
18832276f58aSPaolo Abeni 				 udp_skb_destructor)) {
18846aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
18856aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
18866a5dc9e5SEric Dumazet 	}
1887850cbaddSPaolo Abeni 	kfree_skb(skb);
1888db8dac20SDavid S. Miller 
1889beb39db5SEric Dumazet 	/* starting over for a new packet, but check if we need to yield */
1890beb39db5SEric Dumazet 	cond_resched();
18919cfaa8deSXufeng Zhang 	msg->msg_flags &= ~MSG_TRUNC;
1892db8dac20SDavid S. Miller 	goto try_again;
1893db8dac20SDavid S. Miller }
1894db8dac20SDavid S. Miller 
1895d74bad4eSAndrey Ignatov int udp_pre_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
1896d74bad4eSAndrey Ignatov {
1897d74bad4eSAndrey Ignatov 	/* This check is replicated from __ip4_datagram_connect() and
1898d74bad4eSAndrey Ignatov 	 * intended to prevent BPF program called below from accessing bytes
1899d74bad4eSAndrey Ignatov 	 * that are out of the bound specified by user in addr_len.
1900d74bad4eSAndrey Ignatov 	 */
1901d74bad4eSAndrey Ignatov 	if (addr_len < sizeof(struct sockaddr_in))
1902d74bad4eSAndrey Ignatov 		return -EINVAL;
1903d74bad4eSAndrey Ignatov 
1904d74bad4eSAndrey Ignatov 	return BPF_CGROUP_RUN_PROG_INET4_CONNECT_LOCK(sk, uaddr);
1905d74bad4eSAndrey Ignatov }
1906d74bad4eSAndrey Ignatov EXPORT_SYMBOL(udp_pre_connect);
1907d74bad4eSAndrey Ignatov 
1908286c72deSEric Dumazet int __udp_disconnect(struct sock *sk, int flags)
19091da177e4SLinus Torvalds {
19101da177e4SLinus Torvalds 	struct inet_sock *inet = inet_sk(sk);
19111da177e4SLinus Torvalds 	/*
19121da177e4SLinus Torvalds 	 *	1003.1g - break association.
19131da177e4SLinus Torvalds 	 */
19141da177e4SLinus Torvalds 
19151da177e4SLinus Torvalds 	sk->sk_state = TCP_CLOSE;
1916c720c7e8SEric Dumazet 	inet->inet_daddr = 0;
1917c720c7e8SEric Dumazet 	inet->inet_dport = 0;
1918bdeab991STom Herbert 	sock_rps_reset_rxhash(sk);
19191da177e4SLinus Torvalds 	sk->sk_bound_dev_if = 0;
1920303d0403SWillem de Bruijn 	if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) {
19211da177e4SLinus Torvalds 		inet_reset_saddr(sk);
1922303d0403SWillem de Bruijn 		if (sk->sk_prot->rehash &&
1923303d0403SWillem de Bruijn 		    (sk->sk_userlocks & SOCK_BINDPORT_LOCK))
1924303d0403SWillem de Bruijn 			sk->sk_prot->rehash(sk);
1925303d0403SWillem de Bruijn 	}
19261da177e4SLinus Torvalds 
19271da177e4SLinus Torvalds 	if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
19281da177e4SLinus Torvalds 		sk->sk_prot->unhash(sk);
1929c720c7e8SEric Dumazet 		inet->inet_sport = 0;
19301da177e4SLinus Torvalds 	}
19311da177e4SLinus Torvalds 	sk_dst_reset(sk);
19321da177e4SLinus Torvalds 	return 0;
19331da177e4SLinus Torvalds }
1934286c72deSEric Dumazet EXPORT_SYMBOL(__udp_disconnect);
1935286c72deSEric Dumazet 
1936286c72deSEric Dumazet int udp_disconnect(struct sock *sk, int flags)
1937286c72deSEric Dumazet {
1938286c72deSEric Dumazet 	lock_sock(sk);
1939286c72deSEric Dumazet 	__udp_disconnect(sk, flags);
1940286c72deSEric Dumazet 	release_sock(sk);
1941286c72deSEric Dumazet 	return 0;
1942286c72deSEric Dumazet }
1943c482c568SEric Dumazet EXPORT_SYMBOL(udp_disconnect);
19441da177e4SLinus Torvalds 
1945645ca708SEric Dumazet void udp_lib_unhash(struct sock *sk)
1946645ca708SEric Dumazet {
1947723b4610SEric Dumazet 	if (sk_hashed(sk)) {
1948645ca708SEric Dumazet 		struct udp_table *udptable = sk->sk_prot->h.udp_table;
1949512615b6SEric Dumazet 		struct udp_hslot *hslot, *hslot2;
1950512615b6SEric Dumazet 
1951512615b6SEric Dumazet 		hslot  = udp_hashslot(udptable, sock_net(sk),
1952d4cada4aSEric Dumazet 				      udp_sk(sk)->udp_port_hash);
1953512615b6SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
1954645ca708SEric Dumazet 
1955c8db3fecSEric Dumazet 		spin_lock_bh(&hslot->lock);
1956e32ea7e7SCraig Gallek 		if (rcu_access_pointer(sk->sk_reuseport_cb))
1957e32ea7e7SCraig Gallek 			reuseport_detach_sock(sk);
1958ca065d0cSEric Dumazet 		if (sk_del_node_init_rcu(sk)) {
1959fdcc8aa9SEric Dumazet 			hslot->count--;
1960c720c7e8SEric Dumazet 			inet_sk(sk)->inet_num = 0;
1961645ca708SEric Dumazet 			sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
1962512615b6SEric Dumazet 
1963512615b6SEric Dumazet 			spin_lock(&hslot2->lock);
1964ca065d0cSEric Dumazet 			hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
1965512615b6SEric Dumazet 			hslot2->count--;
1966512615b6SEric Dumazet 			spin_unlock(&hslot2->lock);
1967645ca708SEric Dumazet 		}
1968c8db3fecSEric Dumazet 		spin_unlock_bh(&hslot->lock);
1969645ca708SEric Dumazet 	}
1970723b4610SEric Dumazet }
1971645ca708SEric Dumazet EXPORT_SYMBOL(udp_lib_unhash);
1972645ca708SEric Dumazet 
1973719f8358SEric Dumazet /*
1974719f8358SEric Dumazet  * inet_rcv_saddr was changed, we must rehash secondary hash
1975719f8358SEric Dumazet  */
1976719f8358SEric Dumazet void udp_lib_rehash(struct sock *sk, u16 newhash)
1977719f8358SEric Dumazet {
1978719f8358SEric Dumazet 	if (sk_hashed(sk)) {
1979719f8358SEric Dumazet 		struct udp_table *udptable = sk->sk_prot->h.udp_table;
1980719f8358SEric Dumazet 		struct udp_hslot *hslot, *hslot2, *nhslot2;
1981719f8358SEric Dumazet 
1982719f8358SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
1983719f8358SEric Dumazet 		nhslot2 = udp_hashslot2(udptable, newhash);
1984719f8358SEric Dumazet 		udp_sk(sk)->udp_portaddr_hash = newhash;
1985e32ea7e7SCraig Gallek 
1986e32ea7e7SCraig Gallek 		if (hslot2 != nhslot2 ||
1987e32ea7e7SCraig Gallek 		    rcu_access_pointer(sk->sk_reuseport_cb)) {
1988719f8358SEric Dumazet 			hslot = udp_hashslot(udptable, sock_net(sk),
1989719f8358SEric Dumazet 					     udp_sk(sk)->udp_port_hash);
1990719f8358SEric Dumazet 			/* we must lock primary chain too */
1991719f8358SEric Dumazet 			spin_lock_bh(&hslot->lock);
1992e32ea7e7SCraig Gallek 			if (rcu_access_pointer(sk->sk_reuseport_cb))
1993e32ea7e7SCraig Gallek 				reuseport_detach_sock(sk);
1994719f8358SEric Dumazet 
1995e32ea7e7SCraig Gallek 			if (hslot2 != nhslot2) {
1996719f8358SEric Dumazet 				spin_lock(&hslot2->lock);
1997ca065d0cSEric Dumazet 				hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
1998719f8358SEric Dumazet 				hslot2->count--;
1999719f8358SEric Dumazet 				spin_unlock(&hslot2->lock);
2000719f8358SEric Dumazet 
2001719f8358SEric Dumazet 				spin_lock(&nhslot2->lock);
2002ca065d0cSEric Dumazet 				hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
2003719f8358SEric Dumazet 							 &nhslot2->head);
2004719f8358SEric Dumazet 				nhslot2->count++;
2005719f8358SEric Dumazet 				spin_unlock(&nhslot2->lock);
2006e32ea7e7SCraig Gallek 			}
2007719f8358SEric Dumazet 
2008719f8358SEric Dumazet 			spin_unlock_bh(&hslot->lock);
2009719f8358SEric Dumazet 		}
2010719f8358SEric Dumazet 	}
2011719f8358SEric Dumazet }
2012719f8358SEric Dumazet EXPORT_SYMBOL(udp_lib_rehash);
2013719f8358SEric Dumazet 
20148f6b5392SAlexey Kodanev void udp_v4_rehash(struct sock *sk)
2015719f8358SEric Dumazet {
2016f0b1e64cSMartin KaFai Lau 	u16 new_hash = ipv4_portaddr_hash(sock_net(sk),
2017719f8358SEric Dumazet 					  inet_sk(sk)->inet_rcv_saddr,
2018719f8358SEric Dumazet 					  inet_sk(sk)->inet_num);
2019719f8358SEric Dumazet 	udp_lib_rehash(sk, new_hash);
2020719f8358SEric Dumazet }
2021719f8358SEric Dumazet 
2022a3f96c47SPaolo Abeni static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
202393821778SHerbert Xu {
2024fec5e652STom Herbert 	int rc;
202593821778SHerbert Xu 
2026005ec974SShawn Bohrer 	if (inet_sk(sk)->inet_daddr) {
2027bdeab991STom Herbert 		sock_rps_save_rxhash(sk, skb);
2028005ec974SShawn Bohrer 		sk_mark_napi_id(sk, skb);
20292c8c56e1SEric Dumazet 		sk_incoming_cpu_update(sk);
2030e68b6e50SEric Dumazet 	} else {
2031e68b6e50SEric Dumazet 		sk_mark_napi_id_once(sk, skb);
2032005ec974SShawn Bohrer 	}
2033fec5e652STom Herbert 
2034850cbaddSPaolo Abeni 	rc = __udp_enqueue_schedule_skb(sk, skb);
2035766e9037SEric Dumazet 	if (rc < 0) {
2036766e9037SEric Dumazet 		int is_udplite = IS_UDPLITE(sk);
2037766e9037SEric Dumazet 
203893821778SHerbert Xu 		/* Note that an ENOMEM error is charged twice */
2039766e9037SEric Dumazet 		if (rc == -ENOMEM)
2040e61da9e2SEric Dumazet 			UDP_INC_STATS(sock_net(sk), UDP_MIB_RCVBUFERRORS,
204193821778SHerbert Xu 					is_udplite);
2042e61da9e2SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
2043766e9037SEric Dumazet 		kfree_skb(skb);
2044296f7ea7SSatoru Moriya 		trace_udp_fail_queue_rcv_skb(rc, sk);
2045766e9037SEric Dumazet 		return -1;
204693821778SHerbert Xu 	}
204793821778SHerbert Xu 
204893821778SHerbert Xu 	return 0;
204993821778SHerbert Xu }
205093821778SHerbert Xu 
2051db8dac20SDavid S. Miller /* returns:
2052db8dac20SDavid S. Miller  *  -1: error
2053db8dac20SDavid S. Miller  *   0: success
2054db8dac20SDavid S. Miller  *  >0: "udp encap" protocol resubmission
2055db8dac20SDavid S. Miller  *
2056db8dac20SDavid S. Miller  * Note that in the success and error cases, the skb is assumed to
2057db8dac20SDavid S. Miller  * have either been requeued or freed.
2058db8dac20SDavid S. Miller  */
2059cf329aa4SPaolo Abeni static int udp_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
2060db8dac20SDavid S. Miller {
2061db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
2062db8dac20SDavid S. Miller 	int is_udplite = IS_UDPLITE(sk);
2063db8dac20SDavid S. Miller 
2064db8dac20SDavid S. Miller 	/*
2065db8dac20SDavid S. Miller 	 *	Charge it to the socket, dropping if the queue is full.
2066db8dac20SDavid S. Miller 	 */
2067db8dac20SDavid S. Miller 	if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
2068db8dac20SDavid S. Miller 		goto drop;
2069895b5c9fSFlorian Westphal 	nf_reset_ct(skb);
2070db8dac20SDavid S. Miller 
207188ab3108SDavidlohr Bueso 	if (static_branch_unlikely(&udp_encap_needed_key) && up->encap_type) {
20720ad92ad0SEric Dumazet 		int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
20730ad92ad0SEric Dumazet 
2074db8dac20SDavid S. Miller 		/*
2075db8dac20SDavid S. Miller 		 * This is an encapsulation socket so pass the skb to
2076db8dac20SDavid S. Miller 		 * the socket's udp_encap_rcv() hook. Otherwise, just
2077db8dac20SDavid S. Miller 		 * fall through and pass this up the UDP socket.
2078db8dac20SDavid S. Miller 		 * up->encap_rcv() returns the following value:
2079db8dac20SDavid S. Miller 		 * =0 if skb was successfully passed to the encap
2080db8dac20SDavid S. Miller 		 *    handler or was discarded by it.
2081db8dac20SDavid S. Miller 		 * >0 if skb should be passed on to UDP.
2082db8dac20SDavid S. Miller 		 * <0 if skb should be resubmitted as proto -N
2083db8dac20SDavid S. Miller 		 */
2084db8dac20SDavid S. Miller 
2085db8dac20SDavid S. Miller 		/* if we're overly short, let UDP handle it */
20866aa7de05SMark Rutland 		encap_rcv = READ_ONCE(up->encap_rcv);
2087e5aed006SHannes Frederic Sowa 		if (encap_rcv) {
2088db8dac20SDavid S. Miller 			int ret;
2089db8dac20SDavid S. Miller 
20900a80966bSTom Herbert 			/* Verify checksum before giving to encap */
20910a80966bSTom Herbert 			if (udp_lib_checksum_complete(skb))
20920a80966bSTom Herbert 				goto csum_error;
20930a80966bSTom Herbert 
20940ad92ad0SEric Dumazet 			ret = encap_rcv(sk, skb);
2095db8dac20SDavid S. Miller 			if (ret <= 0) {
209602c22347SEric Dumazet 				__UDP_INC_STATS(sock_net(sk),
20970283328eSPavel Emelyanov 						UDP_MIB_INDATAGRAMS,
2098db8dac20SDavid S. Miller 						is_udplite);
2099db8dac20SDavid S. Miller 				return -ret;
2100db8dac20SDavid S. Miller 			}
2101db8dac20SDavid S. Miller 		}
2102db8dac20SDavid S. Miller 
2103db8dac20SDavid S. Miller 		/* FALLTHROUGH -- it's a UDP Packet */
2104db8dac20SDavid S. Miller 	}
2105db8dac20SDavid S. Miller 
2106db8dac20SDavid S. Miller 	/*
2107db8dac20SDavid S. Miller 	 * 	UDP-Lite specific tests, ignored on UDP sockets
2108db8dac20SDavid S. Miller 	 */
2109db8dac20SDavid S. Miller 	if ((is_udplite & UDPLITE_RECV_CC)  &&  UDP_SKB_CB(skb)->partial_cov) {
2110db8dac20SDavid S. Miller 
2111db8dac20SDavid S. Miller 		/*
2112db8dac20SDavid S. Miller 		 * MIB statistics other than incrementing the error count are
2113db8dac20SDavid S. Miller 		 * disabled for the following two types of errors: these depend
2114db8dac20SDavid S. Miller 		 * on the application settings, not on the functioning of the
2115db8dac20SDavid S. Miller 		 * protocol stack as such.
2116db8dac20SDavid S. Miller 		 *
2117db8dac20SDavid S. Miller 		 * RFC 3828 here recommends (sec 3.3): "There should also be a
2118db8dac20SDavid S. Miller 		 * way ... to ... at least let the receiving application block
2119db8dac20SDavid S. Miller 		 * delivery of packets with coverage values less than a value
2120db8dac20SDavid S. Miller 		 * provided by the application."
2121db8dac20SDavid S. Miller 		 */
2122db8dac20SDavid S. Miller 		if (up->pcrlen == 0) {          /* full coverage was set  */
2123ba7a46f1SJoe Perches 			net_dbg_ratelimited("UDPLite: partial coverage %d while full coverage %d requested\n",
2124db8dac20SDavid S. Miller 					    UDP_SKB_CB(skb)->cscov, skb->len);
2125db8dac20SDavid S. Miller 			goto drop;
2126db8dac20SDavid S. Miller 		}
2127db8dac20SDavid S. Miller 		/* The next case involves violating the min. coverage requested
2128db8dac20SDavid S. Miller 		 * by the receiver. This is subtle: if receiver wants x and x is
2129db8dac20SDavid S. Miller 		 * greater than the buffersize/MTU then receiver will complain
2130db8dac20SDavid S. Miller 		 * that it wants x while sender emits packets of smaller size y.
2131db8dac20SDavid S. Miller 		 * Therefore the above ...()->partial_cov statement is essential.
2132db8dac20SDavid S. Miller 		 */
2133db8dac20SDavid S. Miller 		if (UDP_SKB_CB(skb)->cscov  <  up->pcrlen) {
2134ba7a46f1SJoe Perches 			net_dbg_ratelimited("UDPLite: coverage %d too small, need min %d\n",
2135db8dac20SDavid S. Miller 					    UDP_SKB_CB(skb)->cscov, up->pcrlen);
2136db8dac20SDavid S. Miller 			goto drop;
2137db8dac20SDavid S. Miller 		}
2138db8dac20SDavid S. Miller 	}
2139db8dac20SDavid S. Miller 
2140dd99e425SPaolo Abeni 	prefetch(&sk->sk_rmem_alloc);
2141ce25d66aSEric Dumazet 	if (rcu_access_pointer(sk->sk_filter) &&
2142ce25d66aSEric Dumazet 	    udp_lib_checksum_complete(skb))
21436a5dc9e5SEric Dumazet 			goto csum_error;
2144ce25d66aSEric Dumazet 
2145ba66bbe5SDaniel Borkmann 	if (sk_filter_trim_cap(sk, skb, sizeof(struct udphdr)))
2146a6127697SMichal Kubeček 		goto drop;
2147db8dac20SDavid S. Miller 
2148e6afc8acSsamanthakumar 	udp_csum_pull_header(skb);
2149db8dac20SDavid S. Miller 
2150fbf8866dSShawn Bohrer 	ipv4_pktinfo_prepare(sk, skb);
2151850cbaddSPaolo Abeni 	return __udp_queue_rcv_skb(sk, skb);
2152db8dac20SDavid S. Miller 
21536a5dc9e5SEric Dumazet csum_error:
215402c22347SEric Dumazet 	__UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
2155db8dac20SDavid S. Miller drop:
215602c22347SEric Dumazet 	__UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
21578edf19c2SEric Dumazet 	atomic_inc(&sk->sk_drops);
2158db8dac20SDavid S. Miller 	kfree_skb(skb);
2159db8dac20SDavid S. Miller 	return -1;
2160db8dac20SDavid S. Miller }
2161db8dac20SDavid S. Miller 
2162cf329aa4SPaolo Abeni static int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2163cf329aa4SPaolo Abeni {
2164cf329aa4SPaolo Abeni 	struct sk_buff *next, *segs;
2165cf329aa4SPaolo Abeni 	int ret;
2166cf329aa4SPaolo Abeni 
2167cf329aa4SPaolo Abeni 	if (likely(!udp_unexpected_gso(sk, skb)))
2168cf329aa4SPaolo Abeni 		return udp_queue_rcv_one_skb(sk, skb);
2169cf329aa4SPaolo Abeni 
2170a08e7fd9SCambda Zhu 	BUILD_BUG_ON(sizeof(struct udp_skb_cb) > SKB_GSO_CB_OFFSET);
2171cf329aa4SPaolo Abeni 	__skb_push(skb, -skb_mac_offset(skb));
2172cf329aa4SPaolo Abeni 	segs = udp_rcv_segment(sk, skb, true);
21731a186c14SJason A. Donenfeld 	skb_list_walk_safe(segs, skb, next) {
2174cf329aa4SPaolo Abeni 		__skb_pull(skb, skb_transport_offset(skb));
2175cf329aa4SPaolo Abeni 		ret = udp_queue_rcv_one_skb(sk, skb);
2176cf329aa4SPaolo Abeni 		if (ret > 0)
2177cf329aa4SPaolo Abeni 			ip_protocol_deliver_rcu(dev_net(skb->dev), skb, -ret);
2178cf329aa4SPaolo Abeni 	}
2179cf329aa4SPaolo Abeni 	return 0;
2180cf329aa4SPaolo Abeni }
2181cf329aa4SPaolo Abeni 
218297502231SEric Dumazet /* For TCP sockets, sk_rx_dst is protected by socket lock
2183e47eb5dfSEric Dumazet  * For UDP, we use xchg() to guard against concurrent changes.
218497502231SEric Dumazet  */
218564f0f5d1SPaolo Abeni bool udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
2186421b3885SShawn Bohrer {
218797502231SEric Dumazet 	struct dst_entry *old;
2188421b3885SShawn Bohrer 
2189d24406c8SWei Wang 	if (dst_hold_safe(dst)) {
2190e47eb5dfSEric Dumazet 		old = xchg(&sk->sk_rx_dst, dst);
219197502231SEric Dumazet 		dst_release(old);
219264f0f5d1SPaolo Abeni 		return old != dst;
219397502231SEric Dumazet 	}
219464f0f5d1SPaolo Abeni 	return false;
2195d24406c8SWei Wang }
2196c9f2c1aeSPaolo Abeni EXPORT_SYMBOL(udp_sk_rx_dst_set);
2197421b3885SShawn Bohrer 
2198db8dac20SDavid S. Miller /*
2199db8dac20SDavid S. Miller  *	Multicasts and broadcasts go to each listener.
2200db8dac20SDavid S. Miller  *
22011240d137SEric Dumazet  *	Note: called only from the BH handler context.
2202db8dac20SDavid S. Miller  */
2203e3163493SPavel Emelyanov static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
2204db8dac20SDavid S. Miller 				    struct udphdr  *uh,
2205db8dac20SDavid S. Miller 				    __be32 saddr, __be32 daddr,
220636cbb245SRick Jones 				    struct udp_table *udptable,
220736cbb245SRick Jones 				    int proto)
2208db8dac20SDavid S. Miller {
2209ca065d0cSEric Dumazet 	struct sock *sk, *first = NULL;
22105cf3d461SDavid Held 	unsigned short hnum = ntohs(uh->dest);
22115cf3d461SDavid Held 	struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum);
22122dc41cffSDavid Held 	unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10);
2213ca065d0cSEric Dumazet 	unsigned int offset = offsetof(typeof(*sk), sk_node);
2214ca065d0cSEric Dumazet 	int dif = skb->dev->ifindex;
2215fb74c277SDavid Ahern 	int sdif = inet_sdif(skb);
2216ca065d0cSEric Dumazet 	struct hlist_node *node;
2217ca065d0cSEric Dumazet 	struct sk_buff *nskb;
22182dc41cffSDavid Held 
22192dc41cffSDavid Held 	if (use_hash2) {
2220f0b1e64cSMartin KaFai Lau 		hash2_any = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum) &
222173e2d5e3SPablo Neira 			    udptable->mask;
2222f0b1e64cSMartin KaFai Lau 		hash2 = ipv4_portaddr_hash(net, daddr, hnum) & udptable->mask;
22232dc41cffSDavid Held start_lookup:
222473e2d5e3SPablo Neira 		hslot = &udptable->hash2[hash2];
22252dc41cffSDavid Held 		offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
22262dc41cffSDavid Held 	}
2227db8dac20SDavid S. Miller 
2228ca065d0cSEric Dumazet 	sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
2229ca065d0cSEric Dumazet 		if (!__udp_is_mcast_sock(net, sk, uh->dest, daddr,
2230fb74c277SDavid Ahern 					 uh->source, saddr, dif, sdif, hnum))
2231ca065d0cSEric Dumazet 			continue;
22321240d137SEric Dumazet 
2233ca065d0cSEric Dumazet 		if (!first) {
2234ca065d0cSEric Dumazet 			first = sk;
2235ca065d0cSEric Dumazet 			continue;
2236ca065d0cSEric Dumazet 		}
2237ca065d0cSEric Dumazet 		nskb = skb_clone(skb, GFP_ATOMIC);
2238ca065d0cSEric Dumazet 
2239ca065d0cSEric Dumazet 		if (unlikely(!nskb)) {
2240ca065d0cSEric Dumazet 			atomic_inc(&sk->sk_drops);
224102c22347SEric Dumazet 			__UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS,
2242ca065d0cSEric Dumazet 					IS_UDPLITE(sk));
224302c22347SEric Dumazet 			__UDP_INC_STATS(net, UDP_MIB_INERRORS,
2244ca065d0cSEric Dumazet 					IS_UDPLITE(sk));
2245ca065d0cSEric Dumazet 			continue;
2246ca065d0cSEric Dumazet 		}
2247ca065d0cSEric Dumazet 		if (udp_queue_rcv_skb(sk, nskb) > 0)
2248ca065d0cSEric Dumazet 			consume_skb(nskb);
2249ca065d0cSEric Dumazet 	}
22501240d137SEric Dumazet 
22512dc41cffSDavid Held 	/* Also lookup *:port if we are using hash2 and haven't done so yet. */
22522dc41cffSDavid Held 	if (use_hash2 && hash2 != hash2_any) {
22532dc41cffSDavid Held 		hash2 = hash2_any;
22542dc41cffSDavid Held 		goto start_lookup;
22552dc41cffSDavid Held 	}
22562dc41cffSDavid Held 
2257ca065d0cSEric Dumazet 	if (first) {
2258ca065d0cSEric Dumazet 		if (udp_queue_rcv_skb(first, skb) > 0)
2259ca065d0cSEric Dumazet 			consume_skb(skb);
22601240d137SEric Dumazet 	} else {
2261ca065d0cSEric Dumazet 		kfree_skb(skb);
226202c22347SEric Dumazet 		__UDP_INC_STATS(net, UDP_MIB_IGNOREDMULTI,
226336cbb245SRick Jones 				proto == IPPROTO_UDPLITE);
22641240d137SEric Dumazet 	}
2265db8dac20SDavid S. Miller 	return 0;
2266db8dac20SDavid S. Miller }
2267db8dac20SDavid S. Miller 
2268db8dac20SDavid S. Miller /* Initialize UDP checksum. If exited with zero value (success),
2269db8dac20SDavid S. Miller  * CHECKSUM_UNNECESSARY means, that no more checks are required.
2270666a3d6eSSu Yanjun  * Otherwise, csum completion requires checksumming packet body,
2271db8dac20SDavid S. Miller  * including udp header and folding it to skb->csum.
2272db8dac20SDavid S. Miller  */
2273db8dac20SDavid S. Miller static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
2274db8dac20SDavid S. Miller 				 int proto)
2275db8dac20SDavid S. Miller {
2276db8dac20SDavid S. Miller 	int err;
2277db8dac20SDavid S. Miller 
2278db8dac20SDavid S. Miller 	UDP_SKB_CB(skb)->partial_cov = 0;
2279db8dac20SDavid S. Miller 	UDP_SKB_CB(skb)->cscov = skb->len;
2280db8dac20SDavid S. Miller 
2281db8dac20SDavid S. Miller 	if (proto == IPPROTO_UDPLITE) {
2282db8dac20SDavid S. Miller 		err = udplite_checksum_init(skb, uh);
2283db8dac20SDavid S. Miller 		if (err)
2284db8dac20SDavid S. Miller 			return err;
228515f35d49SAlexey Kodanev 
228615f35d49SAlexey Kodanev 		if (UDP_SKB_CB(skb)->partial_cov) {
228715f35d49SAlexey Kodanev 			skb->csum = inet_compute_pseudo(skb, proto);
228815f35d49SAlexey Kodanev 			return 0;
228915f35d49SAlexey Kodanev 		}
2290db8dac20SDavid S. Miller 	}
2291db8dac20SDavid S. Miller 
2292b46d9f62SHannes Frederic Sowa 	/* Note, we are only interested in != 0 or == 0, thus the
2293b46d9f62SHannes Frederic Sowa 	 * force to int.
2294b46d9f62SHannes Frederic Sowa 	 */
2295db4f1be3SSean Tranchetti 	err = (__force int)skb_checksum_init_zero_check(skb, proto, uh->check,
2296ed70fcfcSTom Herbert 							inet_compute_pseudo);
2297db4f1be3SSean Tranchetti 	if (err)
2298db4f1be3SSean Tranchetti 		return err;
2299db4f1be3SSean Tranchetti 
2300db4f1be3SSean Tranchetti 	if (skb->ip_summed == CHECKSUM_COMPLETE && !skb->csum_valid) {
2301db4f1be3SSean Tranchetti 		/* If SW calculated the value, we know it's bad */
2302db4f1be3SSean Tranchetti 		if (skb->csum_complete_sw)
2303db4f1be3SSean Tranchetti 			return 1;
2304db4f1be3SSean Tranchetti 
2305db4f1be3SSean Tranchetti 		/* HW says the value is bad. Let's validate that.
2306db4f1be3SSean Tranchetti 		 * skb->csum is no longer the full packet checksum,
2307db4f1be3SSean Tranchetti 		 * so don't treat it as such.
2308db4f1be3SSean Tranchetti 		 */
2309db4f1be3SSean Tranchetti 		skb_checksum_complete_unset(skb);
2310db4f1be3SSean Tranchetti 	}
2311db4f1be3SSean Tranchetti 
2312db4f1be3SSean Tranchetti 	return 0;
2313db8dac20SDavid S. Miller }
2314db8dac20SDavid S. Miller 
23152b5a9217SPaolo Abeni /* wrapper for udp_queue_rcv_skb tacking care of csum conversion and
23162b5a9217SPaolo Abeni  * return code conversion for ip layer consumption
23172b5a9217SPaolo Abeni  */
23182b5a9217SPaolo Abeni static int udp_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb,
23192b5a9217SPaolo Abeni 			       struct udphdr *uh)
23202b5a9217SPaolo Abeni {
23212b5a9217SPaolo Abeni 	int ret;
23222b5a9217SPaolo Abeni 
23232b5a9217SPaolo Abeni 	if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk))
2324e4aa33adSLi RongQing 		skb_checksum_try_convert(skb, IPPROTO_UDP, inet_compute_pseudo);
23252b5a9217SPaolo Abeni 
23262b5a9217SPaolo Abeni 	ret = udp_queue_rcv_skb(sk, skb);
23272b5a9217SPaolo Abeni 
23282b5a9217SPaolo Abeni 	/* a return value > 0 means to resubmit the input, but
23292b5a9217SPaolo Abeni 	 * it wants the return to be -protocol, or 0
23302b5a9217SPaolo Abeni 	 */
23312b5a9217SPaolo Abeni 	if (ret > 0)
23322b5a9217SPaolo Abeni 		return -ret;
23332b5a9217SPaolo Abeni 	return 0;
23342b5a9217SPaolo Abeni }
23352b5a9217SPaolo Abeni 
2336db8dac20SDavid S. Miller /*
2337db8dac20SDavid S. Miller  *	All we need to do is get the socket, and then do a checksum.
2338db8dac20SDavid S. Miller  */
2339db8dac20SDavid S. Miller 
2340645ca708SEric Dumazet int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
2341db8dac20SDavid S. Miller 		   int proto)
2342db8dac20SDavid S. Miller {
2343db8dac20SDavid S. Miller 	struct sock *sk;
23447b5e56f9SJesper Dangaard Brouer 	struct udphdr *uh;
2345db8dac20SDavid S. Miller 	unsigned short ulen;
2346adf30907SEric Dumazet 	struct rtable *rt = skb_rtable(skb);
23472783ef23SJesper Dangaard Brouer 	__be32 saddr, daddr;
23480283328eSPavel Emelyanov 	struct net *net = dev_net(skb->dev);
234971489e21SJoe Stringer 	bool refcounted;
2350db8dac20SDavid S. Miller 
2351db8dac20SDavid S. Miller 	/*
2352db8dac20SDavid S. Miller 	 *  Validate the packet.
2353db8dac20SDavid S. Miller 	 */
2354db8dac20SDavid S. Miller 	if (!pskb_may_pull(skb, sizeof(struct udphdr)))
2355db8dac20SDavid S. Miller 		goto drop;		/* No space for header. */
2356db8dac20SDavid S. Miller 
23577b5e56f9SJesper Dangaard Brouer 	uh   = udp_hdr(skb);
2358db8dac20SDavid S. Miller 	ulen = ntohs(uh->len);
2359ccc2d97cSBjørn Mork 	saddr = ip_hdr(skb)->saddr;
2360ccc2d97cSBjørn Mork 	daddr = ip_hdr(skb)->daddr;
2361ccc2d97cSBjørn Mork 
2362db8dac20SDavid S. Miller 	if (ulen > skb->len)
2363db8dac20SDavid S. Miller 		goto short_packet;
2364db8dac20SDavid S. Miller 
2365db8dac20SDavid S. Miller 	if (proto == IPPROTO_UDP) {
2366db8dac20SDavid S. Miller 		/* UDP validates ulen. */
2367db8dac20SDavid S. Miller 		if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
2368db8dac20SDavid S. Miller 			goto short_packet;
2369db8dac20SDavid S. Miller 		uh = udp_hdr(skb);
2370db8dac20SDavid S. Miller 	}
2371db8dac20SDavid S. Miller 
2372db8dac20SDavid S. Miller 	if (udp4_csum_init(skb, uh, proto))
2373db8dac20SDavid S. Miller 		goto csum_error;
2374db8dac20SDavid S. Miller 
237571489e21SJoe Stringer 	sk = skb_steal_sock(skb, &refcounted);
23768afdd99aSEric Dumazet 	if (sk) {
237797502231SEric Dumazet 		struct dst_entry *dst = skb_dst(skb);
2378421b3885SShawn Bohrer 		int ret;
2379421b3885SShawn Bohrer 
238097502231SEric Dumazet 		if (unlikely(sk->sk_rx_dst != dst))
238197502231SEric Dumazet 			udp_sk_rx_dst_set(sk, dst);
2382421b3885SShawn Bohrer 
23832b5a9217SPaolo Abeni 		ret = udp_unicast_rcv_skb(sk, skb, uh);
238471489e21SJoe Stringer 		if (refcounted)
23858afdd99aSEric Dumazet 			sock_put(sk);
23862b5a9217SPaolo Abeni 		return ret;
2387c18450a5SFabian Frederick 	}
2388c18450a5SFabian Frederick 
2389db8dac20SDavid S. Miller 	if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
2390e3163493SPavel Emelyanov 		return __udp4_lib_mcast_deliver(net, skb, uh,
239136cbb245SRick Jones 						saddr, daddr, udptable, proto);
2392db8dac20SDavid S. Miller 
2393607c4aafSKOVACS Krisztian 	sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
23942b5a9217SPaolo Abeni 	if (sk)
23952b5a9217SPaolo Abeni 		return udp_unicast_rcv_skb(sk, skb, uh);
2396db8dac20SDavid S. Miller 
2397db8dac20SDavid S. Miller 	if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
2398db8dac20SDavid S. Miller 		goto drop;
2399895b5c9fSFlorian Westphal 	nf_reset_ct(skb);
2400db8dac20SDavid S. Miller 
2401db8dac20SDavid S. Miller 	/* No socket. Drop packet silently, if checksum is wrong */
2402db8dac20SDavid S. Miller 	if (udp_lib_checksum_complete(skb))
2403db8dac20SDavid S. Miller 		goto csum_error;
2404db8dac20SDavid S. Miller 
240502c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
2406db8dac20SDavid S. Miller 	icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
2407db8dac20SDavid S. Miller 
2408db8dac20SDavid S. Miller 	/*
2409db8dac20SDavid S. Miller 	 * Hmm.  We got an UDP packet to a port to which we
2410db8dac20SDavid S. Miller 	 * don't wanna listen.  Ignore it.
2411db8dac20SDavid S. Miller 	 */
2412db8dac20SDavid S. Miller 	kfree_skb(skb);
2413db8dac20SDavid S. Miller 	return 0;
2414db8dac20SDavid S. Miller 
2415db8dac20SDavid S. Miller short_packet:
2416ba7a46f1SJoe Perches 	net_dbg_ratelimited("UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
2417afd46503SJoe Perches 			    proto == IPPROTO_UDPLITE ? "Lite" : "",
2418afd46503SJoe Perches 			    &saddr, ntohs(uh->source),
2419afd46503SJoe Perches 			    ulen, skb->len,
2420afd46503SJoe Perches 			    &daddr, ntohs(uh->dest));
2421db8dac20SDavid S. Miller 	goto drop;
2422db8dac20SDavid S. Miller 
2423db8dac20SDavid S. Miller csum_error:
2424db8dac20SDavid S. Miller 	/*
2425db8dac20SDavid S. Miller 	 * RFC1122: OK.  Discards the bad packet silently (as far as
2426db8dac20SDavid S. Miller 	 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
2427db8dac20SDavid S. Miller 	 */
2428ba7a46f1SJoe Perches 	net_dbg_ratelimited("UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
2429afd46503SJoe Perches 			    proto == IPPROTO_UDPLITE ? "Lite" : "",
2430afd46503SJoe Perches 			    &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
2431db8dac20SDavid S. Miller 			    ulen);
243202c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
2433db8dac20SDavid S. Miller drop:
243402c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
2435db8dac20SDavid S. Miller 	kfree_skb(skb);
2436db8dac20SDavid S. Miller 	return 0;
2437db8dac20SDavid S. Miller }
2438db8dac20SDavid S. Miller 
2439421b3885SShawn Bohrer /* We can only early demux multicast if there is a single matching socket.
2440421b3885SShawn Bohrer  * If more than one socket found returns NULL
2441421b3885SShawn Bohrer  */
2442421b3885SShawn Bohrer static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net,
2443421b3885SShawn Bohrer 						  __be16 loc_port, __be32 loc_addr,
2444421b3885SShawn Bohrer 						  __be16 rmt_port, __be32 rmt_addr,
2445fb74c277SDavid Ahern 						  int dif, int sdif)
2446421b3885SShawn Bohrer {
2447421b3885SShawn Bohrer 	struct sock *sk, *result;
2448421b3885SShawn Bohrer 	unsigned short hnum = ntohs(loc_port);
2449ca065d0cSEric Dumazet 	unsigned int slot = udp_hashfn(net, hnum, udp_table.mask);
2450421b3885SShawn Bohrer 	struct udp_hslot *hslot = &udp_table.hash[slot];
2451421b3885SShawn Bohrer 
245263c6f81cSEric Dumazet 	/* Do not bother scanning a too big list */
245363c6f81cSEric Dumazet 	if (hslot->count > 10)
245463c6f81cSEric Dumazet 		return NULL;
245563c6f81cSEric Dumazet 
2456421b3885SShawn Bohrer 	result = NULL;
2457ca065d0cSEric Dumazet 	sk_for_each_rcu(sk, &hslot->head) {
2458ca065d0cSEric Dumazet 		if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr,
2459fb74c277SDavid Ahern 					rmt_port, rmt_addr, dif, sdif, hnum)) {
2460ca065d0cSEric Dumazet 			if (result)
2461ca065d0cSEric Dumazet 				return NULL;
2462421b3885SShawn Bohrer 			result = sk;
2463421b3885SShawn Bohrer 		}
2464421b3885SShawn Bohrer 	}
2465421b3885SShawn Bohrer 
2466421b3885SShawn Bohrer 	return result;
2467421b3885SShawn Bohrer }
2468421b3885SShawn Bohrer 
2469421b3885SShawn Bohrer /* For unicast we should only early demux connected sockets or we can
2470421b3885SShawn Bohrer  * break forwarding setups.  The chains here can be long so only check
2471421b3885SShawn Bohrer  * if the first socket is an exact match and if not move on.
2472421b3885SShawn Bohrer  */
2473421b3885SShawn Bohrer static struct sock *__udp4_lib_demux_lookup(struct net *net,
2474421b3885SShawn Bohrer 					    __be16 loc_port, __be32 loc_addr,
2475421b3885SShawn Bohrer 					    __be16 rmt_port, __be32 rmt_addr,
24763fa6f616SDavid Ahern 					    int dif, int sdif)
2477421b3885SShawn Bohrer {
2478421b3885SShawn Bohrer 	unsigned short hnum = ntohs(loc_port);
2479f0b1e64cSMartin KaFai Lau 	unsigned int hash2 = ipv4_portaddr_hash(net, loc_addr, hnum);
2480421b3885SShawn Bohrer 	unsigned int slot2 = hash2 & udp_table.mask;
2481421b3885SShawn Bohrer 	struct udp_hslot *hslot2 = &udp_table.hash2[slot2];
2482c7228317SJoe Perches 	INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr);
2483421b3885SShawn Bohrer 	const __portpair ports = INET_COMBINED_PORTS(rmt_port, hnum);
2484ca065d0cSEric Dumazet 	struct sock *sk;
2485421b3885SShawn Bohrer 
2486ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
2487ca065d0cSEric Dumazet 		if (INET_MATCH(sk, net, acookie, rmt_addr,
24883fa6f616SDavid Ahern 			       loc_addr, ports, dif, sdif))
2489ca065d0cSEric Dumazet 			return sk;
2490421b3885SShawn Bohrer 		/* Only check first socket in chain */
2491421b3885SShawn Bohrer 		break;
2492421b3885SShawn Bohrer 	}
2493ca065d0cSEric Dumazet 	return NULL;
2494421b3885SShawn Bohrer }
2495421b3885SShawn Bohrer 
24967487449cSPaolo Abeni int udp_v4_early_demux(struct sk_buff *skb)
2497421b3885SShawn Bohrer {
2498610438b7SEric Dumazet 	struct net *net = dev_net(skb->dev);
2499bc044e8dSPaolo Abeni 	struct in_device *in_dev = NULL;
2500610438b7SEric Dumazet 	const struct iphdr *iph;
2501610438b7SEric Dumazet 	const struct udphdr *uh;
2502ca065d0cSEric Dumazet 	struct sock *sk = NULL;
2503421b3885SShawn Bohrer 	struct dst_entry *dst;
2504421b3885SShawn Bohrer 	int dif = skb->dev->ifindex;
2505fb74c277SDavid Ahern 	int sdif = inet_sdif(skb);
25066e540309SShawn Bohrer 	int ours;
2507421b3885SShawn Bohrer 
2508421b3885SShawn Bohrer 	/* validate the packet */
2509421b3885SShawn Bohrer 	if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)))
25107487449cSPaolo Abeni 		return 0;
2511421b3885SShawn Bohrer 
2512610438b7SEric Dumazet 	iph = ip_hdr(skb);
2513610438b7SEric Dumazet 	uh = udp_hdr(skb);
2514610438b7SEric Dumazet 
2515996b44fcSPaolo Abeni 	if (skb->pkt_type == PACKET_MULTICAST) {
2516bc044e8dSPaolo Abeni 		in_dev = __in_dev_get_rcu(skb->dev);
25176e540309SShawn Bohrer 
25186e540309SShawn Bohrer 		if (!in_dev)
25197487449cSPaolo Abeni 			return 0;
25206e540309SShawn Bohrer 
25216e540309SShawn Bohrer 		ours = ip_check_mc_rcu(in_dev, iph->daddr, iph->saddr,
25226e540309SShawn Bohrer 				       iph->protocol);
25236e540309SShawn Bohrer 		if (!ours)
25247487449cSPaolo Abeni 			return 0;
2525ad0ea198SPaolo Abeni 
2526421b3885SShawn Bohrer 		sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr,
2527fb74c277SDavid Ahern 						   uh->source, iph->saddr,
2528fb74c277SDavid Ahern 						   dif, sdif);
25296e540309SShawn Bohrer 	} else if (skb->pkt_type == PACKET_HOST) {
2530421b3885SShawn Bohrer 		sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr,
25313fa6f616SDavid Ahern 					     uh->source, iph->saddr, dif, sdif);
25326e540309SShawn Bohrer 	}
2533421b3885SShawn Bohrer 
253441c6d650SReshetova, Elena 	if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
25357487449cSPaolo Abeni 		return 0;
2536421b3885SShawn Bohrer 
2537421b3885SShawn Bohrer 	skb->sk = sk;
253882eabd9eSAlexander Duyck 	skb->destructor = sock_efree;
253910e2eb87SEric Dumazet 	dst = READ_ONCE(sk->sk_rx_dst);
2540421b3885SShawn Bohrer 
2541421b3885SShawn Bohrer 	if (dst)
2542421b3885SShawn Bohrer 		dst = dst_check(dst, 0);
254310e2eb87SEric Dumazet 	if (dst) {
2544bc044e8dSPaolo Abeni 		u32 itag = 0;
2545bc044e8dSPaolo Abeni 
2546d24406c8SWei Wang 		/* set noref for now.
2547d24406c8SWei Wang 		 * any place which wants to hold dst has to call
2548d24406c8SWei Wang 		 * dst_hold_safe()
2549d24406c8SWei Wang 		 */
2550421b3885SShawn Bohrer 		skb_dst_set_noref(skb, dst);
2551bc044e8dSPaolo Abeni 
2552bc044e8dSPaolo Abeni 		/* for unconnected multicast sockets we need to validate
2553bc044e8dSPaolo Abeni 		 * the source on each packet
2554bc044e8dSPaolo Abeni 		 */
2555bc044e8dSPaolo Abeni 		if (!inet_sk(sk)->inet_daddr && in_dev)
2556bc044e8dSPaolo Abeni 			return ip_mc_validate_source(skb, iph->daddr,
2557bc044e8dSPaolo Abeni 						     iph->saddr, iph->tos,
2558bc044e8dSPaolo Abeni 						     skb->dev, in_dev, &itag);
2559421b3885SShawn Bohrer 	}
25607487449cSPaolo Abeni 	return 0;
256110e2eb87SEric Dumazet }
2562421b3885SShawn Bohrer 
2563db8dac20SDavid S. Miller int udp_rcv(struct sk_buff *skb)
2564db8dac20SDavid S. Miller {
2565645ca708SEric Dumazet 	return __udp4_lib_rcv(skb, &udp_table, IPPROTO_UDP);
2566db8dac20SDavid S. Miller }
2567db8dac20SDavid S. Miller 
25687d06b2e0SBrian Haley void udp_destroy_sock(struct sock *sk)
2569db8dac20SDavid S. Miller {
257044046a59STom Parkin 	struct udp_sock *up = udp_sk(sk);
25718a74ad60SEric Dumazet 	bool slow = lock_sock_fast(sk);
2572db8dac20SDavid S. Miller 	udp_flush_pending_frames(sk);
25738a74ad60SEric Dumazet 	unlock_sock_fast(sk, slow);
257460fb9567SPaolo Abeni 	if (static_branch_unlikely(&udp_encap_needed_key)) {
257560fb9567SPaolo Abeni 		if (up->encap_type) {
257644046a59STom Parkin 			void (*encap_destroy)(struct sock *sk);
25776aa7de05SMark Rutland 			encap_destroy = READ_ONCE(up->encap_destroy);
257844046a59STom Parkin 			if (encap_destroy)
257944046a59STom Parkin 				encap_destroy(sk);
258044046a59STom Parkin 		}
258160fb9567SPaolo Abeni 		if (up->encap_enabled)
25829c480601SPaolo Abeni 			static_branch_dec(&udp_encap_needed_key);
258360fb9567SPaolo Abeni 	}
2584db8dac20SDavid S. Miller }
2585db8dac20SDavid S. Miller 
25861da177e4SLinus Torvalds /*
25871da177e4SLinus Torvalds  *	Socket option code for UDP
25881da177e4SLinus Torvalds  */
25894c0a6cb0SGerrit Renker int udp_lib_setsockopt(struct sock *sk, int level, int optname,
2590b7058842SDavid S. Miller 		       char __user *optval, unsigned int optlen,
25914c0a6cb0SGerrit Renker 		       int (*push_pending_frames)(struct sock *))
25921da177e4SLinus Torvalds {
25931da177e4SLinus Torvalds 	struct udp_sock *up = udp_sk(sk);
25941c19448cSTom Herbert 	int val, valbool;
25951da177e4SLinus Torvalds 	int err = 0;
2596b2bf1e26SWang Chen 	int is_udplite = IS_UDPLITE(sk);
25971da177e4SLinus Torvalds 
25981da177e4SLinus Torvalds 	if (optlen < sizeof(int))
25991da177e4SLinus Torvalds 		return -EINVAL;
26001da177e4SLinus Torvalds 
26011da177e4SLinus Torvalds 	if (get_user(val, (int __user *)optval))
26021da177e4SLinus Torvalds 		return -EFAULT;
26031da177e4SLinus Torvalds 
26041c19448cSTom Herbert 	valbool = val ? 1 : 0;
26051c19448cSTom Herbert 
26061da177e4SLinus Torvalds 	switch (optname) {
26071da177e4SLinus Torvalds 	case UDP_CORK:
26081da177e4SLinus Torvalds 		if (val != 0) {
26091da177e4SLinus Torvalds 			up->corkflag = 1;
26101da177e4SLinus Torvalds 		} else {
26111da177e4SLinus Torvalds 			up->corkflag = 0;
26121da177e4SLinus Torvalds 			lock_sock(sk);
26134243cdc2SJoe Perches 			push_pending_frames(sk);
26141da177e4SLinus Torvalds 			release_sock(sk);
26151da177e4SLinus Torvalds 		}
26161da177e4SLinus Torvalds 		break;
26171da177e4SLinus Torvalds 
26181da177e4SLinus Torvalds 	case UDP_ENCAP:
26191da177e4SLinus Torvalds 		switch (val) {
26201da177e4SLinus Torvalds 		case 0:
2621fd1ac07fSAlexey Dobriyan #ifdef CONFIG_XFRM
26221da177e4SLinus Torvalds 		case UDP_ENCAP_ESPINUDP:
26231da177e4SLinus Torvalds 		case UDP_ENCAP_ESPINUDP_NON_IKE:
26240146dca7SSabrina Dubroca #if IS_ENABLED(CONFIG_IPV6)
26250146dca7SSabrina Dubroca 			if (sk->sk_family == AF_INET6)
26260146dca7SSabrina Dubroca 				up->encap_rcv = ipv6_stub->xfrm6_udp_encap_rcv;
26270146dca7SSabrina Dubroca 			else
26280146dca7SSabrina Dubroca #endif
2629067b207bSJames Chapman 				up->encap_rcv = xfrm4_udp_encap_rcv;
2630fd1ac07fSAlexey Dobriyan #endif
2631a8eceea8SJoe Perches 			fallthrough;
2632342f0234SJames Chapman 		case UDP_ENCAP_L2TPINUDP:
26331da177e4SLinus Torvalds 			up->encap_type = val;
263460fb9567SPaolo Abeni 			lock_sock(sk);
263560fb9567SPaolo Abeni 			udp_tunnel_encap_enable(sk->sk_socket);
263660fb9567SPaolo Abeni 			release_sock(sk);
26371da177e4SLinus Torvalds 			break;
26381da177e4SLinus Torvalds 		default:
26391da177e4SLinus Torvalds 			err = -ENOPROTOOPT;
26401da177e4SLinus Torvalds 			break;
26411da177e4SLinus Torvalds 		}
26421da177e4SLinus Torvalds 		break;
26431da177e4SLinus Torvalds 
26441c19448cSTom Herbert 	case UDP_NO_CHECK6_TX:
26451c19448cSTom Herbert 		up->no_check6_tx = valbool;
26461c19448cSTom Herbert 		break;
26471c19448cSTom Herbert 
26481c19448cSTom Herbert 	case UDP_NO_CHECK6_RX:
26491c19448cSTom Herbert 		up->no_check6_rx = valbool;
26501c19448cSTom Herbert 		break;
26511c19448cSTom Herbert 
2652bec1f6f6SWillem de Bruijn 	case UDP_SEGMENT:
2653bec1f6f6SWillem de Bruijn 		if (val < 0 || val > USHRT_MAX)
2654bec1f6f6SWillem de Bruijn 			return -EINVAL;
2655bec1f6f6SWillem de Bruijn 		up->gso_size = val;
2656bec1f6f6SWillem de Bruijn 		break;
2657bec1f6f6SWillem de Bruijn 
2658e20cf8d3SPaolo Abeni 	case UDP_GRO:
2659e20cf8d3SPaolo Abeni 		lock_sock(sk);
2660e20cf8d3SPaolo Abeni 		if (valbool)
2661e20cf8d3SPaolo Abeni 			udp_tunnel_encap_enable(sk->sk_socket);
2662e20cf8d3SPaolo Abeni 		up->gro_enabled = valbool;
2663e20cf8d3SPaolo Abeni 		release_sock(sk);
2664e20cf8d3SPaolo Abeni 		break;
2665e20cf8d3SPaolo Abeni 
2666ba4e58ecSGerrit Renker 	/*
2667ba4e58ecSGerrit Renker 	 * 	UDP-Lite's partial checksum coverage (RFC 3828).
2668ba4e58ecSGerrit Renker 	 */
2669ba4e58ecSGerrit Renker 	/* The sender sets actual checksum coverage length via this option.
2670ba4e58ecSGerrit Renker 	 * The case coverage > packet length is handled by send module. */
2671ba4e58ecSGerrit Renker 	case UDPLITE_SEND_CSCOV:
2672b2bf1e26SWang Chen 		if (!is_udplite)         /* Disable the option on UDP sockets */
2673ba4e58ecSGerrit Renker 			return -ENOPROTOOPT;
2674ba4e58ecSGerrit Renker 		if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
2675ba4e58ecSGerrit Renker 			val = 8;
26764be929beSAlexey Dobriyan 		else if (val > USHRT_MAX)
26774be929beSAlexey Dobriyan 			val = USHRT_MAX;
2678ba4e58ecSGerrit Renker 		up->pcslen = val;
2679ba4e58ecSGerrit Renker 		up->pcflag |= UDPLITE_SEND_CC;
2680ba4e58ecSGerrit Renker 		break;
2681ba4e58ecSGerrit Renker 
2682ba4e58ecSGerrit Renker 	/* The receiver specifies a minimum checksum coverage value. To make
2683ba4e58ecSGerrit Renker 	 * sense, this should be set to at least 8 (as done below). If zero is
2684ba4e58ecSGerrit Renker 	 * used, this again means full checksum coverage.                     */
2685ba4e58ecSGerrit Renker 	case UDPLITE_RECV_CSCOV:
2686b2bf1e26SWang Chen 		if (!is_udplite)         /* Disable the option on UDP sockets */
2687ba4e58ecSGerrit Renker 			return -ENOPROTOOPT;
2688ba4e58ecSGerrit Renker 		if (val != 0 && val < 8) /* Avoid silly minimal values.       */
2689ba4e58ecSGerrit Renker 			val = 8;
26904be929beSAlexey Dobriyan 		else if (val > USHRT_MAX)
26914be929beSAlexey Dobriyan 			val = USHRT_MAX;
2692ba4e58ecSGerrit Renker 		up->pcrlen = val;
2693ba4e58ecSGerrit Renker 		up->pcflag |= UDPLITE_RECV_CC;
2694ba4e58ecSGerrit Renker 		break;
2695ba4e58ecSGerrit Renker 
26961da177e4SLinus Torvalds 	default:
26971da177e4SLinus Torvalds 		err = -ENOPROTOOPT;
26981da177e4SLinus Torvalds 		break;
26996516c655SStephen Hemminger 	}
27001da177e4SLinus Torvalds 
27011da177e4SLinus Torvalds 	return err;
27021da177e4SLinus Torvalds }
2703c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_setsockopt);
27041da177e4SLinus Torvalds 
2705db8dac20SDavid S. Miller int udp_setsockopt(struct sock *sk, int level, int optname,
2706b7058842SDavid S. Miller 		   char __user *optval, unsigned int optlen)
2707db8dac20SDavid S. Miller {
2708db8dac20SDavid S. Miller 	if (level == SOL_UDP  ||  level == SOL_UDPLITE)
2709db8dac20SDavid S. Miller 		return udp_lib_setsockopt(sk, level, optname, optval, optlen,
2710db8dac20SDavid S. Miller 					  udp_push_pending_frames);
2711db8dac20SDavid S. Miller 	return ip_setsockopt(sk, level, optname, optval, optlen);
2712db8dac20SDavid S. Miller }
2713db8dac20SDavid S. Miller 
2714db8dac20SDavid S. Miller #ifdef CONFIG_COMPAT
2715db8dac20SDavid S. Miller int compat_udp_setsockopt(struct sock *sk, int level, int optname,
2716b7058842SDavid S. Miller 			  char __user *optval, unsigned int optlen)
2717db8dac20SDavid S. Miller {
2718db8dac20SDavid S. Miller 	if (level == SOL_UDP  ||  level == SOL_UDPLITE)
2719db8dac20SDavid S. Miller 		return udp_lib_setsockopt(sk, level, optname, optval, optlen,
2720db8dac20SDavid S. Miller 					  udp_push_pending_frames);
2721db8dac20SDavid S. Miller 	return compat_ip_setsockopt(sk, level, optname, optval, optlen);
2722db8dac20SDavid S. Miller }
2723db8dac20SDavid S. Miller #endif
2724db8dac20SDavid S. Miller 
27254c0a6cb0SGerrit Renker int udp_lib_getsockopt(struct sock *sk, int level, int optname,
27261da177e4SLinus Torvalds 		       char __user *optval, int __user *optlen)
27271da177e4SLinus Torvalds {
27281da177e4SLinus Torvalds 	struct udp_sock *up = udp_sk(sk);
27291da177e4SLinus Torvalds 	int val, len;
27301da177e4SLinus Torvalds 
27311da177e4SLinus Torvalds 	if (get_user(len, optlen))
27321da177e4SLinus Torvalds 		return -EFAULT;
27331da177e4SLinus Torvalds 
27341da177e4SLinus Torvalds 	len = min_t(unsigned int, len, sizeof(int));
27351da177e4SLinus Torvalds 
27361da177e4SLinus Torvalds 	if (len < 0)
27371da177e4SLinus Torvalds 		return -EINVAL;
27381da177e4SLinus Torvalds 
27391da177e4SLinus Torvalds 	switch (optname) {
27401da177e4SLinus Torvalds 	case UDP_CORK:
27411da177e4SLinus Torvalds 		val = up->corkflag;
27421da177e4SLinus Torvalds 		break;
27431da177e4SLinus Torvalds 
27441da177e4SLinus Torvalds 	case UDP_ENCAP:
27451da177e4SLinus Torvalds 		val = up->encap_type;
27461da177e4SLinus Torvalds 		break;
27471da177e4SLinus Torvalds 
27481c19448cSTom Herbert 	case UDP_NO_CHECK6_TX:
27491c19448cSTom Herbert 		val = up->no_check6_tx;
27501c19448cSTom Herbert 		break;
27511c19448cSTom Herbert 
27521c19448cSTom Herbert 	case UDP_NO_CHECK6_RX:
27531c19448cSTom Herbert 		val = up->no_check6_rx;
27541c19448cSTom Herbert 		break;
27551c19448cSTom Herbert 
2756bec1f6f6SWillem de Bruijn 	case UDP_SEGMENT:
2757bec1f6f6SWillem de Bruijn 		val = up->gso_size;
2758bec1f6f6SWillem de Bruijn 		break;
2759bec1f6f6SWillem de Bruijn 
2760ba4e58ecSGerrit Renker 	/* The following two cannot be changed on UDP sockets, the return is
2761ba4e58ecSGerrit Renker 	 * always 0 (which corresponds to the full checksum coverage of UDP). */
2762ba4e58ecSGerrit Renker 	case UDPLITE_SEND_CSCOV:
2763ba4e58ecSGerrit Renker 		val = up->pcslen;
2764ba4e58ecSGerrit Renker 		break;
2765ba4e58ecSGerrit Renker 
2766ba4e58ecSGerrit Renker 	case UDPLITE_RECV_CSCOV:
2767ba4e58ecSGerrit Renker 		val = up->pcrlen;
2768ba4e58ecSGerrit Renker 		break;
2769ba4e58ecSGerrit Renker 
27701da177e4SLinus Torvalds 	default:
27711da177e4SLinus Torvalds 		return -ENOPROTOOPT;
27726516c655SStephen Hemminger 	}
27731da177e4SLinus Torvalds 
27741da177e4SLinus Torvalds 	if (put_user(len, optlen))
27751da177e4SLinus Torvalds 		return -EFAULT;
27761da177e4SLinus Torvalds 	if (copy_to_user(optval, &val, len))
27771da177e4SLinus Torvalds 		return -EFAULT;
27781da177e4SLinus Torvalds 	return 0;
27791da177e4SLinus Torvalds }
2780c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_getsockopt);
27811da177e4SLinus Torvalds 
2782db8dac20SDavid S. Miller int udp_getsockopt(struct sock *sk, int level, int optname,
2783db8dac20SDavid S. Miller 		   char __user *optval, int __user *optlen)
2784db8dac20SDavid S. Miller {
2785db8dac20SDavid S. Miller 	if (level == SOL_UDP  ||  level == SOL_UDPLITE)
2786db8dac20SDavid S. Miller 		return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2787db8dac20SDavid S. Miller 	return ip_getsockopt(sk, level, optname, optval, optlen);
2788db8dac20SDavid S. Miller }
2789db8dac20SDavid S. Miller 
2790db8dac20SDavid S. Miller #ifdef CONFIG_COMPAT
2791db8dac20SDavid S. Miller int compat_udp_getsockopt(struct sock *sk, int level, int optname,
2792db8dac20SDavid S. Miller 				 char __user *optval, int __user *optlen)
2793db8dac20SDavid S. Miller {
2794db8dac20SDavid S. Miller 	if (level == SOL_UDP  ||  level == SOL_UDPLITE)
2795db8dac20SDavid S. Miller 		return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2796db8dac20SDavid S. Miller 	return compat_ip_getsockopt(sk, level, optname, optval, optlen);
2797db8dac20SDavid S. Miller }
2798db8dac20SDavid S. Miller #endif
27991da177e4SLinus Torvalds /**
28001da177e4SLinus Torvalds  * 	udp_poll - wait for a UDP event.
28013628e3cbSAndrew Lunn  *	@file: - file struct
28023628e3cbSAndrew Lunn  *	@sock: - socket
28033628e3cbSAndrew Lunn  *	@wait: - poll table
28041da177e4SLinus Torvalds  *
28051da177e4SLinus Torvalds  *	This is same as datagram poll, except for the special case of
28061da177e4SLinus Torvalds  *	blocking sockets. If application is using a blocking fd
28071da177e4SLinus Torvalds  *	and a packet with checksum error is in the queue;
28081da177e4SLinus Torvalds  *	then it could get return from select indicating data available
28091da177e4SLinus Torvalds  *	but then block when reading it. Add special case code
28101da177e4SLinus Torvalds  *	to work around these arguably broken applications.
28111da177e4SLinus Torvalds  */
2812a11e1d43SLinus Torvalds __poll_t udp_poll(struct file *file, struct socket *sock, poll_table *wait)
28131da177e4SLinus Torvalds {
2814a11e1d43SLinus Torvalds 	__poll_t mask = datagram_poll(file, sock, wait);
28151da177e4SLinus Torvalds 	struct sock *sk = sock->sk;
28161da177e4SLinus Torvalds 
28173ef7cf57SEric Dumazet 	if (!skb_queue_empty_lockless(&udp_sk(sk)->reader_queue))
2818a9a08845SLinus Torvalds 		mask |= EPOLLIN | EPOLLRDNORM;
28192276f58aSPaolo Abeni 
28201da177e4SLinus Torvalds 	/* Check for false positives due to checksum errors */
2821a11e1d43SLinus Torvalds 	if ((mask & EPOLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
2822e83c6744SEric Dumazet 	    !(sk->sk_shutdown & RCV_SHUTDOWN) && first_packet_length(sk) == -1)
2823a9a08845SLinus Torvalds 		mask &= ~(EPOLLIN | EPOLLRDNORM);
28241da177e4SLinus Torvalds 
28251da177e4SLinus Torvalds 	return mask;
28261da177e4SLinus Torvalds 
28271da177e4SLinus Torvalds }
2828a11e1d43SLinus Torvalds EXPORT_SYMBOL(udp_poll);
28291da177e4SLinus Torvalds 
28305d77dca8SDavid Ahern int udp_abort(struct sock *sk, int err)
28315d77dca8SDavid Ahern {
28325d77dca8SDavid Ahern 	lock_sock(sk);
28335d77dca8SDavid Ahern 
28345d77dca8SDavid Ahern 	sk->sk_err = err;
28355d77dca8SDavid Ahern 	sk->sk_error_report(sk);
2836286c72deSEric Dumazet 	__udp_disconnect(sk, 0);
28375d77dca8SDavid Ahern 
28385d77dca8SDavid Ahern 	release_sock(sk);
28395d77dca8SDavid Ahern 
28405d77dca8SDavid Ahern 	return 0;
28415d77dca8SDavid Ahern }
28425d77dca8SDavid Ahern EXPORT_SYMBOL_GPL(udp_abort);
28435d77dca8SDavid Ahern 
2844db8dac20SDavid S. Miller struct proto udp_prot = {
2845db8dac20SDavid S. Miller 	.name			= "UDP",
2846db8dac20SDavid S. Miller 	.owner			= THIS_MODULE,
2847db8dac20SDavid S. Miller 	.close			= udp_lib_close,
2848d74bad4eSAndrey Ignatov 	.pre_connect		= udp_pre_connect,
2849db8dac20SDavid S. Miller 	.connect		= ip4_datagram_connect,
2850db8dac20SDavid S. Miller 	.disconnect		= udp_disconnect,
2851db8dac20SDavid S. Miller 	.ioctl			= udp_ioctl,
2852850cbaddSPaolo Abeni 	.init			= udp_init_sock,
2853db8dac20SDavid S. Miller 	.destroy		= udp_destroy_sock,
2854db8dac20SDavid S. Miller 	.setsockopt		= udp_setsockopt,
2855db8dac20SDavid S. Miller 	.getsockopt		= udp_getsockopt,
2856db8dac20SDavid S. Miller 	.sendmsg		= udp_sendmsg,
2857db8dac20SDavid S. Miller 	.recvmsg		= udp_recvmsg,
2858db8dac20SDavid S. Miller 	.sendpage		= udp_sendpage,
28598141ed9fSSteffen Klassert 	.release_cb		= ip4_datagram_release_cb,
2860db8dac20SDavid S. Miller 	.hash			= udp_lib_hash,
2861db8dac20SDavid S. Miller 	.unhash			= udp_lib_unhash,
2862719f8358SEric Dumazet 	.rehash			= udp_v4_rehash,
2863db8dac20SDavid S. Miller 	.get_port		= udp_v4_get_port,
2864db8dac20SDavid S. Miller 	.memory_allocated	= &udp_memory_allocated,
2865db8dac20SDavid S. Miller 	.sysctl_mem		= sysctl_udp_mem,
28661e802951STonghao Zhang 	.sysctl_wmem_offset	= offsetof(struct net, ipv4.sysctl_udp_wmem_min),
28671e802951STonghao Zhang 	.sysctl_rmem_offset	= offsetof(struct net, ipv4.sysctl_udp_rmem_min),
2868db8dac20SDavid S. Miller 	.obj_size		= sizeof(struct udp_sock),
2869645ca708SEric Dumazet 	.h.udp_table		= &udp_table,
2870db8dac20SDavid S. Miller #ifdef CONFIG_COMPAT
2871db8dac20SDavid S. Miller 	.compat_setsockopt	= compat_udp_setsockopt,
2872db8dac20SDavid S. Miller 	.compat_getsockopt	= compat_udp_getsockopt,
2873db8dac20SDavid S. Miller #endif
28745d77dca8SDavid Ahern 	.diag_destroy		= udp_abort,
2875db8dac20SDavid S. Miller };
2876c482c568SEric Dumazet EXPORT_SYMBOL(udp_prot);
28771da177e4SLinus Torvalds 
28781da177e4SLinus Torvalds /* ------------------------------------------------------------------------ */
28791da177e4SLinus Torvalds #ifdef CONFIG_PROC_FS
28801da177e4SLinus Torvalds 
2881645ca708SEric Dumazet static struct sock *udp_get_first(struct seq_file *seq, int start)
28821da177e4SLinus Torvalds {
28831da177e4SLinus Torvalds 	struct sock *sk;
28849e8ca27aSYonghong Song 	struct udp_seq_afinfo *afinfo;
28851da177e4SLinus Torvalds 	struct udp_iter_state *state = seq->private;
28866f191efeSDenis V. Lunev 	struct net *net = seq_file_net(seq);
28871da177e4SLinus Torvalds 
28889e8ca27aSYonghong Song 	if (state->bpf_seq_afinfo)
28899e8ca27aSYonghong Song 		afinfo = state->bpf_seq_afinfo;
28909e8ca27aSYonghong Song 	else
28919e8ca27aSYonghong Song 		afinfo = PDE_DATA(file_inode(seq->file));
28929e8ca27aSYonghong Song 
2893a3d2599bSChristoph Hellwig 	for (state->bucket = start; state->bucket <= afinfo->udp_table->mask;
2894f86dcc5aSEric Dumazet 	     ++state->bucket) {
2895a3d2599bSChristoph Hellwig 		struct udp_hslot *hslot = &afinfo->udp_table->hash[state->bucket];
2896f86dcc5aSEric Dumazet 
2897ca065d0cSEric Dumazet 		if (hlist_empty(&hslot->head))
2898f86dcc5aSEric Dumazet 			continue;
2899f86dcc5aSEric Dumazet 
2900645ca708SEric Dumazet 		spin_lock_bh(&hslot->lock);
2901ca065d0cSEric Dumazet 		sk_for_each(sk, &hslot->head) {
2902878628fbSYOSHIFUJI Hideaki 			if (!net_eq(sock_net(sk), net))
2903a91275efSDaniel Lezcano 				continue;
29049e8ca27aSYonghong Song 			if (afinfo->family == AF_UNSPEC ||
29059e8ca27aSYonghong Song 			    sk->sk_family == afinfo->family)
29061da177e4SLinus Torvalds 				goto found;
29071da177e4SLinus Torvalds 		}
2908645ca708SEric Dumazet 		spin_unlock_bh(&hslot->lock);
29091da177e4SLinus Torvalds 	}
29101da177e4SLinus Torvalds 	sk = NULL;
29111da177e4SLinus Torvalds found:
29121da177e4SLinus Torvalds 	return sk;
29131da177e4SLinus Torvalds }
29141da177e4SLinus Torvalds 
29151da177e4SLinus Torvalds static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
29161da177e4SLinus Torvalds {
29179e8ca27aSYonghong Song 	struct udp_seq_afinfo *afinfo;
29181da177e4SLinus Torvalds 	struct udp_iter_state *state = seq->private;
29196f191efeSDenis V. Lunev 	struct net *net = seq_file_net(seq);
29201da177e4SLinus Torvalds 
29219e8ca27aSYonghong Song 	if (state->bpf_seq_afinfo)
29229e8ca27aSYonghong Song 		afinfo = state->bpf_seq_afinfo;
29239e8ca27aSYonghong Song 	else
29249e8ca27aSYonghong Song 		afinfo = PDE_DATA(file_inode(seq->file));
29259e8ca27aSYonghong Song 
29261da177e4SLinus Torvalds 	do {
2927ca065d0cSEric Dumazet 		sk = sk_next(sk);
29289e8ca27aSYonghong Song 	} while (sk && (!net_eq(sock_net(sk), net) ||
29299e8ca27aSYonghong Song 			(afinfo->family != AF_UNSPEC &&
29309e8ca27aSYonghong Song 			 sk->sk_family != afinfo->family)));
29311da177e4SLinus Torvalds 
2932645ca708SEric Dumazet 	if (!sk) {
2933a3d2599bSChristoph Hellwig 		if (state->bucket <= afinfo->udp_table->mask)
2934a3d2599bSChristoph Hellwig 			spin_unlock_bh(&afinfo->udp_table->hash[state->bucket].lock);
2935645ca708SEric Dumazet 		return udp_get_first(seq, state->bucket + 1);
29361da177e4SLinus Torvalds 	}
29371da177e4SLinus Torvalds 	return sk;
29381da177e4SLinus Torvalds }
29391da177e4SLinus Torvalds 
29401da177e4SLinus Torvalds static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
29411da177e4SLinus Torvalds {
2942645ca708SEric Dumazet 	struct sock *sk = udp_get_first(seq, 0);
29431da177e4SLinus Torvalds 
29441da177e4SLinus Torvalds 	if (sk)
29451da177e4SLinus Torvalds 		while (pos && (sk = udp_get_next(seq, sk)) != NULL)
29461da177e4SLinus Torvalds 			--pos;
29471da177e4SLinus Torvalds 	return pos ? NULL : sk;
29481da177e4SLinus Torvalds }
29491da177e4SLinus Torvalds 
2950a3d2599bSChristoph Hellwig void *udp_seq_start(struct seq_file *seq, loff_t *pos)
29511da177e4SLinus Torvalds {
295230842f29SVitaly Mayatskikh 	struct udp_iter_state *state = seq->private;
2953f86dcc5aSEric Dumazet 	state->bucket = MAX_UDP_PORTS;
295430842f29SVitaly Mayatskikh 
2955b50660f1SYOSHIFUJI Hideaki 	return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
29561da177e4SLinus Torvalds }
2957a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_start);
29581da177e4SLinus Torvalds 
2959a3d2599bSChristoph Hellwig void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
29601da177e4SLinus Torvalds {
29611da177e4SLinus Torvalds 	struct sock *sk;
29621da177e4SLinus Torvalds 
2963b50660f1SYOSHIFUJI Hideaki 	if (v == SEQ_START_TOKEN)
29641da177e4SLinus Torvalds 		sk = udp_get_idx(seq, 0);
29651da177e4SLinus Torvalds 	else
29661da177e4SLinus Torvalds 		sk = udp_get_next(seq, v);
29671da177e4SLinus Torvalds 
29681da177e4SLinus Torvalds 	++*pos;
29691da177e4SLinus Torvalds 	return sk;
29701da177e4SLinus Torvalds }
2971a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_next);
29721da177e4SLinus Torvalds 
2973a3d2599bSChristoph Hellwig void udp_seq_stop(struct seq_file *seq, void *v)
29741da177e4SLinus Torvalds {
29759e8ca27aSYonghong Song 	struct udp_seq_afinfo *afinfo;
2976645ca708SEric Dumazet 	struct udp_iter_state *state = seq->private;
2977645ca708SEric Dumazet 
29789e8ca27aSYonghong Song 	if (state->bpf_seq_afinfo)
29799e8ca27aSYonghong Song 		afinfo = state->bpf_seq_afinfo;
29809e8ca27aSYonghong Song 	else
29819e8ca27aSYonghong Song 		afinfo = PDE_DATA(file_inode(seq->file));
29829e8ca27aSYonghong Song 
2983a3d2599bSChristoph Hellwig 	if (state->bucket <= afinfo->udp_table->mask)
2984a3d2599bSChristoph Hellwig 		spin_unlock_bh(&afinfo->udp_table->hash[state->bucket].lock);
29851da177e4SLinus Torvalds }
2986a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_stop);
2987db8dac20SDavid S. Miller 
2988db8dac20SDavid S. Miller /* ------------------------------------------------------------------------ */
29895e659e4cSPavel Emelyanov static void udp4_format_sock(struct sock *sp, struct seq_file *f,
2990652586dfSTetsuo Handa 		int bucket)
2991db8dac20SDavid S. Miller {
2992db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sp);
2993c720c7e8SEric Dumazet 	__be32 dest = inet->inet_daddr;
2994c720c7e8SEric Dumazet 	__be32 src  = inet->inet_rcv_saddr;
2995c720c7e8SEric Dumazet 	__u16 destp	  = ntohs(inet->inet_dport);
2996c720c7e8SEric Dumazet 	__u16 srcp	  = ntohs(inet->inet_sport);
2997db8dac20SDavid S. Miller 
2998f86dcc5aSEric Dumazet 	seq_printf(f, "%5d: %08X:%04X %08X:%04X"
2999ea9a0379SPatrick Talbert 		" %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %u",
3000db8dac20SDavid S. Miller 		bucket, src, srcp, dest, destp, sp->sk_state,
300131e6d363SEric Dumazet 		sk_wmem_alloc_get(sp),
30026c206b20SPaolo Abeni 		udp_rqueue_get(sp),
3003a7cb5a49SEric W. Biederman 		0, 0L, 0,
3004a7cb5a49SEric W. Biederman 		from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
3005a7cb5a49SEric W. Biederman 		0, sock_i_ino(sp),
300641c6d650SReshetova, Elena 		refcount_read(&sp->sk_refcnt), sp,
3007652586dfSTetsuo Handa 		atomic_read(&sp->sk_drops));
3008db8dac20SDavid S. Miller }
3009db8dac20SDavid S. Miller 
3010db8dac20SDavid S. Miller int udp4_seq_show(struct seq_file *seq, void *v)
3011db8dac20SDavid S. Miller {
3012652586dfSTetsuo Handa 	seq_setwidth(seq, 127);
3013db8dac20SDavid S. Miller 	if (v == SEQ_START_TOKEN)
3014652586dfSTetsuo Handa 		seq_puts(seq, "  sl  local_address rem_address   st tx_queue "
3015db8dac20SDavid S. Miller 			   "rx_queue tr tm->when retrnsmt   uid  timeout "
3016cb61cb9bSEric Dumazet 			   "inode ref pointer drops");
3017db8dac20SDavid S. Miller 	else {
3018db8dac20SDavid S. Miller 		struct udp_iter_state *state = seq->private;
3019db8dac20SDavid S. Miller 
3020652586dfSTetsuo Handa 		udp4_format_sock(v, seq, state->bucket);
3021db8dac20SDavid S. Miller 	}
3022652586dfSTetsuo Handa 	seq_pad(seq, '\n');
3023db8dac20SDavid S. Miller 	return 0;
3024db8dac20SDavid S. Miller }
3025db8dac20SDavid S. Miller 
30265788b3a0SYonghong Song #ifdef CONFIG_BPF_SYSCALL
30275788b3a0SYonghong Song struct bpf_iter__udp {
30285788b3a0SYonghong Song 	__bpf_md_ptr(struct bpf_iter_meta *, meta);
30295788b3a0SYonghong Song 	__bpf_md_ptr(struct udp_sock *, udp_sk);
30305788b3a0SYonghong Song 	uid_t uid __aligned(8);
30315788b3a0SYonghong Song 	int bucket __aligned(8);
30325788b3a0SYonghong Song };
30335788b3a0SYonghong Song 
30345788b3a0SYonghong Song static int udp_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
30355788b3a0SYonghong Song 			     struct udp_sock *udp_sk, uid_t uid, int bucket)
30365788b3a0SYonghong Song {
30375788b3a0SYonghong Song 	struct bpf_iter__udp ctx;
30385788b3a0SYonghong Song 
30395788b3a0SYonghong Song 	meta->seq_num--;  /* skip SEQ_START_TOKEN */
30405788b3a0SYonghong Song 	ctx.meta = meta;
30415788b3a0SYonghong Song 	ctx.udp_sk = udp_sk;
30425788b3a0SYonghong Song 	ctx.uid = uid;
30435788b3a0SYonghong Song 	ctx.bucket = bucket;
30445788b3a0SYonghong Song 	return bpf_iter_run_prog(prog, &ctx);
30455788b3a0SYonghong Song }
30465788b3a0SYonghong Song 
30475788b3a0SYonghong Song static int bpf_iter_udp_seq_show(struct seq_file *seq, void *v)
30485788b3a0SYonghong Song {
30495788b3a0SYonghong Song 	struct udp_iter_state *state = seq->private;
30505788b3a0SYonghong Song 	struct bpf_iter_meta meta;
30515788b3a0SYonghong Song 	struct bpf_prog *prog;
30525788b3a0SYonghong Song 	struct sock *sk = v;
30535788b3a0SYonghong Song 	uid_t uid;
30545788b3a0SYonghong Song 
30555788b3a0SYonghong Song 	if (v == SEQ_START_TOKEN)
30565788b3a0SYonghong Song 		return 0;
30575788b3a0SYonghong Song 
30585788b3a0SYonghong Song 	uid = from_kuid_munged(seq_user_ns(seq), sock_i_uid(sk));
30595788b3a0SYonghong Song 	meta.seq = seq;
30605788b3a0SYonghong Song 	prog = bpf_iter_get_info(&meta, false);
30615788b3a0SYonghong Song 	return udp_prog_seq_show(prog, &meta, v, uid, state->bucket);
30625788b3a0SYonghong Song }
30635788b3a0SYonghong Song 
30645788b3a0SYonghong Song static void bpf_iter_udp_seq_stop(struct seq_file *seq, void *v)
30655788b3a0SYonghong Song {
30665788b3a0SYonghong Song 	struct bpf_iter_meta meta;
30675788b3a0SYonghong Song 	struct bpf_prog *prog;
30685788b3a0SYonghong Song 
30695788b3a0SYonghong Song 	if (!v) {
30705788b3a0SYonghong Song 		meta.seq = seq;
30715788b3a0SYonghong Song 		prog = bpf_iter_get_info(&meta, true);
30725788b3a0SYonghong Song 		if (prog)
30735788b3a0SYonghong Song 			(void)udp_prog_seq_show(prog, &meta, v, 0, 0);
30745788b3a0SYonghong Song 	}
30755788b3a0SYonghong Song 
30765788b3a0SYonghong Song 	udp_seq_stop(seq, v);
30775788b3a0SYonghong Song }
30785788b3a0SYonghong Song 
30795788b3a0SYonghong Song static const struct seq_operations bpf_iter_udp_seq_ops = {
30805788b3a0SYonghong Song 	.start		= udp_seq_start,
30815788b3a0SYonghong Song 	.next		= udp_seq_next,
30825788b3a0SYonghong Song 	.stop		= bpf_iter_udp_seq_stop,
30835788b3a0SYonghong Song 	.show		= bpf_iter_udp_seq_show,
30845788b3a0SYonghong Song };
30855788b3a0SYonghong Song #endif
30865788b3a0SYonghong Song 
3087c3506372SChristoph Hellwig const struct seq_operations udp_seq_ops = {
3088a3d2599bSChristoph Hellwig 	.start		= udp_seq_start,
3089a3d2599bSChristoph Hellwig 	.next		= udp_seq_next,
3090a3d2599bSChristoph Hellwig 	.stop		= udp_seq_stop,
3091a3d2599bSChristoph Hellwig 	.show		= udp4_seq_show,
3092a3d2599bSChristoph Hellwig };
3093c3506372SChristoph Hellwig EXPORT_SYMBOL(udp_seq_ops);
309473cb88ecSArjan van de Ven 
3095db8dac20SDavid S. Miller static struct udp_seq_afinfo udp4_seq_afinfo = {
3096db8dac20SDavid S. Miller 	.family		= AF_INET,
3097645ca708SEric Dumazet 	.udp_table	= &udp_table,
3098db8dac20SDavid S. Miller };
3099db8dac20SDavid S. Miller 
31002c8c1e72SAlexey Dobriyan static int __net_init udp4_proc_init_net(struct net *net)
310115439febSPavel Emelyanov {
3102c3506372SChristoph Hellwig 	if (!proc_create_net_data("udp", 0444, net->proc_net, &udp_seq_ops,
3103c3506372SChristoph Hellwig 			sizeof(struct udp_iter_state), &udp4_seq_afinfo))
3104a3d2599bSChristoph Hellwig 		return -ENOMEM;
3105a3d2599bSChristoph Hellwig 	return 0;
310615439febSPavel Emelyanov }
310715439febSPavel Emelyanov 
31082c8c1e72SAlexey Dobriyan static void __net_exit udp4_proc_exit_net(struct net *net)
310915439febSPavel Emelyanov {
3110a3d2599bSChristoph Hellwig 	remove_proc_entry("udp", net->proc_net);
311115439febSPavel Emelyanov }
311215439febSPavel Emelyanov 
311315439febSPavel Emelyanov static struct pernet_operations udp4_net_ops = {
311415439febSPavel Emelyanov 	.init = udp4_proc_init_net,
311515439febSPavel Emelyanov 	.exit = udp4_proc_exit_net,
311615439febSPavel Emelyanov };
311715439febSPavel Emelyanov 
3118db8dac20SDavid S. Miller int __init udp4_proc_init(void)
3119db8dac20SDavid S. Miller {
312015439febSPavel Emelyanov 	return register_pernet_subsys(&udp4_net_ops);
3121db8dac20SDavid S. Miller }
3122db8dac20SDavid S. Miller 
3123db8dac20SDavid S. Miller void udp4_proc_exit(void)
3124db8dac20SDavid S. Miller {
312515439febSPavel Emelyanov 	unregister_pernet_subsys(&udp4_net_ops);
3126db8dac20SDavid S. Miller }
31271da177e4SLinus Torvalds #endif /* CONFIG_PROC_FS */
31281da177e4SLinus Torvalds 
3129f86dcc5aSEric Dumazet static __initdata unsigned long uhash_entries;
3130f86dcc5aSEric Dumazet static int __init set_uhash_entries(char *str)
3131645ca708SEric Dumazet {
3132413c27d8SEldad Zack 	ssize_t ret;
3133413c27d8SEldad Zack 
3134f86dcc5aSEric Dumazet 	if (!str)
3135f86dcc5aSEric Dumazet 		return 0;
3136413c27d8SEldad Zack 
3137413c27d8SEldad Zack 	ret = kstrtoul(str, 0, &uhash_entries);
3138413c27d8SEldad Zack 	if (ret)
3139413c27d8SEldad Zack 		return 0;
3140413c27d8SEldad Zack 
3141f86dcc5aSEric Dumazet 	if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
3142f86dcc5aSEric Dumazet 		uhash_entries = UDP_HTABLE_SIZE_MIN;
3143f86dcc5aSEric Dumazet 	return 1;
3144f86dcc5aSEric Dumazet }
3145f86dcc5aSEric Dumazet __setup("uhash_entries=", set_uhash_entries);
3146645ca708SEric Dumazet 
3147f86dcc5aSEric Dumazet void __init udp_table_init(struct udp_table *table, const char *name)
3148f86dcc5aSEric Dumazet {
3149f86dcc5aSEric Dumazet 	unsigned int i;
3150f86dcc5aSEric Dumazet 
3151f86dcc5aSEric Dumazet 	table->hash = alloc_large_system_hash(name,
3152512615b6SEric Dumazet 					      2 * sizeof(struct udp_hslot),
3153f86dcc5aSEric Dumazet 					      uhash_entries,
3154f86dcc5aSEric Dumazet 					      21, /* one slot per 2 MB */
3155f86dcc5aSEric Dumazet 					      0,
3156f86dcc5aSEric Dumazet 					      &table->log,
3157f86dcc5aSEric Dumazet 					      &table->mask,
315831fe62b9STim Bird 					      UDP_HTABLE_SIZE_MIN,
3159f86dcc5aSEric Dumazet 					      64 * 1024);
316031fe62b9STim Bird 
3161512615b6SEric Dumazet 	table->hash2 = table->hash + (table->mask + 1);
3162f86dcc5aSEric Dumazet 	for (i = 0; i <= table->mask; i++) {
3163ca065d0cSEric Dumazet 		INIT_HLIST_HEAD(&table->hash[i].head);
3164fdcc8aa9SEric Dumazet 		table->hash[i].count = 0;
3165645ca708SEric Dumazet 		spin_lock_init(&table->hash[i].lock);
3166645ca708SEric Dumazet 	}
3167512615b6SEric Dumazet 	for (i = 0; i <= table->mask; i++) {
3168ca065d0cSEric Dumazet 		INIT_HLIST_HEAD(&table->hash2[i].head);
3169512615b6SEric Dumazet 		table->hash2[i].count = 0;
3170512615b6SEric Dumazet 		spin_lock_init(&table->hash2[i].lock);
3171512615b6SEric Dumazet 	}
3172645ca708SEric Dumazet }
3173645ca708SEric Dumazet 
3174723b8e46STom Herbert u32 udp_flow_hashrnd(void)
3175723b8e46STom Herbert {
3176723b8e46STom Herbert 	static u32 hashrnd __read_mostly;
3177723b8e46STom Herbert 
3178723b8e46STom Herbert 	net_get_random_once(&hashrnd, sizeof(hashrnd));
3179723b8e46STom Herbert 
3180723b8e46STom Herbert 	return hashrnd;
3181723b8e46STom Herbert }
3182723b8e46STom Herbert EXPORT_SYMBOL(udp_flow_hashrnd);
3183723b8e46STom Herbert 
31841e802951STonghao Zhang static void __udp_sysctl_init(struct net *net)
31851e802951STonghao Zhang {
31861e802951STonghao Zhang 	net->ipv4.sysctl_udp_rmem_min = SK_MEM_QUANTUM;
31871e802951STonghao Zhang 	net->ipv4.sysctl_udp_wmem_min = SK_MEM_QUANTUM;
31881e802951STonghao Zhang 
31891e802951STonghao Zhang #ifdef CONFIG_NET_L3_MASTER_DEV
31901e802951STonghao Zhang 	net->ipv4.sysctl_udp_l3mdev_accept = 0;
31911e802951STonghao Zhang #endif
31921e802951STonghao Zhang }
31931e802951STonghao Zhang 
31941e802951STonghao Zhang static int __net_init udp_sysctl_init(struct net *net)
31951e802951STonghao Zhang {
31961e802951STonghao Zhang 	__udp_sysctl_init(net);
31971e802951STonghao Zhang 	return 0;
31981e802951STonghao Zhang }
31991e802951STonghao Zhang 
32001e802951STonghao Zhang static struct pernet_operations __net_initdata udp_sysctl_ops = {
32011e802951STonghao Zhang 	.init	= udp_sysctl_init,
32021e802951STonghao Zhang };
32031e802951STonghao Zhang 
32045788b3a0SYonghong Song #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
32055788b3a0SYonghong Song DEFINE_BPF_ITER_FUNC(udp, struct bpf_iter_meta *meta,
32065788b3a0SYonghong Song 		     struct udp_sock *udp_sk, uid_t uid, int bucket)
32075788b3a0SYonghong Song 
32085788b3a0SYonghong Song static int bpf_iter_init_udp(void *priv_data)
32095788b3a0SYonghong Song {
32105788b3a0SYonghong Song 	struct udp_iter_state *st = priv_data;
32115788b3a0SYonghong Song 	struct udp_seq_afinfo *afinfo;
32125788b3a0SYonghong Song 	int ret;
32135788b3a0SYonghong Song 
32145788b3a0SYonghong Song 	afinfo = kmalloc(sizeof(*afinfo), GFP_USER | __GFP_NOWARN);
32155788b3a0SYonghong Song 	if (!afinfo)
32165788b3a0SYonghong Song 		return -ENOMEM;
32175788b3a0SYonghong Song 
32185788b3a0SYonghong Song 	afinfo->family = AF_UNSPEC;
32195788b3a0SYonghong Song 	afinfo->udp_table = &udp_table;
32205788b3a0SYonghong Song 	st->bpf_seq_afinfo = afinfo;
32215788b3a0SYonghong Song 	ret = bpf_iter_init_seq_net(priv_data);
32225788b3a0SYonghong Song 	if (ret)
32235788b3a0SYonghong Song 		kfree(afinfo);
32245788b3a0SYonghong Song 	return ret;
32255788b3a0SYonghong Song }
32265788b3a0SYonghong Song 
32275788b3a0SYonghong Song static void bpf_iter_fini_udp(void *priv_data)
32285788b3a0SYonghong Song {
32295788b3a0SYonghong Song 	struct udp_iter_state *st = priv_data;
32305788b3a0SYonghong Song 
32315788b3a0SYonghong Song 	kfree(st->bpf_seq_afinfo);
32325788b3a0SYonghong Song 	bpf_iter_fini_seq_net(priv_data);
32335788b3a0SYonghong Song }
32345788b3a0SYonghong Song 
32355788b3a0SYonghong Song static const struct bpf_iter_reg udp_reg_info = {
32365788b3a0SYonghong Song 	.target			= "udp",
32375788b3a0SYonghong Song 	.seq_ops		= &bpf_iter_udp_seq_ops,
32385788b3a0SYonghong Song 	.init_seq_private	= bpf_iter_init_udp,
32395788b3a0SYonghong Song 	.fini_seq_private	= bpf_iter_fini_udp,
32405788b3a0SYonghong Song 	.seq_priv_size		= sizeof(struct udp_iter_state),
32415788b3a0SYonghong Song 	.ctx_arg_info_size	= 1,
32425788b3a0SYonghong Song 	.ctx_arg_info		= {
32435788b3a0SYonghong Song 		{ offsetof(struct bpf_iter__udp, udp_sk),
32445788b3a0SYonghong Song 		  PTR_TO_BTF_ID_OR_NULL },
32455788b3a0SYonghong Song 	},
32465788b3a0SYonghong Song };
32475788b3a0SYonghong Song 
32485788b3a0SYonghong Song static void __init bpf_iter_register(void)
32495788b3a0SYonghong Song {
32505788b3a0SYonghong Song 	if (bpf_iter_reg_target(&udp_reg_info))
32515788b3a0SYonghong Song 		pr_warn("Warning: could not register bpf iterator udp\n");
32525788b3a0SYonghong Song }
32535788b3a0SYonghong Song #endif
32545788b3a0SYonghong Song 
325595766fffSHideo Aoki void __init udp_init(void)
325695766fffSHideo Aoki {
3257f03d78dbSEric Dumazet 	unsigned long limit;
32584b272750SEric Dumazet 	unsigned int i;
325995766fffSHideo Aoki 
3260f86dcc5aSEric Dumazet 	udp_table_init(&udp_table, "UDP");
3261f03d78dbSEric Dumazet 	limit = nr_free_buffer_pages() / 8;
326295766fffSHideo Aoki 	limit = max(limit, 128UL);
326395766fffSHideo Aoki 	sysctl_udp_mem[0] = limit / 4 * 3;
326495766fffSHideo Aoki 	sysctl_udp_mem[1] = limit;
326595766fffSHideo Aoki 	sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
326695766fffSHideo Aoki 
32671e802951STonghao Zhang 	__udp_sysctl_init(&init_net);
32684b272750SEric Dumazet 
32694b272750SEric Dumazet 	/* 16 spinlocks per cpu */
32704b272750SEric Dumazet 	udp_busylocks_log = ilog2(nr_cpu_ids) + 4;
32714b272750SEric Dumazet 	udp_busylocks = kmalloc(sizeof(spinlock_t) << udp_busylocks_log,
32724b272750SEric Dumazet 				GFP_KERNEL);
32734b272750SEric Dumazet 	if (!udp_busylocks)
32744b272750SEric Dumazet 		panic("UDP: failed to alloc udp_busylocks\n");
32754b272750SEric Dumazet 	for (i = 0; i < (1U << udp_busylocks_log); i++)
32764b272750SEric Dumazet 		spin_lock_init(udp_busylocks + i);
32771e802951STonghao Zhang 
32781e802951STonghao Zhang 	if (register_pernet_subsys(&udp_sysctl_ops))
32791e802951STonghao Zhang 		panic("UDP: failed to init sysctl parameters.\n");
32805788b3a0SYonghong Song 
32815788b3a0SYonghong Song #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
32825788b3a0SYonghong Song 	bpf_iter_register();
32835788b3a0SYonghong Song #endif
328495766fffSHideo Aoki }
3285