xref: /linux/net/ipv4/udp.c (revision 735453730a05391b4be97ad408b3bef07df13fe7)
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>
1151da177e4SLinus Torvalds 
116f86dcc5aSEric Dumazet struct udp_table udp_table __read_mostly;
117645ca708SEric Dumazet EXPORT_SYMBOL(udp_table);
1181da177e4SLinus Torvalds 
1198d987e5cSEric Dumazet long sysctl_udp_mem[3] __read_mostly;
12095766fffSHideo Aoki EXPORT_SYMBOL(sysctl_udp_mem);
121c482c568SEric Dumazet 
1228d987e5cSEric Dumazet atomic_long_t udp_memory_allocated;
12395766fffSHideo Aoki EXPORT_SYMBOL(udp_memory_allocated);
12495766fffSHideo Aoki 
125f86dcc5aSEric Dumazet #define MAX_UDP_PORTS 65536
126f86dcc5aSEric Dumazet #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN)
12798322f22SEric Dumazet 
12863a6fff3SRobert Shearman /* IPCB reference means this can not be used from early demux */
12963a6fff3SRobert Shearman static bool udp_lib_exact_dif_match(struct net *net, struct sk_buff *skb)
13063a6fff3SRobert Shearman {
13163a6fff3SRobert Shearman #if IS_ENABLED(CONFIG_NET_L3_MASTER_DEV)
13263a6fff3SRobert Shearman 	if (!net->ipv4.sysctl_udp_l3mdev_accept &&
13363a6fff3SRobert Shearman 	    skb && ipv4_l3mdev_skb(IPCB(skb)->flags))
13463a6fff3SRobert Shearman 		return true;
13563a6fff3SRobert Shearman #endif
13663a6fff3SRobert Shearman 	return false;
13763a6fff3SRobert Shearman }
13863a6fff3SRobert Shearman 
139f24d43c0SEric Dumazet static int udp_lib_lport_inuse(struct net *net, __u16 num,
140645ca708SEric Dumazet 			       const struct udp_hslot *hslot,
14198322f22SEric Dumazet 			       unsigned long *bitmap,
142fe38d2a1SJosef Bacik 			       struct sock *sk, unsigned int log)
14325030a7fSGerrit Renker {
144f24d43c0SEric Dumazet 	struct sock *sk2;
145ba418fa3STom Herbert 	kuid_t uid = sock_i_uid(sk);
14625030a7fSGerrit Renker 
147ca065d0cSEric Dumazet 	sk_for_each(sk2, &hslot->head) {
148f24d43c0SEric Dumazet 		if (net_eq(sock_net(sk2), net) &&
149f24d43c0SEric Dumazet 		    sk2 != sk &&
150d4cada4aSEric Dumazet 		    (bitmap || udp_sk(sk2)->udp_port_hash == num) &&
151f24d43c0SEric Dumazet 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
1529d4fb27dSJoe Perches 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
1539d4fb27dSJoe Perches 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
154fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, true)) {
155df560056SEric Garver 			if (sk2->sk_reuseport && sk->sk_reuseport &&
156df560056SEric Garver 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
157df560056SEric Garver 			    uid_eq(uid, sock_i_uid(sk2))) {
158df560056SEric Garver 				if (!bitmap)
159df560056SEric Garver 					return 0;
160df560056SEric Garver 			} else {
1614243cdc2SJoe Perches 				if (!bitmap)
162fc038410SDavid S. Miller 					return 1;
163df560056SEric Garver 				__set_bit(udp_sk(sk2)->udp_port_hash >> log,
164df560056SEric Garver 					  bitmap);
165df560056SEric Garver 			}
1664243cdc2SJoe Perches 		}
16798322f22SEric Dumazet 	}
16825030a7fSGerrit Renker 	return 0;
16925030a7fSGerrit Renker }
17025030a7fSGerrit Renker 
17130fff923SEric Dumazet /*
17230fff923SEric Dumazet  * Note: we still hold spinlock of primary hash chain, so no other writer
17330fff923SEric Dumazet  * can insert/delete a socket with local_port == num
17430fff923SEric Dumazet  */
17530fff923SEric Dumazet static int udp_lib_lport_inuse2(struct net *net, __u16 num,
17630fff923SEric Dumazet 				struct udp_hslot *hslot2,
177fe38d2a1SJosef Bacik 				struct sock *sk)
17830fff923SEric Dumazet {
17930fff923SEric Dumazet 	struct sock *sk2;
180ba418fa3STom Herbert 	kuid_t uid = sock_i_uid(sk);
18130fff923SEric Dumazet 	int res = 0;
18230fff923SEric Dumazet 
18330fff923SEric Dumazet 	spin_lock(&hslot2->lock);
184ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry(sk2, &hslot2->head) {
18530fff923SEric Dumazet 		if (net_eq(sock_net(sk2), net) &&
18630fff923SEric Dumazet 		    sk2 != sk &&
18730fff923SEric Dumazet 		    (udp_sk(sk2)->udp_port_hash == num) &&
18830fff923SEric Dumazet 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
1899d4fb27dSJoe Perches 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
1909d4fb27dSJoe Perches 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
191fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, true)) {
192df560056SEric Garver 			if (sk2->sk_reuseport && sk->sk_reuseport &&
193df560056SEric Garver 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
194df560056SEric Garver 			    uid_eq(uid, sock_i_uid(sk2))) {
195df560056SEric Garver 				res = 0;
196df560056SEric Garver 			} else {
19730fff923SEric Dumazet 				res = 1;
198df560056SEric Garver 			}
19930fff923SEric Dumazet 			break;
20030fff923SEric Dumazet 		}
2014243cdc2SJoe Perches 	}
20230fff923SEric Dumazet 	spin_unlock(&hslot2->lock);
20330fff923SEric Dumazet 	return res;
20430fff923SEric Dumazet }
20530fff923SEric Dumazet 
206fe38d2a1SJosef Bacik static int udp_reuseport_add_sock(struct sock *sk, struct udp_hslot *hslot)
207e32ea7e7SCraig Gallek {
208e32ea7e7SCraig Gallek 	struct net *net = sock_net(sk);
209e32ea7e7SCraig Gallek 	kuid_t uid = sock_i_uid(sk);
210e32ea7e7SCraig Gallek 	struct sock *sk2;
211e32ea7e7SCraig Gallek 
212ca065d0cSEric Dumazet 	sk_for_each(sk2, &hslot->head) {
213e32ea7e7SCraig Gallek 		if (net_eq(sock_net(sk2), net) &&
214e32ea7e7SCraig Gallek 		    sk2 != sk &&
215e32ea7e7SCraig Gallek 		    sk2->sk_family == sk->sk_family &&
216e32ea7e7SCraig Gallek 		    ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
217e32ea7e7SCraig Gallek 		    (udp_sk(sk2)->udp_port_hash == udp_sk(sk)->udp_port_hash) &&
218e32ea7e7SCraig Gallek 		    (sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
219e32ea7e7SCraig Gallek 		    sk2->sk_reuseport && uid_eq(uid, sock_i_uid(sk2)) &&
220fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, false)) {
2212dbb9b9eSMartin KaFai Lau 			return reuseport_add_sock(sk, sk2,
2222dbb9b9eSMartin KaFai Lau 						  inet_rcv_saddr_any(sk));
223e32ea7e7SCraig Gallek 		}
224e32ea7e7SCraig Gallek 	}
225e32ea7e7SCraig Gallek 
2262dbb9b9eSMartin KaFai Lau 	return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
227e32ea7e7SCraig Gallek }
228e32ea7e7SCraig Gallek 
22925030a7fSGerrit Renker /**
2306ba5a3c5SPavel Emelyanov  *  udp_lib_get_port  -  UDP/-Lite port lookup for IPv4 and IPv6
23125030a7fSGerrit Renker  *
23225030a7fSGerrit Renker  *  @sk:          socket struct in question
23325030a7fSGerrit Renker  *  @snum:        port number to look up
23425985edcSLucas De Marchi  *  @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
23530fff923SEric Dumazet  *                   with NULL address
23625030a7fSGerrit Renker  */
2376ba5a3c5SPavel Emelyanov int udp_lib_get_port(struct sock *sk, unsigned short snum,
23830fff923SEric Dumazet 		     unsigned int hash2_nulladdr)
2391da177e4SLinus Torvalds {
240512615b6SEric Dumazet 	struct udp_hslot *hslot, *hslot2;
241645ca708SEric Dumazet 	struct udp_table *udptable = sk->sk_prot->h.udp_table;
24225030a7fSGerrit Renker 	int    error = 1;
2433b1e0a65SYOSHIFUJI Hideaki 	struct net *net = sock_net(sk);
2441da177e4SLinus Torvalds 
24532c1da70SStephen Hemminger 	if (!snum) {
2469088c560SEric Dumazet 		int low, high, remaining;
24795c96174SEric Dumazet 		unsigned int rand;
24898322f22SEric Dumazet 		unsigned short first, last;
24998322f22SEric Dumazet 		DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
2501da177e4SLinus Torvalds 
2510bbf87d8SEric W. Biederman 		inet_get_local_port_range(net, &low, &high);
252a25de534SAnton Arapov 		remaining = (high - low) + 1;
253227b60f5SStephen Hemminger 
25463862b5bSAruna-Hewapathirane 		rand = prandom_u32();
2558fc54f68SDaniel Borkmann 		first = reciprocal_scale(rand, remaining) + low;
25698322f22SEric Dumazet 		/*
25798322f22SEric Dumazet 		 * force rand to be an odd multiple of UDP_HTABLE_SIZE
25898322f22SEric Dumazet 		 */
259f86dcc5aSEric Dumazet 		rand = (rand | 1) * (udptable->mask + 1);
2605781b235SEric Dumazet 		last = first + udptable->mask + 1;
2615781b235SEric Dumazet 		do {
262f86dcc5aSEric Dumazet 			hslot = udp_hashslot(udptable, net, first);
26398322f22SEric Dumazet 			bitmap_zero(bitmap, PORTS_PER_CHAIN);
264645ca708SEric Dumazet 			spin_lock_bh(&hslot->lock);
26598322f22SEric Dumazet 			udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
266fe38d2a1SJosef Bacik 					    udptable->log);
26798322f22SEric Dumazet 
26898322f22SEric Dumazet 			snum = first;
26998322f22SEric Dumazet 			/*
27098322f22SEric Dumazet 			 * Iterate on all possible values of snum for this hash.
27198322f22SEric Dumazet 			 * Using steps of an odd multiple of UDP_HTABLE_SIZE
27298322f22SEric Dumazet 			 * give us randomization and full range coverage.
27398322f22SEric Dumazet 			 */
2749088c560SEric Dumazet 			do {
27598322f22SEric Dumazet 				if (low <= snum && snum <= high &&
276e3826f1eSAmerigo Wang 				    !test_bit(snum >> udptable->log, bitmap) &&
277122ff243SWANG Cong 				    !inet_is_local_reserved_port(net, snum))
27898322f22SEric Dumazet 					goto found;
27998322f22SEric Dumazet 				snum += rand;
28098322f22SEric Dumazet 			} while (snum != first);
28198322f22SEric Dumazet 			spin_unlock_bh(&hslot->lock);
282df560056SEric Garver 			cond_resched();
2835781b235SEric Dumazet 		} while (++first != last);
28498322f22SEric Dumazet 		goto fail;
285645ca708SEric Dumazet 	} else {
286f86dcc5aSEric Dumazet 		hslot = udp_hashslot(udptable, net, snum);
287645ca708SEric Dumazet 		spin_lock_bh(&hslot->lock);
28830fff923SEric Dumazet 		if (hslot->count > 10) {
28930fff923SEric Dumazet 			int exist;
29030fff923SEric Dumazet 			unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
29130fff923SEric Dumazet 
29230fff923SEric Dumazet 			slot2          &= udptable->mask;
29330fff923SEric Dumazet 			hash2_nulladdr &= udptable->mask;
29430fff923SEric Dumazet 
29530fff923SEric Dumazet 			hslot2 = udp_hashslot2(udptable, slot2);
29630fff923SEric Dumazet 			if (hslot->count < hslot2->count)
29730fff923SEric Dumazet 				goto scan_primary_hash;
29830fff923SEric Dumazet 
299fe38d2a1SJosef Bacik 			exist = udp_lib_lport_inuse2(net, snum, hslot2, sk);
30030fff923SEric Dumazet 			if (!exist && (hash2_nulladdr != slot2)) {
30130fff923SEric Dumazet 				hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
30230fff923SEric Dumazet 				exist = udp_lib_lport_inuse2(net, snum, hslot2,
303fe38d2a1SJosef Bacik 							     sk);
30430fff923SEric Dumazet 			}
30530fff923SEric Dumazet 			if (exist)
30630fff923SEric Dumazet 				goto fail_unlock;
30730fff923SEric Dumazet 			else
30830fff923SEric Dumazet 				goto found;
30930fff923SEric Dumazet 		}
31030fff923SEric Dumazet scan_primary_hash:
311fe38d2a1SJosef Bacik 		if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, 0))
312645ca708SEric Dumazet 			goto fail_unlock;
313645ca708SEric Dumazet 	}
31498322f22SEric Dumazet found:
315c720c7e8SEric Dumazet 	inet_sk(sk)->inet_num = snum;
316d4cada4aSEric Dumazet 	udp_sk(sk)->udp_port_hash = snum;
317d4cada4aSEric Dumazet 	udp_sk(sk)->udp_portaddr_hash ^= snum;
3181da177e4SLinus Torvalds 	if (sk_unhashed(sk)) {
319e32ea7e7SCraig Gallek 		if (sk->sk_reuseport &&
320fe38d2a1SJosef Bacik 		    udp_reuseport_add_sock(sk, hslot)) {
321e32ea7e7SCraig Gallek 			inet_sk(sk)->inet_num = 0;
322e32ea7e7SCraig Gallek 			udp_sk(sk)->udp_port_hash = 0;
323e32ea7e7SCraig Gallek 			udp_sk(sk)->udp_portaddr_hash ^= snum;
324e32ea7e7SCraig Gallek 			goto fail_unlock;
325e32ea7e7SCraig Gallek 		}
326e32ea7e7SCraig Gallek 
327ca065d0cSEric Dumazet 		sk_add_node_rcu(sk, &hslot->head);
328fdcc8aa9SEric Dumazet 		hslot->count++;
329c29a0bc4SPavel Emelyanov 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
330512615b6SEric Dumazet 
331512615b6SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
332512615b6SEric Dumazet 		spin_lock(&hslot2->lock);
333d894ba18SCraig Gallek 		if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
334d894ba18SCraig Gallek 		    sk->sk_family == AF_INET6)
3351602f49bSDavid S. Miller 			hlist_add_tail_rcu(&udp_sk(sk)->udp_portaddr_node,
336d894ba18SCraig Gallek 					   &hslot2->head);
337d894ba18SCraig Gallek 		else
338ca065d0cSEric Dumazet 			hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
339512615b6SEric Dumazet 					   &hslot2->head);
340512615b6SEric Dumazet 		hslot2->count++;
341512615b6SEric Dumazet 		spin_unlock(&hslot2->lock);
3421da177e4SLinus Torvalds 	}
343ca065d0cSEric Dumazet 	sock_set_flag(sk, SOCK_RCU_FREE);
34425030a7fSGerrit Renker 	error = 0;
345645ca708SEric Dumazet fail_unlock:
346645ca708SEric Dumazet 	spin_unlock_bh(&hslot->lock);
3471da177e4SLinus Torvalds fail:
34825030a7fSGerrit Renker 	return error;
3491da177e4SLinus Torvalds }
350c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_get_port);
3511da177e4SLinus Torvalds 
3526ba5a3c5SPavel Emelyanov int udp_v4_get_port(struct sock *sk, unsigned short snum)
353db8dac20SDavid S. Miller {
35430fff923SEric Dumazet 	unsigned int hash2_nulladdr =
355f0b1e64cSMartin KaFai Lau 		ipv4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
35630fff923SEric Dumazet 	unsigned int hash2_partial =
357f0b1e64cSMartin KaFai Lau 		ipv4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
35830fff923SEric Dumazet 
359d4cada4aSEric Dumazet 	/* precompute partial secondary hash */
36030fff923SEric Dumazet 	udp_sk(sk)->udp_portaddr_hash = hash2_partial;
361fe38d2a1SJosef Bacik 	return udp_lib_get_port(sk, snum, hash2_nulladdr);
362db8dac20SDavid S. Miller }
363db8dac20SDavid S. Miller 
364d1e37288SSu, Xuemin static int compute_score(struct sock *sk, struct net *net,
365d1e37288SSu, Xuemin 			 __be32 saddr, __be16 sport,
366fb74c277SDavid Ahern 			 __be32 daddr, unsigned short hnum,
367*73545373STim Beale 			 int dif, int sdif)
368645ca708SEric Dumazet {
36960c04aecSJoe Perches 	int score;
37060c04aecSJoe Perches 	struct inet_sock *inet;
3716da5b0f0SMike Manning 	bool dev_match;
372645ca708SEric Dumazet 
37360c04aecSJoe Perches 	if (!net_eq(sock_net(sk), net) ||
37460c04aecSJoe Perches 	    udp_sk(sk)->udp_port_hash != hnum ||
37560c04aecSJoe Perches 	    ipv6_only_sock(sk))
37660c04aecSJoe Perches 		return -1;
377645ca708SEric Dumazet 
3784cdeeee9SPeter Oskolkov 	if (sk->sk_rcv_saddr != daddr)
379645ca708SEric Dumazet 		return -1;
38060c04aecSJoe Perches 
3814cdeeee9SPeter Oskolkov 	score = (sk->sk_family == PF_INET) ? 2 : 1;
3824cdeeee9SPeter Oskolkov 
3834cdeeee9SPeter Oskolkov 	inet = inet_sk(sk);
384c720c7e8SEric Dumazet 	if (inet->inet_daddr) {
385c720c7e8SEric Dumazet 		if (inet->inet_daddr != saddr)
386645ca708SEric Dumazet 			return -1;
387ba418fa3STom Herbert 		score += 4;
388645ca708SEric Dumazet 	}
38960c04aecSJoe Perches 
390c720c7e8SEric Dumazet 	if (inet->inet_dport) {
391c720c7e8SEric Dumazet 		if (inet->inet_dport != sport)
392645ca708SEric Dumazet 			return -1;
393ba418fa3STom Herbert 		score += 4;
394645ca708SEric Dumazet 	}
39560c04aecSJoe Perches 
3966da5b0f0SMike Manning 	dev_match = udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if,
3976da5b0f0SMike Manning 					dif, sdif);
39869678bcdSPaolo Abeni 	if (!dev_match)
399645ca708SEric Dumazet 		return -1;
400ba418fa3STom Herbert 	score += 4;
401fb74c277SDavid Ahern 
40270da268bSEric Dumazet 	if (sk->sk_incoming_cpu == raw_smp_processor_id())
40370da268bSEric Dumazet 		score++;
404645ca708SEric Dumazet 	return score;
405645ca708SEric Dumazet }
406645ca708SEric Dumazet 
4076eada011SEric Dumazet static u32 udp_ehashfn(const struct net *net, const __be32 laddr,
40865cd8033SHannes Frederic Sowa 		       const __u16 lport, const __be32 faddr,
40965cd8033SHannes Frederic Sowa 		       const __be16 fport)
41065cd8033SHannes Frederic Sowa {
4111bbdceefSHannes Frederic Sowa 	static u32 udp_ehash_secret __read_mostly;
4121bbdceefSHannes Frederic Sowa 
4131bbdceefSHannes Frederic Sowa 	net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret));
4141bbdceefSHannes Frederic Sowa 
41565cd8033SHannes Frederic Sowa 	return __inet_ehashfn(laddr, lport, faddr, fport,
4161bbdceefSHannes Frederic Sowa 			      udp_ehash_secret + net_hash_mix(net));
41765cd8033SHannes Frederic Sowa }
41865cd8033SHannes Frederic Sowa 
419d1e37288SSu, Xuemin /* called with rcu_read_lock() */
4205051ebd2SEric Dumazet static struct sock *udp4_lib_lookup2(struct net *net,
4215051ebd2SEric Dumazet 				     __be32 saddr, __be16 sport,
422fb74c277SDavid Ahern 				     __be32 daddr, unsigned int hnum,
423*73545373STim Beale 				     int dif, int sdif,
424d1e37288SSu, Xuemin 				     struct udp_hslot *hslot2,
4251134158bSCraig Gallek 				     struct sk_buff *skb)
4265051ebd2SEric Dumazet {
4275051ebd2SEric Dumazet 	struct sock *sk, *result;
428e94a62f5SPaolo Abeni 	int score, badness;
429ba418fa3STom Herbert 	u32 hash = 0;
4305051ebd2SEric Dumazet 
4315051ebd2SEric Dumazet 	result = NULL;
432ba418fa3STom Herbert 	badness = 0;
433ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
434d1e37288SSu, Xuemin 		score = compute_score(sk, net, saddr, sport,
435*73545373STim Beale 				      daddr, hnum, dif, sdif);
4365051ebd2SEric Dumazet 		if (score > badness) {
437e94a62f5SPaolo Abeni 			if (sk->sk_reuseport) {
43865cd8033SHannes Frederic Sowa 				hash = udp_ehashfn(net, daddr, hnum,
4397c0cadc6SEric Dumazet 						   saddr, sport);
440ca065d0cSEric Dumazet 				result = reuseport_select_sock(sk, hash, skb,
4411134158bSCraig Gallek 							sizeof(struct udphdr));
442ca065d0cSEric Dumazet 				if (result)
443ca065d0cSEric Dumazet 					return result;
444ba418fa3STom Herbert 			}
445ca065d0cSEric Dumazet 			badness = score;
446ca065d0cSEric Dumazet 			result = sk;
4475051ebd2SEric Dumazet 		}
4485051ebd2SEric Dumazet 	}
4495051ebd2SEric Dumazet 	return result;
4505051ebd2SEric Dumazet }
4515051ebd2SEric Dumazet 
452db8dac20SDavid S. Miller /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
453db8dac20SDavid S. Miller  * harder than this. -DaveM
454db8dac20SDavid S. Miller  */
455fce82338SPavel Emelyanov struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
456fb74c277SDavid Ahern 		__be16 sport, __be32 daddr, __be16 dport, int dif,
457fb74c277SDavid Ahern 		int sdif, struct udp_table *udptable, struct sk_buff *skb)
458db8dac20SDavid S. Miller {
4594cdeeee9SPeter Oskolkov 	struct sock *result;
460db8dac20SDavid S. Miller 	unsigned short hnum = ntohs(dport);
4614cdeeee9SPeter Oskolkov 	unsigned int hash2, slot2;
4624cdeeee9SPeter Oskolkov 	struct udp_hslot *hslot2;
46363a6fff3SRobert Shearman 	bool exact_dif = udp_lib_exact_dif_match(net, skb);
464db8dac20SDavid S. Miller 
465f0b1e64cSMartin KaFai Lau 	hash2 = ipv4_portaddr_hash(net, daddr, hnum);
4665051ebd2SEric Dumazet 	slot2 = hash2 & udptable->mask;
4675051ebd2SEric Dumazet 	hslot2 = &udptable->hash2[slot2];
4685051ebd2SEric Dumazet 
4695051ebd2SEric Dumazet 	result = udp4_lib_lookup2(net, saddr, sport,
470fb74c277SDavid Ahern 				  daddr, hnum, dif, sdif,
471*73545373STim Beale 				  hslot2, skb);
4725051ebd2SEric Dumazet 	if (!result) {
473f0b1e64cSMartin KaFai Lau 		hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
4745051ebd2SEric Dumazet 		slot2 = hash2 & udptable->mask;
4755051ebd2SEric Dumazet 		hslot2 = &udptable->hash2[slot2];
4765051ebd2SEric Dumazet 
4771223c67cSJorge Boncompte [DTI2] 		result = udp4_lib_lookup2(net, saddr, sport,
4784cdeeee9SPeter Oskolkov 					  htonl(INADDR_ANY), hnum, dif, sdif,
479*73545373STim Beale 					  hslot2, skb);
4805051ebd2SEric Dumazet 	}
48188e235b8SEnrico Weigelt 	if (IS_ERR(result))
4828217ca65SMartin KaFai Lau 		return NULL;
4835051ebd2SEric Dumazet 	return result;
4845051ebd2SEric Dumazet }
485fce82338SPavel Emelyanov EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
486db8dac20SDavid S. Miller 
487607c4aafSKOVACS Krisztian static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
488607c4aafSKOVACS Krisztian 						 __be16 sport, __be16 dport,
489645ca708SEric Dumazet 						 struct udp_table *udptable)
490607c4aafSKOVACS Krisztian {
491607c4aafSKOVACS Krisztian 	const struct iphdr *iph = ip_hdr(skb);
492607c4aafSKOVACS Krisztian 
493ed7cbbceSAlexander Duyck 	return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
494607c4aafSKOVACS Krisztian 				 iph->daddr, dport, inet_iif(skb),
495fb74c277SDavid Ahern 				 inet_sdif(skb), udptable, skb);
496607c4aafSKOVACS Krisztian }
497607c4aafSKOVACS Krisztian 
49863058308STom Herbert struct sock *udp4_lib_lookup_skb(struct sk_buff *skb,
49963058308STom Herbert 				 __be16 sport, __be16 dport)
50063058308STom Herbert {
501ed7cbbceSAlexander Duyck 	return __udp4_lib_lookup_skb(skb, sport, dport, &udp_table);
50263058308STom Herbert }
50363058308STom Herbert EXPORT_SYMBOL_GPL(udp4_lib_lookup_skb);
50463058308STom Herbert 
505ca065d0cSEric Dumazet /* Must be called under rcu_read_lock().
506ca065d0cSEric Dumazet  * Does increment socket refcount.
507ca065d0cSEric Dumazet  */
5086e86000cSArnd Bergmann #if IS_ENABLED(CONFIG_NF_TPROXY_IPV4) || IS_ENABLED(CONFIG_NF_SOCKET_IPV4)
509bcd41303SKOVACS Krisztian struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
510bcd41303SKOVACS Krisztian 			     __be32 daddr, __be16 dport, int dif)
511bcd41303SKOVACS Krisztian {
512ca065d0cSEric Dumazet 	struct sock *sk;
513ca065d0cSEric Dumazet 
514ca065d0cSEric Dumazet 	sk = __udp4_lib_lookup(net, saddr, sport, daddr, dport,
515fb74c277SDavid Ahern 			       dif, 0, &udp_table, NULL);
51641c6d650SReshetova, Elena 	if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
517ca065d0cSEric Dumazet 		sk = NULL;
518ca065d0cSEric Dumazet 	return sk;
519bcd41303SKOVACS Krisztian }
520bcd41303SKOVACS Krisztian EXPORT_SYMBOL_GPL(udp4_lib_lookup);
521ca065d0cSEric Dumazet #endif
522bcd41303SKOVACS Krisztian 
523421b3885SShawn Bohrer static inline bool __udp_is_mcast_sock(struct net *net, struct sock *sk,
524421b3885SShawn Bohrer 				       __be16 loc_port, __be32 loc_addr,
525421b3885SShawn Bohrer 				       __be16 rmt_port, __be32 rmt_addr,
526fb74c277SDavid Ahern 				       int dif, int sdif, unsigned short hnum)
527421b3885SShawn Bohrer {
528421b3885SShawn Bohrer 	struct inet_sock *inet = inet_sk(sk);
529421b3885SShawn Bohrer 
530421b3885SShawn Bohrer 	if (!net_eq(sock_net(sk), net) ||
531421b3885SShawn Bohrer 	    udp_sk(sk)->udp_port_hash != hnum ||
532421b3885SShawn Bohrer 	    (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
533421b3885SShawn Bohrer 	    (inet->inet_dport != rmt_port && inet->inet_dport) ||
534421b3885SShawn Bohrer 	    (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) ||
535421b3885SShawn Bohrer 	    ipv6_only_sock(sk) ||
53682ba25c6STim Beale 	    !udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif))
537421b3885SShawn Bohrer 		return false;
53860d9b031SDavid Ahern 	if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif, sdif))
539421b3885SShawn Bohrer 		return false;
540421b3885SShawn Bohrer 	return true;
541421b3885SShawn Bohrer }
542421b3885SShawn Bohrer 
543a36e185eSStefano Brivio DEFINE_STATIC_KEY_FALSE(udp_encap_needed_key);
544a36e185eSStefano Brivio void udp_encap_enable(void)
545a36e185eSStefano Brivio {
5469c480601SPaolo Abeni 	static_branch_inc(&udp_encap_needed_key);
547a36e185eSStefano Brivio }
548a36e185eSStefano Brivio EXPORT_SYMBOL(udp_encap_enable);
549a36e185eSStefano Brivio 
550e7cc0824SStefano Brivio /* Handler for tunnels with arbitrary destination ports: no socket lookup, go
551e7cc0824SStefano Brivio  * through error handlers in encapsulations looking for a match.
552e7cc0824SStefano Brivio  */
553e7cc0824SStefano Brivio static int __udp4_lib_err_encap_no_sk(struct sk_buff *skb, u32 info)
554e7cc0824SStefano Brivio {
555e7cc0824SStefano Brivio 	int i;
556e7cc0824SStefano Brivio 
557e7cc0824SStefano Brivio 	for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) {
558e7cc0824SStefano Brivio 		int (*handler)(struct sk_buff *skb, u32 info);
55992b95364SPaolo Abeni 		const struct ip_tunnel_encap_ops *encap;
560e7cc0824SStefano Brivio 
56192b95364SPaolo Abeni 		encap = rcu_dereference(iptun_encaps[i]);
56292b95364SPaolo Abeni 		if (!encap)
563e7cc0824SStefano Brivio 			continue;
56492b95364SPaolo Abeni 		handler = encap->err_handler;
565e7cc0824SStefano Brivio 		if (handler && !handler(skb, info))
566e7cc0824SStefano Brivio 			return 0;
567e7cc0824SStefano Brivio 	}
568e7cc0824SStefano Brivio 
569e7cc0824SStefano Brivio 	return -ENOENT;
570e7cc0824SStefano Brivio }
571e7cc0824SStefano Brivio 
572a36e185eSStefano Brivio /* Try to match ICMP errors to UDP tunnels by looking up a socket without
573a36e185eSStefano Brivio  * reversing source and destination port: this will match tunnels that force the
574a36e185eSStefano Brivio  * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that
575a36e185eSStefano Brivio  * lwtunnels might actually break this assumption by being configured with
576a36e185eSStefano Brivio  * different destination ports on endpoints, in this case we won't be able to
577a36e185eSStefano Brivio  * trace ICMP messages back to them.
578a36e185eSStefano Brivio  *
579e7cc0824SStefano Brivio  * If this doesn't match any socket, probe tunnels with arbitrary destination
580e7cc0824SStefano Brivio  * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port
581e7cc0824SStefano Brivio  * we've sent packets to won't necessarily match the local destination port.
582e7cc0824SStefano Brivio  *
583a36e185eSStefano Brivio  * Then ask the tunnel implementation to match the error against a valid
584a36e185eSStefano Brivio  * association.
585a36e185eSStefano Brivio  *
586e7cc0824SStefano Brivio  * Return an error if we can't find a match, the socket if we need further
587e7cc0824SStefano Brivio  * processing, zero otherwise.
588a36e185eSStefano Brivio  */
589a36e185eSStefano Brivio static struct sock *__udp4_lib_err_encap(struct net *net,
590a36e185eSStefano Brivio 					 const struct iphdr *iph,
591a36e185eSStefano Brivio 					 struct udphdr *uh,
592a36e185eSStefano Brivio 					 struct udp_table *udptable,
593e7cc0824SStefano Brivio 					 struct sk_buff *skb, u32 info)
594a36e185eSStefano Brivio {
595a36e185eSStefano Brivio 	int network_offset, transport_offset;
596a36e185eSStefano Brivio 	struct sock *sk;
597a36e185eSStefano Brivio 
598a36e185eSStefano Brivio 	network_offset = skb_network_offset(skb);
599a36e185eSStefano Brivio 	transport_offset = skb_transport_offset(skb);
600a36e185eSStefano Brivio 
601a36e185eSStefano Brivio 	/* Network header needs to point to the outer IPv4 header inside ICMP */
602a36e185eSStefano Brivio 	skb_reset_network_header(skb);
603a36e185eSStefano Brivio 
604a36e185eSStefano Brivio 	/* Transport header needs to point to the UDP header */
605a36e185eSStefano Brivio 	skb_set_transport_header(skb, iph->ihl << 2);
606a36e185eSStefano Brivio 
607e7cc0824SStefano Brivio 	sk = __udp4_lib_lookup(net, iph->daddr, uh->source,
608e7cc0824SStefano Brivio 			       iph->saddr, uh->dest, skb->dev->ifindex, 0,
609e7cc0824SStefano Brivio 			       udptable, NULL);
610e7cc0824SStefano Brivio 	if (sk) {
611e7cc0824SStefano Brivio 		int (*lookup)(struct sock *sk, struct sk_buff *skb);
612e7cc0824SStefano Brivio 		struct udp_sock *up = udp_sk(sk);
613e7cc0824SStefano Brivio 
614a36e185eSStefano Brivio 		lookup = READ_ONCE(up->encap_err_lookup);
615a36e185eSStefano Brivio 		if (!lookup || lookup(sk, skb))
616a36e185eSStefano Brivio 			sk = NULL;
617e7cc0824SStefano Brivio 	}
618e7cc0824SStefano Brivio 
619e7cc0824SStefano Brivio 	if (!sk)
620e7cc0824SStefano Brivio 		sk = ERR_PTR(__udp4_lib_err_encap_no_sk(skb, info));
621a36e185eSStefano Brivio 
622a36e185eSStefano Brivio 	skb_set_transport_header(skb, transport_offset);
623a36e185eSStefano Brivio 	skb_set_network_header(skb, network_offset);
624a36e185eSStefano Brivio 
625a36e185eSStefano Brivio 	return sk;
626a36e185eSStefano Brivio }
627a36e185eSStefano Brivio 
628db8dac20SDavid S. Miller /*
629db8dac20SDavid S. Miller  * This routine is called by the ICMP module when it gets some
630db8dac20SDavid S. Miller  * sort of error condition.  If err < 0 then the socket should
631db8dac20SDavid S. Miller  * be closed and the error returned to the user.  If err > 0
632db8dac20SDavid S. Miller  * it's just the icmp type << 8 | icmp code.
633db8dac20SDavid S. Miller  * Header points to the ip header of the error packet. We move
634db8dac20SDavid S. Miller  * on past this. Then (as it used to claim before adjustment)
635db8dac20SDavid S. Miller  * header points to the first 8 bytes of the udp header.  We need
636db8dac20SDavid S. Miller  * to find the appropriate port.
637db8dac20SDavid S. Miller  */
638db8dac20SDavid S. Miller 
63932bbd879SStefano Brivio int __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
640db8dac20SDavid S. Miller {
641db8dac20SDavid S. Miller 	struct inet_sock *inet;
642b71d1d42SEric Dumazet 	const struct iphdr *iph = (const struct iphdr *)skb->data;
643db8dac20SDavid S. Miller 	struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
644db8dac20SDavid S. Miller 	const int type = icmp_hdr(skb)->type;
645db8dac20SDavid S. Miller 	const int code = icmp_hdr(skb)->code;
646a36e185eSStefano Brivio 	bool tunnel = false;
647db8dac20SDavid S. Miller 	struct sock *sk;
648db8dac20SDavid S. Miller 	int harderr;
649db8dac20SDavid S. Miller 	int err;
650fd54d716SPavel Emelyanov 	struct net *net = dev_net(skb->dev);
651db8dac20SDavid S. Miller 
652fd54d716SPavel Emelyanov 	sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
653f64bf6b8SMike Manning 			       iph->saddr, uh->source, skb->dev->ifindex,
654f64bf6b8SMike Manning 			       inet_sdif(skb), udptable, NULL);
65551456b29SIan Morris 	if (!sk) {
656a36e185eSStefano Brivio 		/* No socket for error: try tunnels before discarding */
657e7cc0824SStefano Brivio 		sk = ERR_PTR(-ENOENT);
658e7cc0824SStefano Brivio 		if (static_branch_unlikely(&udp_encap_needed_key)) {
659e7cc0824SStefano Brivio 			sk = __udp4_lib_err_encap(net, iph, uh, udptable, skb,
660e7cc0824SStefano Brivio 						  info);
661e7cc0824SStefano Brivio 			if (!sk)
662e7cc0824SStefano Brivio 				return 0;
663a36e185eSStefano Brivio 		}
664e7cc0824SStefano Brivio 
665e7cc0824SStefano Brivio 		if (IS_ERR(sk)) {
666e7cc0824SStefano Brivio 			__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
667e7cc0824SStefano Brivio 			return PTR_ERR(sk);
668e7cc0824SStefano Brivio 		}
669e7cc0824SStefano Brivio 
670a36e185eSStefano Brivio 		tunnel = true;
671db8dac20SDavid S. Miller 	}
672db8dac20SDavid S. Miller 
673db8dac20SDavid S. Miller 	err = 0;
674db8dac20SDavid S. Miller 	harderr = 0;
675db8dac20SDavid S. Miller 	inet = inet_sk(sk);
676db8dac20SDavid S. Miller 
677db8dac20SDavid S. Miller 	switch (type) {
678db8dac20SDavid S. Miller 	default:
679db8dac20SDavid S. Miller 	case ICMP_TIME_EXCEEDED:
680db8dac20SDavid S. Miller 		err = EHOSTUNREACH;
681db8dac20SDavid S. Miller 		break;
682db8dac20SDavid S. Miller 	case ICMP_SOURCE_QUENCH:
683db8dac20SDavid S. Miller 		goto out;
684db8dac20SDavid S. Miller 	case ICMP_PARAMETERPROB:
685db8dac20SDavid S. Miller 		err = EPROTO;
686db8dac20SDavid S. Miller 		harderr = 1;
687db8dac20SDavid S. Miller 		break;
688db8dac20SDavid S. Miller 	case ICMP_DEST_UNREACH:
689db8dac20SDavid S. Miller 		if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
69036393395SDavid S. Miller 			ipv4_sk_update_pmtu(skb, sk, info);
691db8dac20SDavid S. Miller 			if (inet->pmtudisc != IP_PMTUDISC_DONT) {
692db8dac20SDavid S. Miller 				err = EMSGSIZE;
693db8dac20SDavid S. Miller 				harderr = 1;
694db8dac20SDavid S. Miller 				break;
695db8dac20SDavid S. Miller 			}
696db8dac20SDavid S. Miller 			goto out;
697db8dac20SDavid S. Miller 		}
698db8dac20SDavid S. Miller 		err = EHOSTUNREACH;
699db8dac20SDavid S. Miller 		if (code <= NR_ICMP_UNREACH) {
700db8dac20SDavid S. Miller 			harderr = icmp_err_convert[code].fatal;
701db8dac20SDavid S. Miller 			err = icmp_err_convert[code].errno;
702db8dac20SDavid S. Miller 		}
703db8dac20SDavid S. Miller 		break;
70455be7a9cSDavid S. Miller 	case ICMP_REDIRECT:
70555be7a9cSDavid S. Miller 		ipv4_sk_redirect(skb, sk);
7061a462d18SDuan Jiong 		goto out;
707db8dac20SDavid S. Miller 	}
708db8dac20SDavid S. Miller 
709db8dac20SDavid S. Miller 	/*
710db8dac20SDavid S. Miller 	 *      RFC1122: OK.  Passes ICMP errors back to application, as per
711db8dac20SDavid S. Miller 	 *	4.1.3.3.
712db8dac20SDavid S. Miller 	 */
713a36e185eSStefano Brivio 	if (tunnel) {
714a36e185eSStefano Brivio 		/* ...not for tunnels though: we don't have a sending socket */
715a36e185eSStefano Brivio 		goto out;
716a36e185eSStefano Brivio 	}
717db8dac20SDavid S. Miller 	if (!inet->recverr) {
718db8dac20SDavid S. Miller 		if (!harderr || sk->sk_state != TCP_ESTABLISHED)
719db8dac20SDavid S. Miller 			goto out;
720b1faf566SEric Dumazet 	} else
721db8dac20SDavid S. Miller 		ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
722b1faf566SEric Dumazet 
723db8dac20SDavid S. Miller 	sk->sk_err = err;
724db8dac20SDavid S. Miller 	sk->sk_error_report(sk);
725db8dac20SDavid S. Miller out:
72632bbd879SStefano Brivio 	return 0;
727db8dac20SDavid S. Miller }
728db8dac20SDavid S. Miller 
72932bbd879SStefano Brivio int udp_err(struct sk_buff *skb, u32 info)
730db8dac20SDavid S. Miller {
73132bbd879SStefano Brivio 	return __udp4_lib_err(skb, info, &udp_table);
732db8dac20SDavid S. Miller }
733db8dac20SDavid S. Miller 
734db8dac20SDavid S. Miller /*
735db8dac20SDavid S. Miller  * Throw away all pending data and cancel the corking. Socket is locked.
736db8dac20SDavid S. Miller  */
73736d926b9SDenis V. Lunev void udp_flush_pending_frames(struct sock *sk)
738db8dac20SDavid S. Miller {
739db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
740db8dac20SDavid S. Miller 
741db8dac20SDavid S. Miller 	if (up->pending) {
742db8dac20SDavid S. Miller 		up->len = 0;
743db8dac20SDavid S. Miller 		up->pending = 0;
744db8dac20SDavid S. Miller 		ip_flush_pending_frames(sk);
745db8dac20SDavid S. Miller 	}
746db8dac20SDavid S. Miller }
74736d926b9SDenis V. Lunev EXPORT_SYMBOL(udp_flush_pending_frames);
748db8dac20SDavid S. Miller 
749db8dac20SDavid S. Miller /**
750f6b9664fSHerbert Xu  * 	udp4_hwcsum  -  handle outgoing HW checksumming
751db8dac20SDavid S. Miller  * 	@skb: 	sk_buff containing the filled-in UDP header
752db8dac20SDavid S. Miller  * 	        (checksum field must be zeroed out)
753f6b9664fSHerbert Xu  *	@src:	source IP address
754f6b9664fSHerbert Xu  *	@dst:	destination IP address
755db8dac20SDavid S. Miller  */
756c26bf4a5SThomas Graf void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
757db8dac20SDavid S. Miller {
758db8dac20SDavid S. Miller 	struct udphdr *uh = udp_hdr(skb);
759f6b9664fSHerbert Xu 	int offset = skb_transport_offset(skb);
760f6b9664fSHerbert Xu 	int len = skb->len - offset;
761f6b9664fSHerbert Xu 	int hlen = len;
762db8dac20SDavid S. Miller 	__wsum csum = 0;
763db8dac20SDavid S. Miller 
764ebbe495fSWANG Cong 	if (!skb_has_frag_list(skb)) {
765db8dac20SDavid S. Miller 		/*
766db8dac20SDavid S. Miller 		 * Only one fragment on the socket.
767db8dac20SDavid S. Miller 		 */
768db8dac20SDavid S. Miller 		skb->csum_start = skb_transport_header(skb) - skb->head;
769db8dac20SDavid S. Miller 		skb->csum_offset = offsetof(struct udphdr, check);
770f6b9664fSHerbert Xu 		uh->check = ~csum_tcpudp_magic(src, dst, len,
771f6b9664fSHerbert Xu 					       IPPROTO_UDP, 0);
772db8dac20SDavid S. Miller 	} else {
773ebbe495fSWANG Cong 		struct sk_buff *frags;
774ebbe495fSWANG Cong 
775db8dac20SDavid S. Miller 		/*
776db8dac20SDavid S. Miller 		 * HW-checksum won't work as there are two or more
777db8dac20SDavid S. Miller 		 * fragments on the socket so that all csums of sk_buffs
778db8dac20SDavid S. Miller 		 * should be together
779db8dac20SDavid S. Miller 		 */
780ebbe495fSWANG Cong 		skb_walk_frags(skb, frags) {
781f6b9664fSHerbert Xu 			csum = csum_add(csum, frags->csum);
782f6b9664fSHerbert Xu 			hlen -= frags->len;
783ebbe495fSWANG Cong 		}
784db8dac20SDavid S. Miller 
785f6b9664fSHerbert Xu 		csum = skb_checksum(skb, offset, hlen, csum);
786db8dac20SDavid S. Miller 		skb->ip_summed = CHECKSUM_NONE;
787db8dac20SDavid S. Miller 
788db8dac20SDavid S. Miller 		uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
789db8dac20SDavid S. Miller 		if (uh->check == 0)
790db8dac20SDavid S. Miller 			uh->check = CSUM_MANGLED_0;
791db8dac20SDavid S. Miller 	}
792db8dac20SDavid S. Miller }
793c26bf4a5SThomas Graf EXPORT_SYMBOL_GPL(udp4_hwcsum);
794db8dac20SDavid S. Miller 
795af5fcba7STom Herbert /* Function to set UDP checksum for an IPv4 UDP packet. This is intended
796af5fcba7STom Herbert  * for the simple case like when setting the checksum for a UDP tunnel.
797af5fcba7STom Herbert  */
798af5fcba7STom Herbert void udp_set_csum(bool nocheck, struct sk_buff *skb,
799af5fcba7STom Herbert 		  __be32 saddr, __be32 daddr, int len)
800af5fcba7STom Herbert {
801af5fcba7STom Herbert 	struct udphdr *uh = udp_hdr(skb);
802af5fcba7STom Herbert 
803179bc67fSEdward Cree 	if (nocheck) {
804af5fcba7STom Herbert 		uh->check = 0;
805179bc67fSEdward Cree 	} else if (skb_is_gso(skb)) {
806af5fcba7STom Herbert 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
807179bc67fSEdward Cree 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) {
808179bc67fSEdward Cree 		uh->check = 0;
809179bc67fSEdward Cree 		uh->check = udp_v4_check(len, saddr, daddr, lco_csum(skb));
810179bc67fSEdward Cree 		if (uh->check == 0)
811179bc67fSEdward Cree 			uh->check = CSUM_MANGLED_0;
812d75f1306SEdward Cree 	} else {
813af5fcba7STom Herbert 		skb->ip_summed = CHECKSUM_PARTIAL;
814af5fcba7STom Herbert 		skb->csum_start = skb_transport_header(skb) - skb->head;
815af5fcba7STom Herbert 		skb->csum_offset = offsetof(struct udphdr, check);
816af5fcba7STom Herbert 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
817af5fcba7STom Herbert 	}
818af5fcba7STom Herbert }
819af5fcba7STom Herbert EXPORT_SYMBOL(udp_set_csum);
820af5fcba7STom Herbert 
821bec1f6f6SWillem de Bruijn static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4,
822bec1f6f6SWillem de Bruijn 			struct inet_cork *cork)
823f6b9664fSHerbert Xu {
824f6b9664fSHerbert Xu 	struct sock *sk = skb->sk;
825f6b9664fSHerbert Xu 	struct inet_sock *inet = inet_sk(sk);
826f6b9664fSHerbert Xu 	struct udphdr *uh;
827f6b9664fSHerbert Xu 	int err = 0;
828f6b9664fSHerbert Xu 	int is_udplite = IS_UDPLITE(sk);
829f6b9664fSHerbert Xu 	int offset = skb_transport_offset(skb);
830f6b9664fSHerbert Xu 	int len = skb->len - offset;
831f6b9664fSHerbert Xu 	__wsum csum = 0;
832f6b9664fSHerbert Xu 
833f6b9664fSHerbert Xu 	/*
834f6b9664fSHerbert Xu 	 * Create a UDP header
835f6b9664fSHerbert Xu 	 */
836f6b9664fSHerbert Xu 	uh = udp_hdr(skb);
837f6b9664fSHerbert Xu 	uh->source = inet->inet_sport;
83879ab0531SDavid S. Miller 	uh->dest = fl4->fl4_dport;
839f6b9664fSHerbert Xu 	uh->len = htons(len);
840f6b9664fSHerbert Xu 	uh->check = 0;
841f6b9664fSHerbert Xu 
842bec1f6f6SWillem de Bruijn 	if (cork->gso_size) {
843bec1f6f6SWillem de Bruijn 		const int hlen = skb_network_header_len(skb) +
844bec1f6f6SWillem de Bruijn 				 sizeof(struct udphdr);
845bec1f6f6SWillem de Bruijn 
8460f149c9fSWillem de Bruijn 		if (hlen + cork->gso_size > cork->fragsize) {
8470f149c9fSWillem de Bruijn 			kfree_skb(skb);
848bec1f6f6SWillem de Bruijn 			return -EINVAL;
8490f149c9fSWillem de Bruijn 		}
8500f149c9fSWillem de Bruijn 		if (skb->len > cork->gso_size * UDP_MAX_SEGMENTS) {
8510f149c9fSWillem de Bruijn 			kfree_skb(skb);
852bec1f6f6SWillem de Bruijn 			return -EINVAL;
8530f149c9fSWillem de Bruijn 		}
8540f149c9fSWillem de Bruijn 		if (sk->sk_no_check_tx) {
8550f149c9fSWillem de Bruijn 			kfree_skb(skb);
856a8c744a8SWillem de Bruijn 			return -EINVAL;
8570f149c9fSWillem de Bruijn 		}
858ff06342cSWillem de Bruijn 		if (skb->ip_summed != CHECKSUM_PARTIAL || is_udplite ||
8590f149c9fSWillem de Bruijn 		    dst_xfrm(skb_dst(skb))) {
8600f149c9fSWillem de Bruijn 			kfree_skb(skb);
861bec1f6f6SWillem de Bruijn 			return -EIO;
8620f149c9fSWillem de Bruijn 		}
863bec1f6f6SWillem de Bruijn 
864bec1f6f6SWillem de Bruijn 		skb_shinfo(skb)->gso_size = cork->gso_size;
865bec1f6f6SWillem de Bruijn 		skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4;
866dfec0ee2SAlexander Duyck 		skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(len - sizeof(uh),
867dfec0ee2SAlexander Duyck 							 cork->gso_size);
868a8c744a8SWillem de Bruijn 		goto csum_partial;
869bec1f6f6SWillem de Bruijn 	}
870bec1f6f6SWillem de Bruijn 
871f6b9664fSHerbert Xu 	if (is_udplite)  				 /*     UDP-Lite      */
872f6b9664fSHerbert Xu 		csum = udplite_csum(skb);
873f6b9664fSHerbert Xu 
874ab2fb7e3SWillem de Bruijn 	else if (sk->sk_no_check_tx) {			 /* UDP csum off */
875f6b9664fSHerbert Xu 
876f6b9664fSHerbert Xu 		skb->ip_summed = CHECKSUM_NONE;
877f6b9664fSHerbert Xu 		goto send;
878f6b9664fSHerbert Xu 
879f6b9664fSHerbert Xu 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
880a8c744a8SWillem de Bruijn csum_partial:
881f6b9664fSHerbert Xu 
88279ab0531SDavid S. Miller 		udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
883f6b9664fSHerbert Xu 		goto send;
884f6b9664fSHerbert Xu 
885f6b9664fSHerbert Xu 	} else
886f6b9664fSHerbert Xu 		csum = udp_csum(skb);
887f6b9664fSHerbert Xu 
888f6b9664fSHerbert Xu 	/* add protocol-dependent pseudo-header */
88979ab0531SDavid S. Miller 	uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
890f6b9664fSHerbert Xu 				      sk->sk_protocol, csum);
891f6b9664fSHerbert Xu 	if (uh->check == 0)
892f6b9664fSHerbert Xu 		uh->check = CSUM_MANGLED_0;
893f6b9664fSHerbert Xu 
894f6b9664fSHerbert Xu send:
895b5ec8eeaSEric Dumazet 	err = ip_send_skb(sock_net(sk), skb);
896f6b9664fSHerbert Xu 	if (err) {
897f6b9664fSHerbert Xu 		if (err == -ENOBUFS && !inet->recverr) {
8986aef70a8SEric Dumazet 			UDP_INC_STATS(sock_net(sk),
899f6b9664fSHerbert Xu 				      UDP_MIB_SNDBUFERRORS, is_udplite);
900f6b9664fSHerbert Xu 			err = 0;
901f6b9664fSHerbert Xu 		}
902f6b9664fSHerbert Xu 	} else
9036aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
904f6b9664fSHerbert Xu 			      UDP_MIB_OUTDATAGRAMS, is_udplite);
905f6b9664fSHerbert Xu 	return err;
906f6b9664fSHerbert Xu }
907f6b9664fSHerbert Xu 
908db8dac20SDavid S. Miller /*
909db8dac20SDavid S. Miller  * Push out all pending data as one UDP datagram. Socket is locked.
910db8dac20SDavid S. Miller  */
9118822b64aSHannes Frederic Sowa int udp_push_pending_frames(struct sock *sk)
912db8dac20SDavid S. Miller {
913db8dac20SDavid S. Miller 	struct udp_sock  *up = udp_sk(sk);
914db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
915b6f21b26SDavid S. Miller 	struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
916db8dac20SDavid S. Miller 	struct sk_buff *skb;
917db8dac20SDavid S. Miller 	int err = 0;
918db8dac20SDavid S. Miller 
91977968b78SDavid S. Miller 	skb = ip_finish_skb(sk, fl4);
920f6b9664fSHerbert Xu 	if (!skb)
921db8dac20SDavid S. Miller 		goto out;
922db8dac20SDavid S. Miller 
923bec1f6f6SWillem de Bruijn 	err = udp_send_skb(skb, fl4, &inet->cork.base);
924db8dac20SDavid S. Miller 
925db8dac20SDavid S. Miller out:
926db8dac20SDavid S. Miller 	up->len = 0;
927db8dac20SDavid S. Miller 	up->pending = 0;
928db8dac20SDavid S. Miller 	return err;
929db8dac20SDavid S. Miller }
9308822b64aSHannes Frederic Sowa EXPORT_SYMBOL(udp_push_pending_frames);
931db8dac20SDavid S. Miller 
9322e8de857SWillem de Bruijn static int __udp_cmsg_send(struct cmsghdr *cmsg, u16 *gso_size)
9332e8de857SWillem de Bruijn {
9342e8de857SWillem de Bruijn 	switch (cmsg->cmsg_type) {
9352e8de857SWillem de Bruijn 	case UDP_SEGMENT:
9362e8de857SWillem de Bruijn 		if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u16)))
9372e8de857SWillem de Bruijn 			return -EINVAL;
9382e8de857SWillem de Bruijn 		*gso_size = *(__u16 *)CMSG_DATA(cmsg);
9392e8de857SWillem de Bruijn 		return 0;
9402e8de857SWillem de Bruijn 	default:
9412e8de857SWillem de Bruijn 		return -EINVAL;
9422e8de857SWillem de Bruijn 	}
9432e8de857SWillem de Bruijn }
9442e8de857SWillem de Bruijn 
9452e8de857SWillem de Bruijn int udp_cmsg_send(struct sock *sk, struct msghdr *msg, u16 *gso_size)
9462e8de857SWillem de Bruijn {
9472e8de857SWillem de Bruijn 	struct cmsghdr *cmsg;
9482e8de857SWillem de Bruijn 	bool need_ip = false;
9492e8de857SWillem de Bruijn 	int err;
9502e8de857SWillem de Bruijn 
9512e8de857SWillem de Bruijn 	for_each_cmsghdr(cmsg, msg) {
9522e8de857SWillem de Bruijn 		if (!CMSG_OK(msg, cmsg))
9532e8de857SWillem de Bruijn 			return -EINVAL;
9542e8de857SWillem de Bruijn 
9552e8de857SWillem de Bruijn 		if (cmsg->cmsg_level != SOL_UDP) {
9562e8de857SWillem de Bruijn 			need_ip = true;
9572e8de857SWillem de Bruijn 			continue;
9582e8de857SWillem de Bruijn 		}
9592e8de857SWillem de Bruijn 
9602e8de857SWillem de Bruijn 		err = __udp_cmsg_send(cmsg, gso_size);
9612e8de857SWillem de Bruijn 		if (err)
9622e8de857SWillem de Bruijn 			return err;
9632e8de857SWillem de Bruijn 	}
9642e8de857SWillem de Bruijn 
9652e8de857SWillem de Bruijn 	return need_ip;
9662e8de857SWillem de Bruijn }
9672e8de857SWillem de Bruijn EXPORT_SYMBOL_GPL(udp_cmsg_send);
9682e8de857SWillem de Bruijn 
9691b784140SYing Xue int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
970db8dac20SDavid S. Miller {
971db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
972db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
9731cedee13SAndrey Ignatov 	DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
974e474995fSDavid S. Miller 	struct flowi4 fl4_stack;
975b6f21b26SDavid S. Miller 	struct flowi4 *fl4;
976db8dac20SDavid S. Miller 	int ulen = len;
977db8dac20SDavid S. Miller 	struct ipcm_cookie ipc;
978db8dac20SDavid S. Miller 	struct rtable *rt = NULL;
979db8dac20SDavid S. Miller 	int free = 0;
980db8dac20SDavid S. Miller 	int connected = 0;
981db8dac20SDavid S. Miller 	__be32 daddr, faddr, saddr;
982db8dac20SDavid S. Miller 	__be16 dport;
983db8dac20SDavid S. Miller 	u8  tos;
984db8dac20SDavid S. Miller 	int err, is_udplite = IS_UDPLITE(sk);
985db8dac20SDavid S. Miller 	int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
986db8dac20SDavid S. Miller 	int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
987903ab86dSHerbert Xu 	struct sk_buff *skb;
988f6d8bd05SEric Dumazet 	struct ip_options_data opt_copy;
989db8dac20SDavid S. Miller 
990db8dac20SDavid S. Miller 	if (len > 0xFFFF)
991db8dac20SDavid S. Miller 		return -EMSGSIZE;
992db8dac20SDavid S. Miller 
993db8dac20SDavid S. Miller 	/*
994db8dac20SDavid S. Miller 	 *	Check the flags.
995db8dac20SDavid S. Miller 	 */
996db8dac20SDavid S. Miller 
997db8dac20SDavid S. Miller 	if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
998db8dac20SDavid S. Miller 		return -EOPNOTSUPP;
999db8dac20SDavid S. Miller 
1000903ab86dSHerbert Xu 	getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
1001903ab86dSHerbert Xu 
1002f5fca608SDavid S. Miller 	fl4 = &inet->cork.fl.u.ip4;
1003db8dac20SDavid S. Miller 	if (up->pending) {
1004db8dac20SDavid S. Miller 		/*
1005db8dac20SDavid S. Miller 		 * There are pending frames.
1006db8dac20SDavid S. Miller 		 * The socket lock must be held while it's corked.
1007db8dac20SDavid S. Miller 		 */
1008db8dac20SDavid S. Miller 		lock_sock(sk);
1009db8dac20SDavid S. Miller 		if (likely(up->pending)) {
1010db8dac20SDavid S. Miller 			if (unlikely(up->pending != AF_INET)) {
1011db8dac20SDavid S. Miller 				release_sock(sk);
1012db8dac20SDavid S. Miller 				return -EINVAL;
1013db8dac20SDavid S. Miller 			}
1014db8dac20SDavid S. Miller 			goto do_append_data;
1015db8dac20SDavid S. Miller 		}
1016db8dac20SDavid S. Miller 		release_sock(sk);
1017db8dac20SDavid S. Miller 	}
1018db8dac20SDavid S. Miller 	ulen += sizeof(struct udphdr);
1019db8dac20SDavid S. Miller 
1020db8dac20SDavid S. Miller 	/*
1021db8dac20SDavid S. Miller 	 *	Get and verify the address.
1022db8dac20SDavid S. Miller 	 */
10231cedee13SAndrey Ignatov 	if (usin) {
1024db8dac20SDavid S. Miller 		if (msg->msg_namelen < sizeof(*usin))
1025db8dac20SDavid S. Miller 			return -EINVAL;
1026db8dac20SDavid S. Miller 		if (usin->sin_family != AF_INET) {
1027db8dac20SDavid S. Miller 			if (usin->sin_family != AF_UNSPEC)
1028db8dac20SDavid S. Miller 				return -EAFNOSUPPORT;
1029db8dac20SDavid S. Miller 		}
1030db8dac20SDavid S. Miller 
1031db8dac20SDavid S. Miller 		daddr = usin->sin_addr.s_addr;
1032db8dac20SDavid S. Miller 		dport = usin->sin_port;
1033db8dac20SDavid S. Miller 		if (dport == 0)
1034db8dac20SDavid S. Miller 			return -EINVAL;
1035db8dac20SDavid S. Miller 	} else {
1036db8dac20SDavid S. Miller 		if (sk->sk_state != TCP_ESTABLISHED)
1037db8dac20SDavid S. Miller 			return -EDESTADDRREQ;
1038c720c7e8SEric Dumazet 		daddr = inet->inet_daddr;
1039c720c7e8SEric Dumazet 		dport = inet->inet_dport;
1040db8dac20SDavid S. Miller 		/* Open fast path for connected socket.
1041db8dac20SDavid S. Miller 		   Route will not be used, if at least one option is set.
1042db8dac20SDavid S. Miller 		 */
1043db8dac20SDavid S. Miller 		connected = 1;
1044db8dac20SDavid S. Miller 	}
1045c14ac945SSoheil Hassas Yeganeh 
104635178206SWillem de Bruijn 	ipcm_init_sk(&ipc, inet);
1047bec1f6f6SWillem de Bruijn 	ipc.gso_size = up->gso_size;
1048bf84a010SDaniel Borkmann 
1049db8dac20SDavid S. Miller 	if (msg->msg_controllen) {
10502e8de857SWillem de Bruijn 		err = udp_cmsg_send(sk, msg, &ipc.gso_size);
10512e8de857SWillem de Bruijn 		if (err > 0)
10522e8de857SWillem de Bruijn 			err = ip_cmsg_send(sk, msg, &ipc,
10532e8de857SWillem de Bruijn 					   sk->sk_family == AF_INET6);
10542e8de857SWillem de Bruijn 		if (unlikely(err < 0)) {
105591948309SEric Dumazet 			kfree(ipc.opt);
1056db8dac20SDavid S. Miller 			return err;
105791948309SEric Dumazet 		}
1058db8dac20SDavid S. Miller 		if (ipc.opt)
1059db8dac20SDavid S. Miller 			free = 1;
1060db8dac20SDavid S. Miller 		connected = 0;
1061db8dac20SDavid S. Miller 	}
1062f6d8bd05SEric Dumazet 	if (!ipc.opt) {
1063f6d8bd05SEric Dumazet 		struct ip_options_rcu *inet_opt;
1064f6d8bd05SEric Dumazet 
1065f6d8bd05SEric Dumazet 		rcu_read_lock();
1066f6d8bd05SEric Dumazet 		inet_opt = rcu_dereference(inet->inet_opt);
1067f6d8bd05SEric Dumazet 		if (inet_opt) {
1068f6d8bd05SEric Dumazet 			memcpy(&opt_copy, inet_opt,
1069f6d8bd05SEric Dumazet 			       sizeof(*inet_opt) + inet_opt->opt.optlen);
1070f6d8bd05SEric Dumazet 			ipc.opt = &opt_copy.opt;
1071f6d8bd05SEric Dumazet 		}
1072f6d8bd05SEric Dumazet 		rcu_read_unlock();
1073f6d8bd05SEric Dumazet 	}
1074db8dac20SDavid S. Miller 
10751cedee13SAndrey Ignatov 	if (cgroup_bpf_enabled && !connected) {
10761cedee13SAndrey Ignatov 		err = BPF_CGROUP_RUN_PROG_UDP4_SENDMSG_LOCK(sk,
10771cedee13SAndrey Ignatov 					    (struct sockaddr *)usin, &ipc.addr);
10781cedee13SAndrey Ignatov 		if (err)
10791cedee13SAndrey Ignatov 			goto out_free;
10801cedee13SAndrey Ignatov 		if (usin) {
10811cedee13SAndrey Ignatov 			if (usin->sin_port == 0) {
10821cedee13SAndrey Ignatov 				/* BPF program set invalid port. Reject it. */
10831cedee13SAndrey Ignatov 				err = -EINVAL;
10841cedee13SAndrey Ignatov 				goto out_free;
10851cedee13SAndrey Ignatov 			}
10861cedee13SAndrey Ignatov 			daddr = usin->sin_addr.s_addr;
10871cedee13SAndrey Ignatov 			dport = usin->sin_port;
10881cedee13SAndrey Ignatov 		}
10891cedee13SAndrey Ignatov 	}
10901cedee13SAndrey Ignatov 
1091db8dac20SDavid S. Miller 	saddr = ipc.addr;
1092db8dac20SDavid S. Miller 	ipc.addr = faddr = daddr;
1093db8dac20SDavid S. Miller 
1094f6d8bd05SEric Dumazet 	if (ipc.opt && ipc.opt->opt.srr) {
10951b97013bSAndrey Ignatov 		if (!daddr) {
10961b97013bSAndrey Ignatov 			err = -EINVAL;
10971b97013bSAndrey Ignatov 			goto out_free;
10981b97013bSAndrey Ignatov 		}
1099f6d8bd05SEric Dumazet 		faddr = ipc.opt->opt.faddr;
1100db8dac20SDavid S. Miller 		connected = 0;
1101db8dac20SDavid S. Miller 	}
1102aa661581SFrancesco Fusco 	tos = get_rttos(&ipc, inet);
1103db8dac20SDavid S. Miller 	if (sock_flag(sk, SOCK_LOCALROUTE) ||
1104db8dac20SDavid S. Miller 	    (msg->msg_flags & MSG_DONTROUTE) ||
1105f6d8bd05SEric Dumazet 	    (ipc.opt && ipc.opt->opt.is_strictroute)) {
1106db8dac20SDavid S. Miller 		tos |= RTO_ONLINK;
1107db8dac20SDavid S. Miller 		connected = 0;
1108db8dac20SDavid S. Miller 	}
1109db8dac20SDavid S. Miller 
1110db8dac20SDavid S. Miller 	if (ipv4_is_multicast(daddr)) {
1111854da991SRobert Shearman 		if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif))
1112db8dac20SDavid S. Miller 			ipc.oif = inet->mc_index;
1113db8dac20SDavid S. Miller 		if (!saddr)
1114db8dac20SDavid S. Miller 			saddr = inet->mc_addr;
1115db8dac20SDavid S. Miller 		connected = 0;
11169515a2e0SDavid Ahern 	} else if (!ipc.oif) {
111776e21053SErich E. Hoover 		ipc.oif = inet->uc_index;
11189515a2e0SDavid Ahern 	} else if (ipv4_is_lbcast(daddr) && inet->uc_index) {
11199515a2e0SDavid Ahern 		/* oif is set, packet is to local broadcast and
11209515a2e0SDavid Ahern 		 * and uc_index is set. oif is most likely set
11219515a2e0SDavid Ahern 		 * by sk_bound_dev_if. If uc_index != oif check if the
11229515a2e0SDavid Ahern 		 * oif is an L3 master and uc_index is an L3 slave.
11239515a2e0SDavid Ahern 		 * If so, we want to allow the send using the uc_index.
11249515a2e0SDavid Ahern 		 */
11259515a2e0SDavid Ahern 		if (ipc.oif != inet->uc_index &&
11269515a2e0SDavid Ahern 		    ipc.oif == l3mdev_master_ifindex_by_index(sock_net(sk),
11279515a2e0SDavid Ahern 							      inet->uc_index)) {
11289515a2e0SDavid Ahern 			ipc.oif = inet->uc_index;
11299515a2e0SDavid Ahern 		}
11309515a2e0SDavid Ahern 	}
1131db8dac20SDavid S. Miller 
1132db8dac20SDavid S. Miller 	if (connected)
1133db8dac20SDavid S. Miller 		rt = (struct rtable *)sk_dst_check(sk, 0);
1134db8dac20SDavid S. Miller 
113551456b29SIan Morris 	if (!rt) {
113684a3aa00SPavel Emelyanov 		struct net *net = sock_net(sk);
11379a24abfaSDavid Ahern 		__u8 flow_flags = inet_sk_flowi_flags(sk);
113884a3aa00SPavel Emelyanov 
1139e474995fSDavid S. Miller 		fl4 = &fl4_stack;
11409a24abfaSDavid Ahern 
11419a24abfaSDavid Ahern 		flowi4_init_output(fl4, ipc.oif, sk->sk_mark, tos,
11429a24abfaSDavid Ahern 				   RT_SCOPE_UNIVERSE, sk->sk_protocol,
11439a24abfaSDavid Ahern 				   flow_flags,
1144e2d118a1SLorenzo Colitti 				   faddr, saddr, dport, inet->inet_sport,
1145e2d118a1SLorenzo Colitti 				   sk->sk_uid);
1146c0951cbcSDavid S. Miller 
1147e474995fSDavid S. Miller 		security_sk_classify_flow(sk, flowi4_to_flowi(fl4));
1148e474995fSDavid S. Miller 		rt = ip_route_output_flow(net, fl4, sk);
1149b23dd4feSDavid S. Miller 		if (IS_ERR(rt)) {
1150b23dd4feSDavid S. Miller 			err = PTR_ERR(rt);
115106dc94b1SDavid S. Miller 			rt = NULL;
1152db8dac20SDavid S. Miller 			if (err == -ENETUNREACH)
1153f1d8cba6SEric Dumazet 				IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
1154db8dac20SDavid S. Miller 			goto out;
1155db8dac20SDavid S. Miller 		}
1156db8dac20SDavid S. Miller 
1157db8dac20SDavid S. Miller 		err = -EACCES;
1158db8dac20SDavid S. Miller 		if ((rt->rt_flags & RTCF_BROADCAST) &&
1159db8dac20SDavid S. Miller 		    !sock_flag(sk, SOCK_BROADCAST))
1160db8dac20SDavid S. Miller 			goto out;
1161db8dac20SDavid S. Miller 		if (connected)
1162d8d1f30bSChangli Gao 			sk_dst_set(sk, dst_clone(&rt->dst));
1163db8dac20SDavid S. Miller 	}
1164db8dac20SDavid S. Miller 
1165db8dac20SDavid S. Miller 	if (msg->msg_flags&MSG_CONFIRM)
1166db8dac20SDavid S. Miller 		goto do_confirm;
1167db8dac20SDavid S. Miller back_from_confirm:
1168db8dac20SDavid S. Miller 
1169e474995fSDavid S. Miller 	saddr = fl4->saddr;
1170db8dac20SDavid S. Miller 	if (!ipc.addr)
1171e474995fSDavid S. Miller 		daddr = ipc.addr = fl4->daddr;
1172db8dac20SDavid S. Miller 
1173903ab86dSHerbert Xu 	/* Lockless fast path for the non-corking case. */
1174903ab86dSHerbert Xu 	if (!corkreq) {
11751cd7884dSWillem de Bruijn 		struct inet_cork cork;
11761cd7884dSWillem de Bruijn 
1177f69e6d13SAl Viro 		skb = ip_make_skb(sk, fl4, getfrag, msg, ulen,
1178903ab86dSHerbert Xu 				  sizeof(struct udphdr), &ipc, &rt,
11791cd7884dSWillem de Bruijn 				  &cork, msg->msg_flags);
1180903ab86dSHerbert Xu 		err = PTR_ERR(skb);
118150c3a487SYOSHIFUJI Hideaki / 吉藤英明 		if (!IS_ERR_OR_NULL(skb))
1182bec1f6f6SWillem de Bruijn 			err = udp_send_skb(skb, fl4, &cork);
1183903ab86dSHerbert Xu 		goto out;
1184903ab86dSHerbert Xu 	}
1185903ab86dSHerbert Xu 
1186db8dac20SDavid S. Miller 	lock_sock(sk);
1187db8dac20SDavid S. Miller 	if (unlikely(up->pending)) {
1188db8dac20SDavid S. Miller 		/* The socket is already corked while preparing it. */
1189db8dac20SDavid S. Miller 		/* ... which is an evident application bug. --ANK */
1190db8dac20SDavid S. Miller 		release_sock(sk);
1191db8dac20SDavid S. Miller 
1192197df02cSMatteo Croce 		net_dbg_ratelimited("socket already corked\n");
1193db8dac20SDavid S. Miller 		err = -EINVAL;
1194db8dac20SDavid S. Miller 		goto out;
1195db8dac20SDavid S. Miller 	}
1196db8dac20SDavid S. Miller 	/*
1197db8dac20SDavid S. Miller 	 *	Now cork the socket to pend data.
1198db8dac20SDavid S. Miller 	 */
1199b6f21b26SDavid S. Miller 	fl4 = &inet->cork.fl.u.ip4;
1200b6f21b26SDavid S. Miller 	fl4->daddr = daddr;
1201b6f21b26SDavid S. Miller 	fl4->saddr = saddr;
12029cce96dfSDavid S. Miller 	fl4->fl4_dport = dport;
12039cce96dfSDavid S. Miller 	fl4->fl4_sport = inet->inet_sport;
1204db8dac20SDavid S. Miller 	up->pending = AF_INET;
1205db8dac20SDavid S. Miller 
1206db8dac20SDavid S. Miller do_append_data:
1207db8dac20SDavid S. Miller 	up->len += ulen;
1208f69e6d13SAl Viro 	err = ip_append_data(sk, fl4, getfrag, msg, ulen,
12092e77d89bSEric Dumazet 			     sizeof(struct udphdr), &ipc, &rt,
1210db8dac20SDavid S. Miller 			     corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
1211db8dac20SDavid S. Miller 	if (err)
1212db8dac20SDavid S. Miller 		udp_flush_pending_frames(sk);
1213db8dac20SDavid S. Miller 	else if (!corkreq)
1214db8dac20SDavid S. Miller 		err = udp_push_pending_frames(sk);
1215db8dac20SDavid S. Miller 	else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
1216db8dac20SDavid S. Miller 		up->pending = 0;
1217db8dac20SDavid S. Miller 	release_sock(sk);
1218db8dac20SDavid S. Miller 
1219db8dac20SDavid S. Miller out:
1220db8dac20SDavid S. Miller 	ip_rt_put(rt);
12211b97013bSAndrey Ignatov out_free:
1222db8dac20SDavid S. Miller 	if (free)
1223db8dac20SDavid S. Miller 		kfree(ipc.opt);
1224db8dac20SDavid S. Miller 	if (!err)
1225db8dac20SDavid S. Miller 		return len;
1226db8dac20SDavid S. Miller 	/*
1227db8dac20SDavid S. Miller 	 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space.  Reporting
1228db8dac20SDavid S. Miller 	 * ENOBUFS might not be good (it's not tunable per se), but otherwise
1229db8dac20SDavid S. Miller 	 * we don't have a good statistic (IpOutDiscards but it can be too many
1230db8dac20SDavid S. Miller 	 * things).  We could add another new stat but at least for now that
1231db8dac20SDavid S. Miller 	 * seems like overkill.
1232db8dac20SDavid S. Miller 	 */
1233db8dac20SDavid S. Miller 	if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
12346aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
1235629ca23cSPavel Emelyanov 			      UDP_MIB_SNDBUFERRORS, is_udplite);
1236db8dac20SDavid S. Miller 	}
1237db8dac20SDavid S. Miller 	return err;
1238db8dac20SDavid S. Miller 
1239db8dac20SDavid S. Miller do_confirm:
12400dec879fSJulian Anastasov 	if (msg->msg_flags & MSG_PROBE)
12410dec879fSJulian Anastasov 		dst_confirm_neigh(&rt->dst, &fl4->daddr);
1242db8dac20SDavid S. Miller 	if (!(msg->msg_flags&MSG_PROBE) || len)
1243db8dac20SDavid S. Miller 		goto back_from_confirm;
1244db8dac20SDavid S. Miller 	err = 0;
1245db8dac20SDavid S. Miller 	goto out;
1246db8dac20SDavid S. Miller }
1247c482c568SEric Dumazet EXPORT_SYMBOL(udp_sendmsg);
1248db8dac20SDavid S. Miller 
1249db8dac20SDavid S. Miller int udp_sendpage(struct sock *sk, struct page *page, int offset,
1250db8dac20SDavid S. Miller 		 size_t size, int flags)
1251db8dac20SDavid S. Miller {
1252f5fca608SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1253db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
1254db8dac20SDavid S. Miller 	int ret;
1255db8dac20SDavid S. Miller 
1256d3f7d56aSShawn Landden 	if (flags & MSG_SENDPAGE_NOTLAST)
1257d3f7d56aSShawn Landden 		flags |= MSG_MORE;
1258d3f7d56aSShawn Landden 
1259db8dac20SDavid S. Miller 	if (!up->pending) {
1260db8dac20SDavid S. Miller 		struct msghdr msg = {	.msg_flags = flags|MSG_MORE };
1261db8dac20SDavid S. Miller 
1262db8dac20SDavid S. Miller 		/* Call udp_sendmsg to specify destination address which
1263db8dac20SDavid S. Miller 		 * sendpage interface can't pass.
1264db8dac20SDavid S. Miller 		 * This will succeed only when the socket is connected.
1265db8dac20SDavid S. Miller 		 */
12661b784140SYing Xue 		ret = udp_sendmsg(sk, &msg, 0);
1267db8dac20SDavid S. Miller 		if (ret < 0)
1268db8dac20SDavid S. Miller 			return ret;
1269db8dac20SDavid S. Miller 	}
1270db8dac20SDavid S. Miller 
1271db8dac20SDavid S. Miller 	lock_sock(sk);
1272db8dac20SDavid S. Miller 
1273db8dac20SDavid S. Miller 	if (unlikely(!up->pending)) {
1274db8dac20SDavid S. Miller 		release_sock(sk);
1275db8dac20SDavid S. Miller 
1276197df02cSMatteo Croce 		net_dbg_ratelimited("cork failed\n");
1277db8dac20SDavid S. Miller 		return -EINVAL;
1278db8dac20SDavid S. Miller 	}
1279db8dac20SDavid S. Miller 
1280f5fca608SDavid S. Miller 	ret = ip_append_page(sk, &inet->cork.fl.u.ip4,
1281f5fca608SDavid S. Miller 			     page, offset, size, flags);
1282db8dac20SDavid S. Miller 	if (ret == -EOPNOTSUPP) {
1283db8dac20SDavid S. Miller 		release_sock(sk);
1284db8dac20SDavid S. Miller 		return sock_no_sendpage(sk->sk_socket, page, offset,
1285db8dac20SDavid S. Miller 					size, flags);
1286db8dac20SDavid S. Miller 	}
1287db8dac20SDavid S. Miller 	if (ret < 0) {
1288db8dac20SDavid S. Miller 		udp_flush_pending_frames(sk);
1289db8dac20SDavid S. Miller 		goto out;
1290db8dac20SDavid S. Miller 	}
1291db8dac20SDavid S. Miller 
1292db8dac20SDavid S. Miller 	up->len += size;
1293db8dac20SDavid S. Miller 	if (!(up->corkflag || (flags&MSG_MORE)))
1294db8dac20SDavid S. Miller 		ret = udp_push_pending_frames(sk);
1295db8dac20SDavid S. Miller 	if (!ret)
1296db8dac20SDavid S. Miller 		ret = size;
1297db8dac20SDavid S. Miller out:
1298db8dac20SDavid S. Miller 	release_sock(sk);
1299db8dac20SDavid S. Miller 	return ret;
1300db8dac20SDavid S. Miller }
1301db8dac20SDavid S. Miller 
1302dce4551cSPaolo Abeni #define UDP_SKB_IS_STATELESS 0x80000000
1303dce4551cSPaolo Abeni 
1304b65ac446SPaolo Abeni static void udp_set_dev_scratch(struct sk_buff *skb)
1305b65ac446SPaolo Abeni {
1306dce4551cSPaolo Abeni 	struct udp_dev_scratch *scratch = udp_skb_scratch(skb);
1307b65ac446SPaolo Abeni 
1308b65ac446SPaolo Abeni 	BUILD_BUG_ON(sizeof(struct udp_dev_scratch) > sizeof(long));
1309dce4551cSPaolo Abeni 	scratch->_tsize_state = skb->truesize;
1310dce4551cSPaolo Abeni #if BITS_PER_LONG == 64
1311b65ac446SPaolo Abeni 	scratch->len = skb->len;
1312b65ac446SPaolo Abeni 	scratch->csum_unnecessary = !!skb_csum_unnecessary(skb);
1313b65ac446SPaolo Abeni 	scratch->is_linear = !skb_is_nonlinear(skb);
1314b65ac446SPaolo Abeni #endif
13153bdefdf9SPaolo Abeni 	/* all head states execept sp (dst, sk, nf) are always cleared by
13163bdefdf9SPaolo Abeni 	 * udp_rcv() and we need to preserve secpath, if present, to eventually
13173bdefdf9SPaolo Abeni 	 * process IP_CMSG_PASSSEC at recvmsg() time
13183bdefdf9SPaolo Abeni 	 */
13193bdefdf9SPaolo Abeni 	if (likely(!skb_sec_path(skb)))
1320dce4551cSPaolo Abeni 		scratch->_tsize_state |= UDP_SKB_IS_STATELESS;
1321dce4551cSPaolo Abeni }
1322dce4551cSPaolo Abeni 
1323dce4551cSPaolo Abeni static int udp_skb_truesize(struct sk_buff *skb)
1324dce4551cSPaolo Abeni {
1325dce4551cSPaolo Abeni 	return udp_skb_scratch(skb)->_tsize_state & ~UDP_SKB_IS_STATELESS;
1326dce4551cSPaolo Abeni }
1327dce4551cSPaolo Abeni 
1328dce4551cSPaolo Abeni static bool udp_skb_has_head_state(struct sk_buff *skb)
1329dce4551cSPaolo Abeni {
1330dce4551cSPaolo Abeni 	return !(udp_skb_scratch(skb)->_tsize_state & UDP_SKB_IS_STATELESS);
1331dce4551cSPaolo Abeni }
1332b65ac446SPaolo Abeni 
13337c13f97fSPaolo Abeni /* fully reclaim rmem/fwd memory allocated for skb */
13346dfb4367SPaolo Abeni static void udp_rmem_release(struct sock *sk, int size, int partial,
13356dfb4367SPaolo Abeni 			     bool rx_queue_lock_held)
1336f970bd9eSPaolo Abeni {
13376b229cf7SEric Dumazet 	struct udp_sock *up = udp_sk(sk);
13382276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue;
1339f970bd9eSPaolo Abeni 	int amt;
1340f970bd9eSPaolo Abeni 
13416b229cf7SEric Dumazet 	if (likely(partial)) {
13426b229cf7SEric Dumazet 		up->forward_deficit += size;
13436b229cf7SEric Dumazet 		size = up->forward_deficit;
13440d4a6608SPaolo Abeni 		if (size < (sk->sk_rcvbuf >> 2))
13456b229cf7SEric Dumazet 			return;
13466b229cf7SEric Dumazet 	} else {
13476b229cf7SEric Dumazet 		size += up->forward_deficit;
13486b229cf7SEric Dumazet 	}
13496b229cf7SEric Dumazet 	up->forward_deficit = 0;
13506b229cf7SEric Dumazet 
13516dfb4367SPaolo Abeni 	/* acquire the sk_receive_queue for fwd allocated memory scheduling,
13526dfb4367SPaolo Abeni 	 * if the called don't held it already
13536dfb4367SPaolo Abeni 	 */
13542276f58aSPaolo Abeni 	sk_queue = &sk->sk_receive_queue;
13556dfb4367SPaolo Abeni 	if (!rx_queue_lock_held)
13562276f58aSPaolo Abeni 		spin_lock(&sk_queue->lock);
13572276f58aSPaolo Abeni 
13586dfb4367SPaolo Abeni 
1359f970bd9eSPaolo Abeni 	sk->sk_forward_alloc += size;
1360f970bd9eSPaolo Abeni 	amt = (sk->sk_forward_alloc - partial) & ~(SK_MEM_QUANTUM - 1);
1361f970bd9eSPaolo Abeni 	sk->sk_forward_alloc -= amt;
1362f970bd9eSPaolo Abeni 
1363f970bd9eSPaolo Abeni 	if (amt)
1364f970bd9eSPaolo Abeni 		__sk_mem_reduce_allocated(sk, amt >> SK_MEM_QUANTUM_SHIFT);
136502ab0d13SEric Dumazet 
136602ab0d13SEric Dumazet 	atomic_sub(size, &sk->sk_rmem_alloc);
13672276f58aSPaolo Abeni 
13682276f58aSPaolo Abeni 	/* this can save us from acquiring the rx queue lock on next receive */
13692276f58aSPaolo Abeni 	skb_queue_splice_tail_init(sk_queue, &up->reader_queue);
13702276f58aSPaolo Abeni 
13716dfb4367SPaolo Abeni 	if (!rx_queue_lock_held)
13722276f58aSPaolo Abeni 		spin_unlock(&sk_queue->lock);
1373f970bd9eSPaolo Abeni }
1374f970bd9eSPaolo Abeni 
13752276f58aSPaolo Abeni /* Note: called with reader_queue.lock held.
1376c84d9490SEric Dumazet  * Instead of using skb->truesize here, find a copy of it in skb->dev_scratch
1377c84d9490SEric Dumazet  * This avoids a cache line miss while receive_queue lock is held.
1378c84d9490SEric Dumazet  * Look at __udp_enqueue_schedule_skb() to find where this copy is done.
1379c84d9490SEric Dumazet  */
13807c13f97fSPaolo Abeni void udp_skb_destructor(struct sock *sk, struct sk_buff *skb)
1381f970bd9eSPaolo Abeni {
1382b65ac446SPaolo Abeni 	prefetch(&skb->data);
1383b65ac446SPaolo Abeni 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, false);
1384f970bd9eSPaolo Abeni }
13857c13f97fSPaolo Abeni EXPORT_SYMBOL(udp_skb_destructor);
1386f970bd9eSPaolo Abeni 
13876dfb4367SPaolo Abeni /* as above, but the caller held the rx queue lock, too */
138864f5102dSColin Ian King static void udp_skb_dtor_locked(struct sock *sk, struct sk_buff *skb)
13896dfb4367SPaolo Abeni {
1390b65ac446SPaolo Abeni 	prefetch(&skb->data);
1391b65ac446SPaolo Abeni 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, true);
13926dfb4367SPaolo Abeni }
13936dfb4367SPaolo Abeni 
13944b272750SEric Dumazet /* Idea of busylocks is to let producers grab an extra spinlock
13954b272750SEric Dumazet  * to relieve pressure on the receive_queue spinlock shared by consumer.
13964b272750SEric Dumazet  * Under flood, this means that only one producer can be in line
13974b272750SEric Dumazet  * trying to acquire the receive_queue spinlock.
13984b272750SEric Dumazet  * These busylock can be allocated on a per cpu manner, instead of a
13994b272750SEric Dumazet  * per socket one (that would consume a cache line per socket)
14004b272750SEric Dumazet  */
14014b272750SEric Dumazet static int udp_busylocks_log __read_mostly;
14024b272750SEric Dumazet static spinlock_t *udp_busylocks __read_mostly;
14034b272750SEric Dumazet 
14044b272750SEric Dumazet static spinlock_t *busylock_acquire(void *ptr)
14054b272750SEric Dumazet {
14064b272750SEric Dumazet 	spinlock_t *busy;
14074b272750SEric Dumazet 
14084b272750SEric Dumazet 	busy = udp_busylocks + hash_ptr(ptr, udp_busylocks_log);
14094b272750SEric Dumazet 	spin_lock(busy);
14104b272750SEric Dumazet 	return busy;
14114b272750SEric Dumazet }
14124b272750SEric Dumazet 
14134b272750SEric Dumazet static void busylock_release(spinlock_t *busy)
14144b272750SEric Dumazet {
14154b272750SEric Dumazet 	if (busy)
14164b272750SEric Dumazet 		spin_unlock(busy);
14174b272750SEric Dumazet }
14184b272750SEric Dumazet 
1419f970bd9eSPaolo Abeni int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb)
1420f970bd9eSPaolo Abeni {
1421f970bd9eSPaolo Abeni 	struct sk_buff_head *list = &sk->sk_receive_queue;
1422f970bd9eSPaolo Abeni 	int rmem, delta, amt, err = -ENOMEM;
14234b272750SEric Dumazet 	spinlock_t *busy = NULL;
1424c8c8b127SEric Dumazet 	int size;
1425f970bd9eSPaolo Abeni 
1426f970bd9eSPaolo Abeni 	/* try to avoid the costly atomic add/sub pair when the receive
1427f970bd9eSPaolo Abeni 	 * queue is full; always allow at least a packet
1428f970bd9eSPaolo Abeni 	 */
1429f970bd9eSPaolo Abeni 	rmem = atomic_read(&sk->sk_rmem_alloc);
1430363dc73aSPaolo Abeni 	if (rmem > sk->sk_rcvbuf)
1431f970bd9eSPaolo Abeni 		goto drop;
1432f970bd9eSPaolo Abeni 
1433c8c8b127SEric Dumazet 	/* Under mem pressure, it might be helpful to help udp_recvmsg()
1434c8c8b127SEric Dumazet 	 * having linear skbs :
1435c8c8b127SEric Dumazet 	 * - Reduce memory overhead and thus increase receive queue capacity
1436c8c8b127SEric Dumazet 	 * - Less cache line misses at copyout() time
1437c8c8b127SEric Dumazet 	 * - Less work at consume_skb() (less alien page frag freeing)
1438c8c8b127SEric Dumazet 	 */
14394b272750SEric Dumazet 	if (rmem > (sk->sk_rcvbuf >> 1)) {
1440c8c8b127SEric Dumazet 		skb_condense(skb);
14414b272750SEric Dumazet 
14424b272750SEric Dumazet 		busy = busylock_acquire(sk);
14434b272750SEric Dumazet 	}
1444c8c8b127SEric Dumazet 	size = skb->truesize;
1445b65ac446SPaolo Abeni 	udp_set_dev_scratch(skb);
1446c8c8b127SEric Dumazet 
1447f970bd9eSPaolo Abeni 	/* we drop only if the receive buf is full and the receive
1448f970bd9eSPaolo Abeni 	 * queue contains some other skb
1449f970bd9eSPaolo Abeni 	 */
1450f970bd9eSPaolo Abeni 	rmem = atomic_add_return(size, &sk->sk_rmem_alloc);
1451363dc73aSPaolo Abeni 	if (rmem > (size + sk->sk_rcvbuf))
1452f970bd9eSPaolo Abeni 		goto uncharge_drop;
1453f970bd9eSPaolo Abeni 
1454f970bd9eSPaolo Abeni 	spin_lock(&list->lock);
1455f970bd9eSPaolo Abeni 	if (size >= sk->sk_forward_alloc) {
1456f970bd9eSPaolo Abeni 		amt = sk_mem_pages(size);
1457f970bd9eSPaolo Abeni 		delta = amt << SK_MEM_QUANTUM_SHIFT;
1458f970bd9eSPaolo Abeni 		if (!__sk_mem_raise_allocated(sk, delta, amt, SK_MEM_RECV)) {
1459f970bd9eSPaolo Abeni 			err = -ENOBUFS;
1460f970bd9eSPaolo Abeni 			spin_unlock(&list->lock);
1461f970bd9eSPaolo Abeni 			goto uncharge_drop;
1462f970bd9eSPaolo Abeni 		}
1463f970bd9eSPaolo Abeni 
1464f970bd9eSPaolo Abeni 		sk->sk_forward_alloc += delta;
1465f970bd9eSPaolo Abeni 	}
1466f970bd9eSPaolo Abeni 
1467f970bd9eSPaolo Abeni 	sk->sk_forward_alloc -= size;
1468f970bd9eSPaolo Abeni 
14697c13f97fSPaolo Abeni 	/* no need to setup a destructor, we will explicitly release the
14707c13f97fSPaolo Abeni 	 * forward allocated memory on dequeue
14717c13f97fSPaolo Abeni 	 */
1472f970bd9eSPaolo Abeni 	sock_skb_set_dropcount(sk, skb);
1473f970bd9eSPaolo Abeni 
1474f970bd9eSPaolo Abeni 	__skb_queue_tail(list, skb);
1475f970bd9eSPaolo Abeni 	spin_unlock(&list->lock);
1476f970bd9eSPaolo Abeni 
1477f970bd9eSPaolo Abeni 	if (!sock_flag(sk, SOCK_DEAD))
1478f970bd9eSPaolo Abeni 		sk->sk_data_ready(sk);
1479f970bd9eSPaolo Abeni 
14804b272750SEric Dumazet 	busylock_release(busy);
1481f970bd9eSPaolo Abeni 	return 0;
1482f970bd9eSPaolo Abeni 
1483f970bd9eSPaolo Abeni uncharge_drop:
1484f970bd9eSPaolo Abeni 	atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
1485f970bd9eSPaolo Abeni 
1486f970bd9eSPaolo Abeni drop:
1487f970bd9eSPaolo Abeni 	atomic_inc(&sk->sk_drops);
14884b272750SEric Dumazet 	busylock_release(busy);
1489f970bd9eSPaolo Abeni 	return err;
1490f970bd9eSPaolo Abeni }
1491f970bd9eSPaolo Abeni EXPORT_SYMBOL_GPL(__udp_enqueue_schedule_skb);
1492f970bd9eSPaolo Abeni 
1493c915fe13SPaolo Abeni void udp_destruct_sock(struct sock *sk)
1494f970bd9eSPaolo Abeni {
1495f970bd9eSPaolo Abeni 	/* reclaim completely the forward allocated memory */
14962276f58aSPaolo Abeni 	struct udp_sock *up = udp_sk(sk);
14977c13f97fSPaolo Abeni 	unsigned int total = 0;
14987c13f97fSPaolo Abeni 	struct sk_buff *skb;
14997c13f97fSPaolo Abeni 
15002276f58aSPaolo Abeni 	skb_queue_splice_tail_init(&sk->sk_receive_queue, &up->reader_queue);
15012276f58aSPaolo Abeni 	while ((skb = __skb_dequeue(&up->reader_queue)) != NULL) {
15027c13f97fSPaolo Abeni 		total += skb->truesize;
15037c13f97fSPaolo Abeni 		kfree_skb(skb);
15047c13f97fSPaolo Abeni 	}
15056dfb4367SPaolo Abeni 	udp_rmem_release(sk, total, 0, true);
15067c13f97fSPaolo Abeni 
1507f970bd9eSPaolo Abeni 	inet_sock_destruct(sk);
1508f970bd9eSPaolo Abeni }
1509c915fe13SPaolo Abeni EXPORT_SYMBOL_GPL(udp_destruct_sock);
1510f970bd9eSPaolo Abeni 
1511f970bd9eSPaolo Abeni int udp_init_sock(struct sock *sk)
1512f970bd9eSPaolo Abeni {
15132276f58aSPaolo Abeni 	skb_queue_head_init(&udp_sk(sk)->reader_queue);
1514f970bd9eSPaolo Abeni 	sk->sk_destruct = udp_destruct_sock;
1515f970bd9eSPaolo Abeni 	return 0;
1516f970bd9eSPaolo Abeni }
1517f970bd9eSPaolo Abeni EXPORT_SYMBOL_GPL(udp_init_sock);
1518f970bd9eSPaolo Abeni 
1519f970bd9eSPaolo Abeni void skb_consume_udp(struct sock *sk, struct sk_buff *skb, int len)
1520f970bd9eSPaolo Abeni {
1521f970bd9eSPaolo Abeni 	if (unlikely(READ_ONCE(sk->sk_peek_off) >= 0)) {
1522f970bd9eSPaolo Abeni 		bool slow = lock_sock_fast(sk);
1523f970bd9eSPaolo Abeni 
1524f970bd9eSPaolo Abeni 		sk_peek_offset_bwd(sk, len);
1525f970bd9eSPaolo Abeni 		unlock_sock_fast(sk, slow);
1526f970bd9eSPaolo Abeni 	}
15270a463c78SPaolo Abeni 
1528ca2c1418SPaolo Abeni 	if (!skb_unref(skb))
1529ca2c1418SPaolo Abeni 		return;
1530ca2c1418SPaolo Abeni 
1531dce4551cSPaolo Abeni 	/* In the more common cases we cleared the head states previously,
1532dce4551cSPaolo Abeni 	 * see __udp_queue_rcv_skb().
15330ddf3fb2SPaolo Abeni 	 */
1534dce4551cSPaolo Abeni 	if (unlikely(udp_skb_has_head_state(skb)))
15350ddf3fb2SPaolo Abeni 		skb_release_head_state(skb);
1536ca2c1418SPaolo Abeni 	__consume_stateless_skb(skb);
1537f970bd9eSPaolo Abeni }
1538f970bd9eSPaolo Abeni EXPORT_SYMBOL_GPL(skb_consume_udp);
1539f970bd9eSPaolo Abeni 
15402276f58aSPaolo Abeni static struct sk_buff *__first_packet_length(struct sock *sk,
15412276f58aSPaolo Abeni 					     struct sk_buff_head *rcvq,
15422276f58aSPaolo Abeni 					     int *total)
15432276f58aSPaolo Abeni {
15442276f58aSPaolo Abeni 	struct sk_buff *skb;
15452276f58aSPaolo Abeni 
15469bd780f5SPaolo Abeni 	while ((skb = skb_peek(rcvq)) != NULL) {
15479bd780f5SPaolo Abeni 		if (udp_lib_checksum_complete(skb)) {
15482276f58aSPaolo Abeni 			__UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS,
15492276f58aSPaolo Abeni 					IS_UDPLITE(sk));
15502276f58aSPaolo Abeni 			__UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS,
15512276f58aSPaolo Abeni 					IS_UDPLITE(sk));
15522276f58aSPaolo Abeni 			atomic_inc(&sk->sk_drops);
15532276f58aSPaolo Abeni 			__skb_unlink(skb, rcvq);
15542276f58aSPaolo Abeni 			*total += skb->truesize;
15552276f58aSPaolo Abeni 			kfree_skb(skb);
15569bd780f5SPaolo Abeni 		} else {
15579bd780f5SPaolo Abeni 			/* the csum related bits could be changed, refresh
15589bd780f5SPaolo Abeni 			 * the scratch area
15599bd780f5SPaolo Abeni 			 */
15609bd780f5SPaolo Abeni 			udp_set_dev_scratch(skb);
15619bd780f5SPaolo Abeni 			break;
15629bd780f5SPaolo Abeni 		}
15632276f58aSPaolo Abeni 	}
15642276f58aSPaolo Abeni 	return skb;
15652276f58aSPaolo Abeni }
15662276f58aSPaolo Abeni 
156785584672SEric Dumazet /**
156885584672SEric Dumazet  *	first_packet_length	- return length of first packet in receive queue
156985584672SEric Dumazet  *	@sk: socket
157085584672SEric Dumazet  *
157185584672SEric Dumazet  *	Drops all bad checksum frames, until a valid one is found.
1572e83c6744SEric Dumazet  *	Returns the length of found skb, or -1 if none is found.
157385584672SEric Dumazet  */
1574e83c6744SEric Dumazet static int first_packet_length(struct sock *sk)
157585584672SEric Dumazet {
15762276f58aSPaolo Abeni 	struct sk_buff_head *rcvq = &udp_sk(sk)->reader_queue;
15772276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
157885584672SEric Dumazet 	struct sk_buff *skb;
15797c13f97fSPaolo Abeni 	int total = 0;
1580e83c6744SEric Dumazet 	int res;
158185584672SEric Dumazet 
158285584672SEric Dumazet 	spin_lock_bh(&rcvq->lock);
15832276f58aSPaolo Abeni 	skb = __first_packet_length(sk, rcvq, &total);
15842276f58aSPaolo Abeni 	if (!skb && !skb_queue_empty(sk_queue)) {
15852276f58aSPaolo Abeni 		spin_lock(&sk_queue->lock);
15862276f58aSPaolo Abeni 		skb_queue_splice_tail_init(sk_queue, rcvq);
15872276f58aSPaolo Abeni 		spin_unlock(&sk_queue->lock);
15882276f58aSPaolo Abeni 
15892276f58aSPaolo Abeni 		skb = __first_packet_length(sk, rcvq, &total);
159085584672SEric Dumazet 	}
1591e83c6744SEric Dumazet 	res = skb ? skb->len : -1;
15927c13f97fSPaolo Abeni 	if (total)
15936dfb4367SPaolo Abeni 		udp_rmem_release(sk, total, 1, false);
159485584672SEric Dumazet 	spin_unlock_bh(&rcvq->lock);
159585584672SEric Dumazet 	return res;
159685584672SEric Dumazet }
159785584672SEric Dumazet 
15981da177e4SLinus Torvalds /*
15991da177e4SLinus Torvalds  *	IOCTL requests applicable to the UDP protocol
16001da177e4SLinus Torvalds  */
16011da177e4SLinus Torvalds 
16021da177e4SLinus Torvalds int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
16031da177e4SLinus Torvalds {
16046516c655SStephen Hemminger 	switch (cmd) {
16051da177e4SLinus Torvalds 	case SIOCOUTQ:
16061da177e4SLinus Torvalds 	{
160731e6d363SEric Dumazet 		int amount = sk_wmem_alloc_get(sk);
160831e6d363SEric Dumazet 
16091da177e4SLinus Torvalds 		return put_user(amount, (int __user *)arg);
16101da177e4SLinus Torvalds 	}
16111da177e4SLinus Torvalds 
16121da177e4SLinus Torvalds 	case SIOCINQ:
16131da177e4SLinus Torvalds 	{
1614e83c6744SEric Dumazet 		int amount = max_t(int, 0, first_packet_length(sk));
16151da177e4SLinus Torvalds 
16161da177e4SLinus Torvalds 		return put_user(amount, (int __user *)arg);
16171da177e4SLinus Torvalds 	}
16181da177e4SLinus Torvalds 
16191da177e4SLinus Torvalds 	default:
16201da177e4SLinus Torvalds 		return -ENOIOCTLCMD;
16211da177e4SLinus Torvalds 	}
16226516c655SStephen Hemminger 
16236516c655SStephen Hemminger 	return 0;
16241da177e4SLinus Torvalds }
1625c482c568SEric Dumazet EXPORT_SYMBOL(udp_ioctl);
16261da177e4SLinus Torvalds 
16272276f58aSPaolo Abeni struct sk_buff *__skb_recv_udp(struct sock *sk, unsigned int flags,
1628fd69c399SPaolo Abeni 			       int noblock, int *off, int *err)
16292276f58aSPaolo Abeni {
16302276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
16312276f58aSPaolo Abeni 	struct sk_buff_head *queue;
16322276f58aSPaolo Abeni 	struct sk_buff *last;
16332276f58aSPaolo Abeni 	long timeo;
16342276f58aSPaolo Abeni 	int error;
16352276f58aSPaolo Abeni 
16362276f58aSPaolo Abeni 	queue = &udp_sk(sk)->reader_queue;
16372276f58aSPaolo Abeni 	flags |= noblock ? MSG_DONTWAIT : 0;
16382276f58aSPaolo Abeni 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
16392276f58aSPaolo Abeni 	do {
16402276f58aSPaolo Abeni 		struct sk_buff *skb;
16412276f58aSPaolo Abeni 
16422276f58aSPaolo Abeni 		error = sock_error(sk);
16432276f58aSPaolo Abeni 		if (error)
16442276f58aSPaolo Abeni 			break;
16452276f58aSPaolo Abeni 
16462276f58aSPaolo Abeni 		error = -EAGAIN;
16472276f58aSPaolo Abeni 		do {
16482276f58aSPaolo Abeni 			spin_lock_bh(&queue->lock);
16492276f58aSPaolo Abeni 			skb = __skb_try_recv_from_queue(sk, queue, flags,
16502276f58aSPaolo Abeni 							udp_skb_destructor,
1651fd69c399SPaolo Abeni 							off, err, &last);
16522276f58aSPaolo Abeni 			if (skb) {
16532276f58aSPaolo Abeni 				spin_unlock_bh(&queue->lock);
16542276f58aSPaolo Abeni 				return skb;
16552276f58aSPaolo Abeni 			}
16562276f58aSPaolo Abeni 
16572276f58aSPaolo Abeni 			if (skb_queue_empty(sk_queue)) {
16582276f58aSPaolo Abeni 				spin_unlock_bh(&queue->lock);
16592276f58aSPaolo Abeni 				goto busy_check;
16602276f58aSPaolo Abeni 			}
16612276f58aSPaolo Abeni 
16626dfb4367SPaolo Abeni 			/* refill the reader queue and walk it again
16636dfb4367SPaolo Abeni 			 * keep both queues locked to avoid re-acquiring
16646dfb4367SPaolo Abeni 			 * the sk_receive_queue lock if fwd memory scheduling
16656dfb4367SPaolo Abeni 			 * is needed.
16666dfb4367SPaolo Abeni 			 */
16672276f58aSPaolo Abeni 			spin_lock(&sk_queue->lock);
16682276f58aSPaolo Abeni 			skb_queue_splice_tail_init(sk_queue, queue);
16692276f58aSPaolo Abeni 
16702276f58aSPaolo Abeni 			skb = __skb_try_recv_from_queue(sk, queue, flags,
16716dfb4367SPaolo Abeni 							udp_skb_dtor_locked,
1672fd69c399SPaolo Abeni 							off, err, &last);
16736dfb4367SPaolo Abeni 			spin_unlock(&sk_queue->lock);
16742276f58aSPaolo Abeni 			spin_unlock_bh(&queue->lock);
1675de321ed3SAndrey Vagin 			if (skb)
16762276f58aSPaolo Abeni 				return skb;
16772276f58aSPaolo Abeni 
16782276f58aSPaolo Abeni busy_check:
16792276f58aSPaolo Abeni 			if (!sk_can_busy_loop(sk))
16802276f58aSPaolo Abeni 				break;
16812276f58aSPaolo Abeni 
16822276f58aSPaolo Abeni 			sk_busy_loop(sk, flags & MSG_DONTWAIT);
16832276f58aSPaolo Abeni 		} while (!skb_queue_empty(sk_queue));
16842276f58aSPaolo Abeni 
16852276f58aSPaolo Abeni 		/* sk_queue is empty, reader_queue may contain peeked packets */
16862276f58aSPaolo Abeni 	} while (timeo &&
16872276f58aSPaolo Abeni 		 !__skb_wait_for_more_packets(sk, &error, &timeo,
16882276f58aSPaolo Abeni 					      (struct sk_buff *)sk_queue));
16892276f58aSPaolo Abeni 
16902276f58aSPaolo Abeni 	*err = error;
16912276f58aSPaolo Abeni 	return NULL;
16922276f58aSPaolo Abeni }
16937e823644SJiri Kosina EXPORT_SYMBOL(__skb_recv_udp);
16942276f58aSPaolo Abeni 
1695db8dac20SDavid S. Miller /*
1696db8dac20SDavid S. Miller  * 	This should be easy, if there is something there we
1697db8dac20SDavid S. Miller  * 	return it, otherwise we block.
1698db8dac20SDavid S. Miller  */
1699db8dac20SDavid S. Miller 
17001b784140SYing Xue int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock,
17011b784140SYing Xue 		int flags, int *addr_len)
1702db8dac20SDavid S. Miller {
1703db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1704342dfc30SSteffen Hurrle 	DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
1705db8dac20SDavid S. Miller 	struct sk_buff *skb;
170659c2cdaeSDavid S. Miller 	unsigned int ulen, copied;
1707fd69c399SPaolo Abeni 	int off, err, peeking = flags & MSG_PEEK;
1708db8dac20SDavid S. Miller 	int is_udplite = IS_UDPLITE(sk);
1709197c949eSEric Dumazet 	bool checksum_valid = false;
1710db8dac20SDavid S. Miller 
1711db8dac20SDavid S. Miller 	if (flags & MSG_ERRQUEUE)
171285fbaa75SHannes Frederic Sowa 		return ip_recv_error(sk, msg, len, addr_len);
1713db8dac20SDavid S. Miller 
1714db8dac20SDavid S. Miller try_again:
1715a0917e0bSMatthew Dawson 	off = sk_peek_offset(sk, flags);
1716fd69c399SPaolo Abeni 	skb = __skb_recv_udp(sk, flags, noblock, &off, &err);
1717db8dac20SDavid S. Miller 	if (!skb)
1718627d2d6bSsamanthakumar 		return err;
1719db8dac20SDavid S. Miller 
1720b65ac446SPaolo Abeni 	ulen = udp_skb_len(skb);
172159c2cdaeSDavid S. Miller 	copied = len;
1722627d2d6bSsamanthakumar 	if (copied > ulen - off)
1723627d2d6bSsamanthakumar 		copied = ulen - off;
172459c2cdaeSDavid S. Miller 	else if (copied < ulen)
1725db8dac20SDavid S. Miller 		msg->msg_flags |= MSG_TRUNC;
1726db8dac20SDavid S. Miller 
1727db8dac20SDavid S. Miller 	/*
1728db8dac20SDavid S. Miller 	 * If checksum is needed at all, try to do it while copying the
1729db8dac20SDavid S. Miller 	 * data.  If the data is truncated, or if we only want a partial
1730db8dac20SDavid S. Miller 	 * coverage checksum (UDP-Lite), do it before the copy.
1731db8dac20SDavid S. Miller 	 */
1732db8dac20SDavid S. Miller 
1733d21dbdfeSEric Dumazet 	if (copied < ulen || peeking ||
1734d21dbdfeSEric Dumazet 	    (is_udplite && UDP_SKB_CB(skb)->partial_cov)) {
1735b65ac446SPaolo Abeni 		checksum_valid = udp_skb_csum_unnecessary(skb) ||
1736b65ac446SPaolo Abeni 				!__udp_lib_checksum_complete(skb);
1737197c949eSEric Dumazet 		if (!checksum_valid)
1738db8dac20SDavid S. Miller 			goto csum_copy_err;
1739db8dac20SDavid S. Miller 	}
1740db8dac20SDavid S. Miller 
1741b65ac446SPaolo Abeni 	if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
1742b65ac446SPaolo Abeni 		if (udp_skb_is_linear(skb))
1743b65ac446SPaolo Abeni 			err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
1744b65ac446SPaolo Abeni 		else
1745627d2d6bSsamanthakumar 			err = skb_copy_datagram_msg(skb, off, msg, copied);
1746b65ac446SPaolo Abeni 	} else {
1747627d2d6bSsamanthakumar 		err = skb_copy_and_csum_datagram_msg(skb, off, msg);
1748db8dac20SDavid S. Miller 
1749db8dac20SDavid S. Miller 		if (err == -EINVAL)
1750db8dac20SDavid S. Miller 			goto csum_copy_err;
1751db8dac20SDavid S. Miller 	}
1752db8dac20SDavid S. Miller 
175322911fc5SEric Dumazet 	if (unlikely(err)) {
1754fd69c399SPaolo Abeni 		if (!peeking) {
1755979402b1SEric Dumazet 			atomic_inc(&sk->sk_drops);
17566aef70a8SEric Dumazet 			UDP_INC_STATS(sock_net(sk),
1757979402b1SEric Dumazet 				      UDP_MIB_INERRORS, is_udplite);
1758979402b1SEric Dumazet 		}
1759850cbaddSPaolo Abeni 		kfree_skb(skb);
1760627d2d6bSsamanthakumar 		return err;
176122911fc5SEric Dumazet 	}
1762db8dac20SDavid S. Miller 
1763fd69c399SPaolo Abeni 	if (!peeking)
17646aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
1765629ca23cSPavel Emelyanov 			      UDP_MIB_INDATAGRAMS, is_udplite);
1766db8dac20SDavid S. Miller 
17673b885787SNeil Horman 	sock_recv_ts_and_drops(msg, sk, skb);
1768db8dac20SDavid S. Miller 
1769db8dac20SDavid S. Miller 	/* Copy the address. */
1770c482c568SEric Dumazet 	if (sin) {
1771db8dac20SDavid S. Miller 		sin->sin_family = AF_INET;
1772db8dac20SDavid S. Miller 		sin->sin_port = udp_hdr(skb)->source;
1773db8dac20SDavid S. Miller 		sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
1774db8dac20SDavid S. Miller 		memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
1775bceaa902SHannes Frederic Sowa 		*addr_len = sizeof(*sin);
1776db8dac20SDavid S. Miller 	}
1777bcd1665eSPaolo Abeni 
1778bcd1665eSPaolo Abeni 	if (udp_sk(sk)->gro_enabled)
1779bcd1665eSPaolo Abeni 		udp_cmsg_recv(msg, sk, skb);
1780bcd1665eSPaolo Abeni 
1781db8dac20SDavid S. Miller 	if (inet->cmsg_flags)
1782ad959036SPaolo Abeni 		ip_cmsg_recv_offset(msg, sk, skb, sizeof(struct udphdr), off);
1783db8dac20SDavid S. Miller 
178459c2cdaeSDavid S. Miller 	err = copied;
1785db8dac20SDavid S. Miller 	if (flags & MSG_TRUNC)
1786db8dac20SDavid S. Miller 		err = ulen;
1787db8dac20SDavid S. Miller 
1788850cbaddSPaolo Abeni 	skb_consume_udp(sk, skb, peeking ? -err : err);
1789db8dac20SDavid S. Miller 	return err;
1790db8dac20SDavid S. Miller 
1791db8dac20SDavid S. Miller csum_copy_err:
17922276f58aSPaolo Abeni 	if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags,
17932276f58aSPaolo Abeni 				 udp_skb_destructor)) {
17946aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
17956aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
17966a5dc9e5SEric Dumazet 	}
1797850cbaddSPaolo Abeni 	kfree_skb(skb);
1798db8dac20SDavid S. Miller 
1799beb39db5SEric Dumazet 	/* starting over for a new packet, but check if we need to yield */
1800beb39db5SEric Dumazet 	cond_resched();
18019cfaa8deSXufeng Zhang 	msg->msg_flags &= ~MSG_TRUNC;
1802db8dac20SDavid S. Miller 	goto try_again;
1803db8dac20SDavid S. Miller }
1804db8dac20SDavid S. Miller 
1805d74bad4eSAndrey Ignatov int udp_pre_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
1806d74bad4eSAndrey Ignatov {
1807d74bad4eSAndrey Ignatov 	/* This check is replicated from __ip4_datagram_connect() and
1808d74bad4eSAndrey Ignatov 	 * intended to prevent BPF program called below from accessing bytes
1809d74bad4eSAndrey Ignatov 	 * that are out of the bound specified by user in addr_len.
1810d74bad4eSAndrey Ignatov 	 */
1811d74bad4eSAndrey Ignatov 	if (addr_len < sizeof(struct sockaddr_in))
1812d74bad4eSAndrey Ignatov 		return -EINVAL;
1813d74bad4eSAndrey Ignatov 
1814d74bad4eSAndrey Ignatov 	return BPF_CGROUP_RUN_PROG_INET4_CONNECT_LOCK(sk, uaddr);
1815d74bad4eSAndrey Ignatov }
1816d74bad4eSAndrey Ignatov EXPORT_SYMBOL(udp_pre_connect);
1817d74bad4eSAndrey Ignatov 
1818286c72deSEric Dumazet int __udp_disconnect(struct sock *sk, int flags)
18191da177e4SLinus Torvalds {
18201da177e4SLinus Torvalds 	struct inet_sock *inet = inet_sk(sk);
18211da177e4SLinus Torvalds 	/*
18221da177e4SLinus Torvalds 	 *	1003.1g - break association.
18231da177e4SLinus Torvalds 	 */
18241da177e4SLinus Torvalds 
18251da177e4SLinus Torvalds 	sk->sk_state = TCP_CLOSE;
1826c720c7e8SEric Dumazet 	inet->inet_daddr = 0;
1827c720c7e8SEric Dumazet 	inet->inet_dport = 0;
1828bdeab991STom Herbert 	sock_rps_reset_rxhash(sk);
18291da177e4SLinus Torvalds 	sk->sk_bound_dev_if = 0;
18301da177e4SLinus Torvalds 	if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
18311da177e4SLinus Torvalds 		inet_reset_saddr(sk);
18321da177e4SLinus Torvalds 
18331da177e4SLinus Torvalds 	if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
18341da177e4SLinus Torvalds 		sk->sk_prot->unhash(sk);
1835c720c7e8SEric Dumazet 		inet->inet_sport = 0;
18361da177e4SLinus Torvalds 	}
18371da177e4SLinus Torvalds 	sk_dst_reset(sk);
18381da177e4SLinus Torvalds 	return 0;
18391da177e4SLinus Torvalds }
1840286c72deSEric Dumazet EXPORT_SYMBOL(__udp_disconnect);
1841286c72deSEric Dumazet 
1842286c72deSEric Dumazet int udp_disconnect(struct sock *sk, int flags)
1843286c72deSEric Dumazet {
1844286c72deSEric Dumazet 	lock_sock(sk);
1845286c72deSEric Dumazet 	__udp_disconnect(sk, flags);
1846286c72deSEric Dumazet 	release_sock(sk);
1847286c72deSEric Dumazet 	return 0;
1848286c72deSEric Dumazet }
1849c482c568SEric Dumazet EXPORT_SYMBOL(udp_disconnect);
18501da177e4SLinus Torvalds 
1851645ca708SEric Dumazet void udp_lib_unhash(struct sock *sk)
1852645ca708SEric Dumazet {
1853723b4610SEric Dumazet 	if (sk_hashed(sk)) {
1854645ca708SEric Dumazet 		struct udp_table *udptable = sk->sk_prot->h.udp_table;
1855512615b6SEric Dumazet 		struct udp_hslot *hslot, *hslot2;
1856512615b6SEric Dumazet 
1857512615b6SEric Dumazet 		hslot  = udp_hashslot(udptable, sock_net(sk),
1858d4cada4aSEric Dumazet 				      udp_sk(sk)->udp_port_hash);
1859512615b6SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
1860645ca708SEric Dumazet 
1861c8db3fecSEric Dumazet 		spin_lock_bh(&hslot->lock);
1862e32ea7e7SCraig Gallek 		if (rcu_access_pointer(sk->sk_reuseport_cb))
1863e32ea7e7SCraig Gallek 			reuseport_detach_sock(sk);
1864ca065d0cSEric Dumazet 		if (sk_del_node_init_rcu(sk)) {
1865fdcc8aa9SEric Dumazet 			hslot->count--;
1866c720c7e8SEric Dumazet 			inet_sk(sk)->inet_num = 0;
1867645ca708SEric Dumazet 			sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
1868512615b6SEric Dumazet 
1869512615b6SEric Dumazet 			spin_lock(&hslot2->lock);
1870ca065d0cSEric Dumazet 			hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
1871512615b6SEric Dumazet 			hslot2->count--;
1872512615b6SEric Dumazet 			spin_unlock(&hslot2->lock);
1873645ca708SEric Dumazet 		}
1874c8db3fecSEric Dumazet 		spin_unlock_bh(&hslot->lock);
1875645ca708SEric Dumazet 	}
1876723b4610SEric Dumazet }
1877645ca708SEric Dumazet EXPORT_SYMBOL(udp_lib_unhash);
1878645ca708SEric Dumazet 
1879719f8358SEric Dumazet /*
1880719f8358SEric Dumazet  * inet_rcv_saddr was changed, we must rehash secondary hash
1881719f8358SEric Dumazet  */
1882719f8358SEric Dumazet void udp_lib_rehash(struct sock *sk, u16 newhash)
1883719f8358SEric Dumazet {
1884719f8358SEric Dumazet 	if (sk_hashed(sk)) {
1885719f8358SEric Dumazet 		struct udp_table *udptable = sk->sk_prot->h.udp_table;
1886719f8358SEric Dumazet 		struct udp_hslot *hslot, *hslot2, *nhslot2;
1887719f8358SEric Dumazet 
1888719f8358SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
1889719f8358SEric Dumazet 		nhslot2 = udp_hashslot2(udptable, newhash);
1890719f8358SEric Dumazet 		udp_sk(sk)->udp_portaddr_hash = newhash;
1891e32ea7e7SCraig Gallek 
1892e32ea7e7SCraig Gallek 		if (hslot2 != nhslot2 ||
1893e32ea7e7SCraig Gallek 		    rcu_access_pointer(sk->sk_reuseport_cb)) {
1894719f8358SEric Dumazet 			hslot = udp_hashslot(udptable, sock_net(sk),
1895719f8358SEric Dumazet 					     udp_sk(sk)->udp_port_hash);
1896719f8358SEric Dumazet 			/* we must lock primary chain too */
1897719f8358SEric Dumazet 			spin_lock_bh(&hslot->lock);
1898e32ea7e7SCraig Gallek 			if (rcu_access_pointer(sk->sk_reuseport_cb))
1899e32ea7e7SCraig Gallek 				reuseport_detach_sock(sk);
1900719f8358SEric Dumazet 
1901e32ea7e7SCraig Gallek 			if (hslot2 != nhslot2) {
1902719f8358SEric Dumazet 				spin_lock(&hslot2->lock);
1903ca065d0cSEric Dumazet 				hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
1904719f8358SEric Dumazet 				hslot2->count--;
1905719f8358SEric Dumazet 				spin_unlock(&hslot2->lock);
1906719f8358SEric Dumazet 
1907719f8358SEric Dumazet 				spin_lock(&nhslot2->lock);
1908ca065d0cSEric Dumazet 				hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
1909719f8358SEric Dumazet 							 &nhslot2->head);
1910719f8358SEric Dumazet 				nhslot2->count++;
1911719f8358SEric Dumazet 				spin_unlock(&nhslot2->lock);
1912e32ea7e7SCraig Gallek 			}
1913719f8358SEric Dumazet 
1914719f8358SEric Dumazet 			spin_unlock_bh(&hslot->lock);
1915719f8358SEric Dumazet 		}
1916719f8358SEric Dumazet 	}
1917719f8358SEric Dumazet }
1918719f8358SEric Dumazet EXPORT_SYMBOL(udp_lib_rehash);
1919719f8358SEric Dumazet 
19208f6b5392SAlexey Kodanev void udp_v4_rehash(struct sock *sk)
1921719f8358SEric Dumazet {
1922f0b1e64cSMartin KaFai Lau 	u16 new_hash = ipv4_portaddr_hash(sock_net(sk),
1923719f8358SEric Dumazet 					  inet_sk(sk)->inet_rcv_saddr,
1924719f8358SEric Dumazet 					  inet_sk(sk)->inet_num);
1925719f8358SEric Dumazet 	udp_lib_rehash(sk, new_hash);
1926719f8358SEric Dumazet }
1927719f8358SEric Dumazet 
1928a3f96c47SPaolo Abeni static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
192993821778SHerbert Xu {
1930fec5e652STom Herbert 	int rc;
193193821778SHerbert Xu 
1932005ec974SShawn Bohrer 	if (inet_sk(sk)->inet_daddr) {
1933bdeab991STom Herbert 		sock_rps_save_rxhash(sk, skb);
1934005ec974SShawn Bohrer 		sk_mark_napi_id(sk, skb);
19352c8c56e1SEric Dumazet 		sk_incoming_cpu_update(sk);
1936e68b6e50SEric Dumazet 	} else {
1937e68b6e50SEric Dumazet 		sk_mark_napi_id_once(sk, skb);
1938005ec974SShawn Bohrer 	}
1939fec5e652STom Herbert 
1940850cbaddSPaolo Abeni 	rc = __udp_enqueue_schedule_skb(sk, skb);
1941766e9037SEric Dumazet 	if (rc < 0) {
1942766e9037SEric Dumazet 		int is_udplite = IS_UDPLITE(sk);
1943766e9037SEric Dumazet 
194493821778SHerbert Xu 		/* Note that an ENOMEM error is charged twice */
1945766e9037SEric Dumazet 		if (rc == -ENOMEM)
1946e61da9e2SEric Dumazet 			UDP_INC_STATS(sock_net(sk), UDP_MIB_RCVBUFERRORS,
194793821778SHerbert Xu 					is_udplite);
1948e61da9e2SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
1949766e9037SEric Dumazet 		kfree_skb(skb);
1950296f7ea7SSatoru Moriya 		trace_udp_fail_queue_rcv_skb(rc, sk);
1951766e9037SEric Dumazet 		return -1;
195293821778SHerbert Xu 	}
195393821778SHerbert Xu 
195493821778SHerbert Xu 	return 0;
195593821778SHerbert Xu }
195693821778SHerbert Xu 
1957db8dac20SDavid S. Miller /* returns:
1958db8dac20SDavid S. Miller  *  -1: error
1959db8dac20SDavid S. Miller  *   0: success
1960db8dac20SDavid S. Miller  *  >0: "udp encap" protocol resubmission
1961db8dac20SDavid S. Miller  *
1962db8dac20SDavid S. Miller  * Note that in the success and error cases, the skb is assumed to
1963db8dac20SDavid S. Miller  * have either been requeued or freed.
1964db8dac20SDavid S. Miller  */
1965cf329aa4SPaolo Abeni static int udp_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
1966db8dac20SDavid S. Miller {
1967db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
1968db8dac20SDavid S. Miller 	int is_udplite = IS_UDPLITE(sk);
1969db8dac20SDavid S. Miller 
1970db8dac20SDavid S. Miller 	/*
1971db8dac20SDavid S. Miller 	 *	Charge it to the socket, dropping if the queue is full.
1972db8dac20SDavid S. Miller 	 */
1973db8dac20SDavid S. Miller 	if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
1974db8dac20SDavid S. Miller 		goto drop;
1975db8dac20SDavid S. Miller 	nf_reset(skb);
1976db8dac20SDavid S. Miller 
197788ab3108SDavidlohr Bueso 	if (static_branch_unlikely(&udp_encap_needed_key) && up->encap_type) {
19780ad92ad0SEric Dumazet 		int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
19790ad92ad0SEric Dumazet 
1980db8dac20SDavid S. Miller 		/*
1981db8dac20SDavid S. Miller 		 * This is an encapsulation socket so pass the skb to
1982db8dac20SDavid S. Miller 		 * the socket's udp_encap_rcv() hook. Otherwise, just
1983db8dac20SDavid S. Miller 		 * fall through and pass this up the UDP socket.
1984db8dac20SDavid S. Miller 		 * up->encap_rcv() returns the following value:
1985db8dac20SDavid S. Miller 		 * =0 if skb was successfully passed to the encap
1986db8dac20SDavid S. Miller 		 *    handler or was discarded by it.
1987db8dac20SDavid S. Miller 		 * >0 if skb should be passed on to UDP.
1988db8dac20SDavid S. Miller 		 * <0 if skb should be resubmitted as proto -N
1989db8dac20SDavid S. Miller 		 */
1990db8dac20SDavid S. Miller 
1991db8dac20SDavid S. Miller 		/* if we're overly short, let UDP handle it */
19926aa7de05SMark Rutland 		encap_rcv = READ_ONCE(up->encap_rcv);
1993e5aed006SHannes Frederic Sowa 		if (encap_rcv) {
1994db8dac20SDavid S. Miller 			int ret;
1995db8dac20SDavid S. Miller 
19960a80966bSTom Herbert 			/* Verify checksum before giving to encap */
19970a80966bSTom Herbert 			if (udp_lib_checksum_complete(skb))
19980a80966bSTom Herbert 				goto csum_error;
19990a80966bSTom Herbert 
20000ad92ad0SEric Dumazet 			ret = encap_rcv(sk, skb);
2001db8dac20SDavid S. Miller 			if (ret <= 0) {
200202c22347SEric Dumazet 				__UDP_INC_STATS(sock_net(sk),
20030283328eSPavel Emelyanov 						UDP_MIB_INDATAGRAMS,
2004db8dac20SDavid S. Miller 						is_udplite);
2005db8dac20SDavid S. Miller 				return -ret;
2006db8dac20SDavid S. Miller 			}
2007db8dac20SDavid S. Miller 		}
2008db8dac20SDavid S. Miller 
2009db8dac20SDavid S. Miller 		/* FALLTHROUGH -- it's a UDP Packet */
2010db8dac20SDavid S. Miller 	}
2011db8dac20SDavid S. Miller 
2012db8dac20SDavid S. Miller 	/*
2013db8dac20SDavid S. Miller 	 * 	UDP-Lite specific tests, ignored on UDP sockets
2014db8dac20SDavid S. Miller 	 */
2015db8dac20SDavid S. Miller 	if ((is_udplite & UDPLITE_RECV_CC)  &&  UDP_SKB_CB(skb)->partial_cov) {
2016db8dac20SDavid S. Miller 
2017db8dac20SDavid S. Miller 		/*
2018db8dac20SDavid S. Miller 		 * MIB statistics other than incrementing the error count are
2019db8dac20SDavid S. Miller 		 * disabled for the following two types of errors: these depend
2020db8dac20SDavid S. Miller 		 * on the application settings, not on the functioning of the
2021db8dac20SDavid S. Miller 		 * protocol stack as such.
2022db8dac20SDavid S. Miller 		 *
2023db8dac20SDavid S. Miller 		 * RFC 3828 here recommends (sec 3.3): "There should also be a
2024db8dac20SDavid S. Miller 		 * way ... to ... at least let the receiving application block
2025db8dac20SDavid S. Miller 		 * delivery of packets with coverage values less than a value
2026db8dac20SDavid S. Miller 		 * provided by the application."
2027db8dac20SDavid S. Miller 		 */
2028db8dac20SDavid S. Miller 		if (up->pcrlen == 0) {          /* full coverage was set  */
2029ba7a46f1SJoe Perches 			net_dbg_ratelimited("UDPLite: partial coverage %d while full coverage %d requested\n",
2030db8dac20SDavid S. Miller 					    UDP_SKB_CB(skb)->cscov, skb->len);
2031db8dac20SDavid S. Miller 			goto drop;
2032db8dac20SDavid S. Miller 		}
2033db8dac20SDavid S. Miller 		/* The next case involves violating the min. coverage requested
2034db8dac20SDavid S. Miller 		 * by the receiver. This is subtle: if receiver wants x and x is
2035db8dac20SDavid S. Miller 		 * greater than the buffersize/MTU then receiver will complain
2036db8dac20SDavid S. Miller 		 * that it wants x while sender emits packets of smaller size y.
2037db8dac20SDavid S. Miller 		 * Therefore the above ...()->partial_cov statement is essential.
2038db8dac20SDavid S. Miller 		 */
2039db8dac20SDavid S. Miller 		if (UDP_SKB_CB(skb)->cscov  <  up->pcrlen) {
2040ba7a46f1SJoe Perches 			net_dbg_ratelimited("UDPLite: coverage %d too small, need min %d\n",
2041db8dac20SDavid S. Miller 					    UDP_SKB_CB(skb)->cscov, up->pcrlen);
2042db8dac20SDavid S. Miller 			goto drop;
2043db8dac20SDavid S. Miller 		}
2044db8dac20SDavid S. Miller 	}
2045db8dac20SDavid S. Miller 
2046dd99e425SPaolo Abeni 	prefetch(&sk->sk_rmem_alloc);
2047ce25d66aSEric Dumazet 	if (rcu_access_pointer(sk->sk_filter) &&
2048ce25d66aSEric Dumazet 	    udp_lib_checksum_complete(skb))
20496a5dc9e5SEric Dumazet 			goto csum_error;
2050ce25d66aSEric Dumazet 
2051ba66bbe5SDaniel Borkmann 	if (sk_filter_trim_cap(sk, skb, sizeof(struct udphdr)))
2052a6127697SMichal Kubeček 		goto drop;
2053db8dac20SDavid S. Miller 
2054e6afc8acSsamanthakumar 	udp_csum_pull_header(skb);
2055db8dac20SDavid S. Miller 
2056fbf8866dSShawn Bohrer 	ipv4_pktinfo_prepare(sk, skb);
2057850cbaddSPaolo Abeni 	return __udp_queue_rcv_skb(sk, skb);
2058db8dac20SDavid S. Miller 
20596a5dc9e5SEric Dumazet csum_error:
206002c22347SEric Dumazet 	__UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
2061db8dac20SDavid S. Miller drop:
206202c22347SEric Dumazet 	__UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
20638edf19c2SEric Dumazet 	atomic_inc(&sk->sk_drops);
2064db8dac20SDavid S. Miller 	kfree_skb(skb);
2065db8dac20SDavid S. Miller 	return -1;
2066db8dac20SDavid S. Miller }
2067db8dac20SDavid S. Miller 
2068cf329aa4SPaolo Abeni static int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2069cf329aa4SPaolo Abeni {
2070cf329aa4SPaolo Abeni 	struct sk_buff *next, *segs;
2071cf329aa4SPaolo Abeni 	int ret;
2072cf329aa4SPaolo Abeni 
2073cf329aa4SPaolo Abeni 	if (likely(!udp_unexpected_gso(sk, skb)))
2074cf329aa4SPaolo Abeni 		return udp_queue_rcv_one_skb(sk, skb);
2075cf329aa4SPaolo Abeni 
2076cf329aa4SPaolo Abeni 	BUILD_BUG_ON(sizeof(struct udp_skb_cb) > SKB_SGO_CB_OFFSET);
2077cf329aa4SPaolo Abeni 	__skb_push(skb, -skb_mac_offset(skb));
2078cf329aa4SPaolo Abeni 	segs = udp_rcv_segment(sk, skb, true);
2079cf329aa4SPaolo Abeni 	for (skb = segs; skb; skb = next) {
2080cf329aa4SPaolo Abeni 		next = skb->next;
2081cf329aa4SPaolo Abeni 		__skb_pull(skb, skb_transport_offset(skb));
2082cf329aa4SPaolo Abeni 		ret = udp_queue_rcv_one_skb(sk, skb);
2083cf329aa4SPaolo Abeni 		if (ret > 0)
2084cf329aa4SPaolo Abeni 			ip_protocol_deliver_rcu(dev_net(skb->dev), skb, -ret);
2085cf329aa4SPaolo Abeni 	}
2086cf329aa4SPaolo Abeni 	return 0;
2087cf329aa4SPaolo Abeni }
2088cf329aa4SPaolo Abeni 
208997502231SEric Dumazet /* For TCP sockets, sk_rx_dst is protected by socket lock
2090e47eb5dfSEric Dumazet  * For UDP, we use xchg() to guard against concurrent changes.
209197502231SEric Dumazet  */
209264f0f5d1SPaolo Abeni bool udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
2093421b3885SShawn Bohrer {
209497502231SEric Dumazet 	struct dst_entry *old;
2095421b3885SShawn Bohrer 
2096d24406c8SWei Wang 	if (dst_hold_safe(dst)) {
2097e47eb5dfSEric Dumazet 		old = xchg(&sk->sk_rx_dst, dst);
209897502231SEric Dumazet 		dst_release(old);
209964f0f5d1SPaolo Abeni 		return old != dst;
210097502231SEric Dumazet 	}
210164f0f5d1SPaolo Abeni 	return false;
2102d24406c8SWei Wang }
2103c9f2c1aeSPaolo Abeni EXPORT_SYMBOL(udp_sk_rx_dst_set);
2104421b3885SShawn Bohrer 
2105db8dac20SDavid S. Miller /*
2106db8dac20SDavid S. Miller  *	Multicasts and broadcasts go to each listener.
2107db8dac20SDavid S. Miller  *
21081240d137SEric Dumazet  *	Note: called only from the BH handler context.
2109db8dac20SDavid S. Miller  */
2110e3163493SPavel Emelyanov static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
2111db8dac20SDavid S. Miller 				    struct udphdr  *uh,
2112db8dac20SDavid S. Miller 				    __be32 saddr, __be32 daddr,
211336cbb245SRick Jones 				    struct udp_table *udptable,
211436cbb245SRick Jones 				    int proto)
2115db8dac20SDavid S. Miller {
2116ca065d0cSEric Dumazet 	struct sock *sk, *first = NULL;
21175cf3d461SDavid Held 	unsigned short hnum = ntohs(uh->dest);
21185cf3d461SDavid Held 	struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum);
21192dc41cffSDavid Held 	unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10);
2120ca065d0cSEric Dumazet 	unsigned int offset = offsetof(typeof(*sk), sk_node);
2121ca065d0cSEric Dumazet 	int dif = skb->dev->ifindex;
2122fb74c277SDavid Ahern 	int sdif = inet_sdif(skb);
2123ca065d0cSEric Dumazet 	struct hlist_node *node;
2124ca065d0cSEric Dumazet 	struct sk_buff *nskb;
21252dc41cffSDavid Held 
21262dc41cffSDavid Held 	if (use_hash2) {
2127f0b1e64cSMartin KaFai Lau 		hash2_any = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum) &
212873e2d5e3SPablo Neira 			    udptable->mask;
2129f0b1e64cSMartin KaFai Lau 		hash2 = ipv4_portaddr_hash(net, daddr, hnum) & udptable->mask;
21302dc41cffSDavid Held start_lookup:
213173e2d5e3SPablo Neira 		hslot = &udptable->hash2[hash2];
21322dc41cffSDavid Held 		offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
21332dc41cffSDavid Held 	}
2134db8dac20SDavid S. Miller 
2135ca065d0cSEric Dumazet 	sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
2136ca065d0cSEric Dumazet 		if (!__udp_is_mcast_sock(net, sk, uh->dest, daddr,
2137fb74c277SDavid Ahern 					 uh->source, saddr, dif, sdif, hnum))
2138ca065d0cSEric Dumazet 			continue;
21391240d137SEric Dumazet 
2140ca065d0cSEric Dumazet 		if (!first) {
2141ca065d0cSEric Dumazet 			first = sk;
2142ca065d0cSEric Dumazet 			continue;
2143ca065d0cSEric Dumazet 		}
2144ca065d0cSEric Dumazet 		nskb = skb_clone(skb, GFP_ATOMIC);
2145ca065d0cSEric Dumazet 
2146ca065d0cSEric Dumazet 		if (unlikely(!nskb)) {
2147ca065d0cSEric Dumazet 			atomic_inc(&sk->sk_drops);
214802c22347SEric Dumazet 			__UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS,
2149ca065d0cSEric Dumazet 					IS_UDPLITE(sk));
215002c22347SEric Dumazet 			__UDP_INC_STATS(net, UDP_MIB_INERRORS,
2151ca065d0cSEric Dumazet 					IS_UDPLITE(sk));
2152ca065d0cSEric Dumazet 			continue;
2153ca065d0cSEric Dumazet 		}
2154ca065d0cSEric Dumazet 		if (udp_queue_rcv_skb(sk, nskb) > 0)
2155ca065d0cSEric Dumazet 			consume_skb(nskb);
2156ca065d0cSEric Dumazet 	}
21571240d137SEric Dumazet 
21582dc41cffSDavid Held 	/* Also lookup *:port if we are using hash2 and haven't done so yet. */
21592dc41cffSDavid Held 	if (use_hash2 && hash2 != hash2_any) {
21602dc41cffSDavid Held 		hash2 = hash2_any;
21612dc41cffSDavid Held 		goto start_lookup;
21622dc41cffSDavid Held 	}
21632dc41cffSDavid Held 
2164ca065d0cSEric Dumazet 	if (first) {
2165ca065d0cSEric Dumazet 		if (udp_queue_rcv_skb(first, skb) > 0)
2166ca065d0cSEric Dumazet 			consume_skb(skb);
21671240d137SEric Dumazet 	} else {
2168ca065d0cSEric Dumazet 		kfree_skb(skb);
216902c22347SEric Dumazet 		__UDP_INC_STATS(net, UDP_MIB_IGNOREDMULTI,
217036cbb245SRick Jones 				proto == IPPROTO_UDPLITE);
21711240d137SEric Dumazet 	}
2172db8dac20SDavid S. Miller 	return 0;
2173db8dac20SDavid S. Miller }
2174db8dac20SDavid S. Miller 
2175db8dac20SDavid S. Miller /* Initialize UDP checksum. If exited with zero value (success),
2176db8dac20SDavid S. Miller  * CHECKSUM_UNNECESSARY means, that no more checks are required.
2177db8dac20SDavid S. Miller  * Otherwise, csum completion requires chacksumming packet body,
2178db8dac20SDavid S. Miller  * including udp header and folding it to skb->csum.
2179db8dac20SDavid S. Miller  */
2180db8dac20SDavid S. Miller static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
2181db8dac20SDavid S. Miller 				 int proto)
2182db8dac20SDavid S. Miller {
2183db8dac20SDavid S. Miller 	int err;
2184db8dac20SDavid S. Miller 
2185db8dac20SDavid S. Miller 	UDP_SKB_CB(skb)->partial_cov = 0;
2186db8dac20SDavid S. Miller 	UDP_SKB_CB(skb)->cscov = skb->len;
2187db8dac20SDavid S. Miller 
2188db8dac20SDavid S. Miller 	if (proto == IPPROTO_UDPLITE) {
2189db8dac20SDavid S. Miller 		err = udplite_checksum_init(skb, uh);
2190db8dac20SDavid S. Miller 		if (err)
2191db8dac20SDavid S. Miller 			return err;
219215f35d49SAlexey Kodanev 
219315f35d49SAlexey Kodanev 		if (UDP_SKB_CB(skb)->partial_cov) {
219415f35d49SAlexey Kodanev 			skb->csum = inet_compute_pseudo(skb, proto);
219515f35d49SAlexey Kodanev 			return 0;
219615f35d49SAlexey Kodanev 		}
2197db8dac20SDavid S. Miller 	}
2198db8dac20SDavid S. Miller 
2199b46d9f62SHannes Frederic Sowa 	/* Note, we are only interested in != 0 or == 0, thus the
2200b46d9f62SHannes Frederic Sowa 	 * force to int.
2201b46d9f62SHannes Frederic Sowa 	 */
2202db4f1be3SSean Tranchetti 	err = (__force int)skb_checksum_init_zero_check(skb, proto, uh->check,
2203ed70fcfcSTom Herbert 							inet_compute_pseudo);
2204db4f1be3SSean Tranchetti 	if (err)
2205db4f1be3SSean Tranchetti 		return err;
2206db4f1be3SSean Tranchetti 
2207db4f1be3SSean Tranchetti 	if (skb->ip_summed == CHECKSUM_COMPLETE && !skb->csum_valid) {
2208db4f1be3SSean Tranchetti 		/* If SW calculated the value, we know it's bad */
2209db4f1be3SSean Tranchetti 		if (skb->csum_complete_sw)
2210db4f1be3SSean Tranchetti 			return 1;
2211db4f1be3SSean Tranchetti 
2212db4f1be3SSean Tranchetti 		/* HW says the value is bad. Let's validate that.
2213db4f1be3SSean Tranchetti 		 * skb->csum is no longer the full packet checksum,
2214db4f1be3SSean Tranchetti 		 * so don't treat it as such.
2215db4f1be3SSean Tranchetti 		 */
2216db4f1be3SSean Tranchetti 		skb_checksum_complete_unset(skb);
2217db4f1be3SSean Tranchetti 	}
2218db4f1be3SSean Tranchetti 
2219db4f1be3SSean Tranchetti 	return 0;
2220db8dac20SDavid S. Miller }
2221db8dac20SDavid S. Miller 
22222b5a9217SPaolo Abeni /* wrapper for udp_queue_rcv_skb tacking care of csum conversion and
22232b5a9217SPaolo Abeni  * return code conversion for ip layer consumption
22242b5a9217SPaolo Abeni  */
22252b5a9217SPaolo Abeni static int udp_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb,
22262b5a9217SPaolo Abeni 			       struct udphdr *uh)
22272b5a9217SPaolo Abeni {
22282b5a9217SPaolo Abeni 	int ret;
22292b5a9217SPaolo Abeni 
22302b5a9217SPaolo Abeni 	if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk))
22312b5a9217SPaolo Abeni 		skb_checksum_try_convert(skb, IPPROTO_UDP, uh->check,
22322b5a9217SPaolo Abeni 					 inet_compute_pseudo);
22332b5a9217SPaolo Abeni 
22342b5a9217SPaolo Abeni 	ret = udp_queue_rcv_skb(sk, skb);
22352b5a9217SPaolo Abeni 
22362b5a9217SPaolo Abeni 	/* a return value > 0 means to resubmit the input, but
22372b5a9217SPaolo Abeni 	 * it wants the return to be -protocol, or 0
22382b5a9217SPaolo Abeni 	 */
22392b5a9217SPaolo Abeni 	if (ret > 0)
22402b5a9217SPaolo Abeni 		return -ret;
22412b5a9217SPaolo Abeni 	return 0;
22422b5a9217SPaolo Abeni }
22432b5a9217SPaolo Abeni 
2244db8dac20SDavid S. Miller /*
2245db8dac20SDavid S. Miller  *	All we need to do is get the socket, and then do a checksum.
2246db8dac20SDavid S. Miller  */
2247db8dac20SDavid S. Miller 
2248645ca708SEric Dumazet int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
2249db8dac20SDavid S. Miller 		   int proto)
2250db8dac20SDavid S. Miller {
2251db8dac20SDavid S. Miller 	struct sock *sk;
22527b5e56f9SJesper Dangaard Brouer 	struct udphdr *uh;
2253db8dac20SDavid S. Miller 	unsigned short ulen;
2254adf30907SEric Dumazet 	struct rtable *rt = skb_rtable(skb);
22552783ef23SJesper Dangaard Brouer 	__be32 saddr, daddr;
22560283328eSPavel Emelyanov 	struct net *net = dev_net(skb->dev);
2257db8dac20SDavid S. Miller 
2258db8dac20SDavid S. Miller 	/*
2259db8dac20SDavid S. Miller 	 *  Validate the packet.
2260db8dac20SDavid S. Miller 	 */
2261db8dac20SDavid S. Miller 	if (!pskb_may_pull(skb, sizeof(struct udphdr)))
2262db8dac20SDavid S. Miller 		goto drop;		/* No space for header. */
2263db8dac20SDavid S. Miller 
22647b5e56f9SJesper Dangaard Brouer 	uh   = udp_hdr(skb);
2265db8dac20SDavid S. Miller 	ulen = ntohs(uh->len);
2266ccc2d97cSBjørn Mork 	saddr = ip_hdr(skb)->saddr;
2267ccc2d97cSBjørn Mork 	daddr = ip_hdr(skb)->daddr;
2268ccc2d97cSBjørn Mork 
2269db8dac20SDavid S. Miller 	if (ulen > skb->len)
2270db8dac20SDavid S. Miller 		goto short_packet;
2271db8dac20SDavid S. Miller 
2272db8dac20SDavid S. Miller 	if (proto == IPPROTO_UDP) {
2273db8dac20SDavid S. Miller 		/* UDP validates ulen. */
2274db8dac20SDavid S. Miller 		if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
2275db8dac20SDavid S. Miller 			goto short_packet;
2276db8dac20SDavid S. Miller 		uh = udp_hdr(skb);
2277db8dac20SDavid S. Miller 	}
2278db8dac20SDavid S. Miller 
2279db8dac20SDavid S. Miller 	if (udp4_csum_init(skb, uh, proto))
2280db8dac20SDavid S. Miller 		goto csum_error;
2281db8dac20SDavid S. Miller 
22828afdd99aSEric Dumazet 	sk = skb_steal_sock(skb);
22838afdd99aSEric Dumazet 	if (sk) {
228497502231SEric Dumazet 		struct dst_entry *dst = skb_dst(skb);
2285421b3885SShawn Bohrer 		int ret;
2286421b3885SShawn Bohrer 
228797502231SEric Dumazet 		if (unlikely(sk->sk_rx_dst != dst))
228897502231SEric Dumazet 			udp_sk_rx_dst_set(sk, dst);
2289421b3885SShawn Bohrer 
22902b5a9217SPaolo Abeni 		ret = udp_unicast_rcv_skb(sk, skb, uh);
22918afdd99aSEric Dumazet 		sock_put(sk);
22922b5a9217SPaolo Abeni 		return ret;
2293c18450a5SFabian Frederick 	}
2294c18450a5SFabian Frederick 
2295db8dac20SDavid S. Miller 	if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
2296e3163493SPavel Emelyanov 		return __udp4_lib_mcast_deliver(net, skb, uh,
229736cbb245SRick Jones 						saddr, daddr, udptable, proto);
2298db8dac20SDavid S. Miller 
2299607c4aafSKOVACS Krisztian 	sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
23002b5a9217SPaolo Abeni 	if (sk)
23012b5a9217SPaolo Abeni 		return udp_unicast_rcv_skb(sk, skb, uh);
2302db8dac20SDavid S. Miller 
2303db8dac20SDavid S. Miller 	if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
2304db8dac20SDavid S. Miller 		goto drop;
2305db8dac20SDavid S. Miller 	nf_reset(skb);
2306db8dac20SDavid S. Miller 
2307db8dac20SDavid S. Miller 	/* No socket. Drop packet silently, if checksum is wrong */
2308db8dac20SDavid S. Miller 	if (udp_lib_checksum_complete(skb))
2309db8dac20SDavid S. Miller 		goto csum_error;
2310db8dac20SDavid S. Miller 
231102c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
2312db8dac20SDavid S. Miller 	icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
2313db8dac20SDavid S. Miller 
2314db8dac20SDavid S. Miller 	/*
2315db8dac20SDavid S. Miller 	 * Hmm.  We got an UDP packet to a port to which we
2316db8dac20SDavid S. Miller 	 * don't wanna listen.  Ignore it.
2317db8dac20SDavid S. Miller 	 */
2318db8dac20SDavid S. Miller 	kfree_skb(skb);
2319db8dac20SDavid S. Miller 	return 0;
2320db8dac20SDavid S. Miller 
2321db8dac20SDavid S. Miller short_packet:
2322ba7a46f1SJoe Perches 	net_dbg_ratelimited("UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
2323afd46503SJoe Perches 			    proto == IPPROTO_UDPLITE ? "Lite" : "",
2324afd46503SJoe Perches 			    &saddr, ntohs(uh->source),
2325afd46503SJoe Perches 			    ulen, skb->len,
2326afd46503SJoe Perches 			    &daddr, ntohs(uh->dest));
2327db8dac20SDavid S. Miller 	goto drop;
2328db8dac20SDavid S. Miller 
2329db8dac20SDavid S. Miller csum_error:
2330db8dac20SDavid S. Miller 	/*
2331db8dac20SDavid S. Miller 	 * RFC1122: OK.  Discards the bad packet silently (as far as
2332db8dac20SDavid S. Miller 	 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
2333db8dac20SDavid S. Miller 	 */
2334ba7a46f1SJoe Perches 	net_dbg_ratelimited("UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
2335afd46503SJoe Perches 			    proto == IPPROTO_UDPLITE ? "Lite" : "",
2336afd46503SJoe Perches 			    &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
2337db8dac20SDavid S. Miller 			    ulen);
233802c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
2339db8dac20SDavid S. Miller drop:
234002c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
2341db8dac20SDavid S. Miller 	kfree_skb(skb);
2342db8dac20SDavid S. Miller 	return 0;
2343db8dac20SDavid S. Miller }
2344db8dac20SDavid S. Miller 
2345421b3885SShawn Bohrer /* We can only early demux multicast if there is a single matching socket.
2346421b3885SShawn Bohrer  * If more than one socket found returns NULL
2347421b3885SShawn Bohrer  */
2348421b3885SShawn Bohrer static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net,
2349421b3885SShawn Bohrer 						  __be16 loc_port, __be32 loc_addr,
2350421b3885SShawn Bohrer 						  __be16 rmt_port, __be32 rmt_addr,
2351fb74c277SDavid Ahern 						  int dif, int sdif)
2352421b3885SShawn Bohrer {
2353421b3885SShawn Bohrer 	struct sock *sk, *result;
2354421b3885SShawn Bohrer 	unsigned short hnum = ntohs(loc_port);
2355ca065d0cSEric Dumazet 	unsigned int slot = udp_hashfn(net, hnum, udp_table.mask);
2356421b3885SShawn Bohrer 	struct udp_hslot *hslot = &udp_table.hash[slot];
2357421b3885SShawn Bohrer 
235863c6f81cSEric Dumazet 	/* Do not bother scanning a too big list */
235963c6f81cSEric Dumazet 	if (hslot->count > 10)
236063c6f81cSEric Dumazet 		return NULL;
236163c6f81cSEric Dumazet 
2362421b3885SShawn Bohrer 	result = NULL;
2363ca065d0cSEric Dumazet 	sk_for_each_rcu(sk, &hslot->head) {
2364ca065d0cSEric Dumazet 		if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr,
2365fb74c277SDavid Ahern 					rmt_port, rmt_addr, dif, sdif, hnum)) {
2366ca065d0cSEric Dumazet 			if (result)
2367ca065d0cSEric Dumazet 				return NULL;
2368421b3885SShawn Bohrer 			result = sk;
2369421b3885SShawn Bohrer 		}
2370421b3885SShawn Bohrer 	}
2371421b3885SShawn Bohrer 
2372421b3885SShawn Bohrer 	return result;
2373421b3885SShawn Bohrer }
2374421b3885SShawn Bohrer 
2375421b3885SShawn Bohrer /* For unicast we should only early demux connected sockets or we can
2376421b3885SShawn Bohrer  * break forwarding setups.  The chains here can be long so only check
2377421b3885SShawn Bohrer  * if the first socket is an exact match and if not move on.
2378421b3885SShawn Bohrer  */
2379421b3885SShawn Bohrer static struct sock *__udp4_lib_demux_lookup(struct net *net,
2380421b3885SShawn Bohrer 					    __be16 loc_port, __be32 loc_addr,
2381421b3885SShawn Bohrer 					    __be16 rmt_port, __be32 rmt_addr,
23823fa6f616SDavid Ahern 					    int dif, int sdif)
2383421b3885SShawn Bohrer {
2384421b3885SShawn Bohrer 	unsigned short hnum = ntohs(loc_port);
2385f0b1e64cSMartin KaFai Lau 	unsigned int hash2 = ipv4_portaddr_hash(net, loc_addr, hnum);
2386421b3885SShawn Bohrer 	unsigned int slot2 = hash2 & udp_table.mask;
2387421b3885SShawn Bohrer 	struct udp_hslot *hslot2 = &udp_table.hash2[slot2];
2388c7228317SJoe Perches 	INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr);
2389421b3885SShawn Bohrer 	const __portpair ports = INET_COMBINED_PORTS(rmt_port, hnum);
2390ca065d0cSEric Dumazet 	struct sock *sk;
2391421b3885SShawn Bohrer 
2392ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
2393ca065d0cSEric Dumazet 		if (INET_MATCH(sk, net, acookie, rmt_addr,
23943fa6f616SDavid Ahern 			       loc_addr, ports, dif, sdif))
2395ca065d0cSEric Dumazet 			return sk;
2396421b3885SShawn Bohrer 		/* Only check first socket in chain */
2397421b3885SShawn Bohrer 		break;
2398421b3885SShawn Bohrer 	}
2399ca065d0cSEric Dumazet 	return NULL;
2400421b3885SShawn Bohrer }
2401421b3885SShawn Bohrer 
24027487449cSPaolo Abeni int udp_v4_early_demux(struct sk_buff *skb)
2403421b3885SShawn Bohrer {
2404610438b7SEric Dumazet 	struct net *net = dev_net(skb->dev);
2405bc044e8dSPaolo Abeni 	struct in_device *in_dev = NULL;
2406610438b7SEric Dumazet 	const struct iphdr *iph;
2407610438b7SEric Dumazet 	const struct udphdr *uh;
2408ca065d0cSEric Dumazet 	struct sock *sk = NULL;
2409421b3885SShawn Bohrer 	struct dst_entry *dst;
2410421b3885SShawn Bohrer 	int dif = skb->dev->ifindex;
2411fb74c277SDavid Ahern 	int sdif = inet_sdif(skb);
24126e540309SShawn Bohrer 	int ours;
2413421b3885SShawn Bohrer 
2414421b3885SShawn Bohrer 	/* validate the packet */
2415421b3885SShawn Bohrer 	if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)))
24167487449cSPaolo Abeni 		return 0;
2417421b3885SShawn Bohrer 
2418610438b7SEric Dumazet 	iph = ip_hdr(skb);
2419610438b7SEric Dumazet 	uh = udp_hdr(skb);
2420610438b7SEric Dumazet 
2421996b44fcSPaolo Abeni 	if (skb->pkt_type == PACKET_MULTICAST) {
2422bc044e8dSPaolo Abeni 		in_dev = __in_dev_get_rcu(skb->dev);
24236e540309SShawn Bohrer 
24246e540309SShawn Bohrer 		if (!in_dev)
24257487449cSPaolo Abeni 			return 0;
24266e540309SShawn Bohrer 
24276e540309SShawn Bohrer 		ours = ip_check_mc_rcu(in_dev, iph->daddr, iph->saddr,
24286e540309SShawn Bohrer 				       iph->protocol);
24296e540309SShawn Bohrer 		if (!ours)
24307487449cSPaolo Abeni 			return 0;
2431ad0ea198SPaolo Abeni 
2432421b3885SShawn Bohrer 		sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr,
2433fb74c277SDavid Ahern 						   uh->source, iph->saddr,
2434fb74c277SDavid Ahern 						   dif, sdif);
24356e540309SShawn Bohrer 	} else if (skb->pkt_type == PACKET_HOST) {
2436421b3885SShawn Bohrer 		sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr,
24373fa6f616SDavid Ahern 					     uh->source, iph->saddr, dif, sdif);
24386e540309SShawn Bohrer 	}
2439421b3885SShawn Bohrer 
244041c6d650SReshetova, Elena 	if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
24417487449cSPaolo Abeni 		return 0;
2442421b3885SShawn Bohrer 
2443421b3885SShawn Bohrer 	skb->sk = sk;
244482eabd9eSAlexander Duyck 	skb->destructor = sock_efree;
244510e2eb87SEric Dumazet 	dst = READ_ONCE(sk->sk_rx_dst);
2446421b3885SShawn Bohrer 
2447421b3885SShawn Bohrer 	if (dst)
2448421b3885SShawn Bohrer 		dst = dst_check(dst, 0);
244910e2eb87SEric Dumazet 	if (dst) {
2450bc044e8dSPaolo Abeni 		u32 itag = 0;
2451bc044e8dSPaolo Abeni 
2452d24406c8SWei Wang 		/* set noref for now.
2453d24406c8SWei Wang 		 * any place which wants to hold dst has to call
2454d24406c8SWei Wang 		 * dst_hold_safe()
2455d24406c8SWei Wang 		 */
2456421b3885SShawn Bohrer 		skb_dst_set_noref(skb, dst);
2457bc044e8dSPaolo Abeni 
2458bc044e8dSPaolo Abeni 		/* for unconnected multicast sockets we need to validate
2459bc044e8dSPaolo Abeni 		 * the source on each packet
2460bc044e8dSPaolo Abeni 		 */
2461bc044e8dSPaolo Abeni 		if (!inet_sk(sk)->inet_daddr && in_dev)
2462bc044e8dSPaolo Abeni 			return ip_mc_validate_source(skb, iph->daddr,
2463bc044e8dSPaolo Abeni 						     iph->saddr, iph->tos,
2464bc044e8dSPaolo Abeni 						     skb->dev, in_dev, &itag);
2465421b3885SShawn Bohrer 	}
24667487449cSPaolo Abeni 	return 0;
246710e2eb87SEric Dumazet }
2468421b3885SShawn Bohrer 
2469db8dac20SDavid S. Miller int udp_rcv(struct sk_buff *skb)
2470db8dac20SDavid S. Miller {
2471645ca708SEric Dumazet 	return __udp4_lib_rcv(skb, &udp_table, IPPROTO_UDP);
2472db8dac20SDavid S. Miller }
2473db8dac20SDavid S. Miller 
24747d06b2e0SBrian Haley void udp_destroy_sock(struct sock *sk)
2475db8dac20SDavid S. Miller {
247644046a59STom Parkin 	struct udp_sock *up = udp_sk(sk);
24778a74ad60SEric Dumazet 	bool slow = lock_sock_fast(sk);
2478db8dac20SDavid S. Miller 	udp_flush_pending_frames(sk);
24798a74ad60SEric Dumazet 	unlock_sock_fast(sk, slow);
248060fb9567SPaolo Abeni 	if (static_branch_unlikely(&udp_encap_needed_key)) {
248160fb9567SPaolo Abeni 		if (up->encap_type) {
248244046a59STom Parkin 			void (*encap_destroy)(struct sock *sk);
24836aa7de05SMark Rutland 			encap_destroy = READ_ONCE(up->encap_destroy);
248444046a59STom Parkin 			if (encap_destroy)
248544046a59STom Parkin 				encap_destroy(sk);
248644046a59STom Parkin 		}
248760fb9567SPaolo Abeni 		if (up->encap_enabled)
24889c480601SPaolo Abeni 			static_branch_dec(&udp_encap_needed_key);
248960fb9567SPaolo Abeni 	}
2490db8dac20SDavid S. Miller }
2491db8dac20SDavid S. Miller 
24921da177e4SLinus Torvalds /*
24931da177e4SLinus Torvalds  *	Socket option code for UDP
24941da177e4SLinus Torvalds  */
24954c0a6cb0SGerrit Renker int udp_lib_setsockopt(struct sock *sk, int level, int optname,
2496b7058842SDavid S. Miller 		       char __user *optval, unsigned int optlen,
24974c0a6cb0SGerrit Renker 		       int (*push_pending_frames)(struct sock *))
24981da177e4SLinus Torvalds {
24991da177e4SLinus Torvalds 	struct udp_sock *up = udp_sk(sk);
25001c19448cSTom Herbert 	int val, valbool;
25011da177e4SLinus Torvalds 	int err = 0;
2502b2bf1e26SWang Chen 	int is_udplite = IS_UDPLITE(sk);
25031da177e4SLinus Torvalds 
25041da177e4SLinus Torvalds 	if (optlen < sizeof(int))
25051da177e4SLinus Torvalds 		return -EINVAL;
25061da177e4SLinus Torvalds 
25071da177e4SLinus Torvalds 	if (get_user(val, (int __user *)optval))
25081da177e4SLinus Torvalds 		return -EFAULT;
25091da177e4SLinus Torvalds 
25101c19448cSTom Herbert 	valbool = val ? 1 : 0;
25111c19448cSTom Herbert 
25121da177e4SLinus Torvalds 	switch (optname) {
25131da177e4SLinus Torvalds 	case UDP_CORK:
25141da177e4SLinus Torvalds 		if (val != 0) {
25151da177e4SLinus Torvalds 			up->corkflag = 1;
25161da177e4SLinus Torvalds 		} else {
25171da177e4SLinus Torvalds 			up->corkflag = 0;
25181da177e4SLinus Torvalds 			lock_sock(sk);
25194243cdc2SJoe Perches 			push_pending_frames(sk);
25201da177e4SLinus Torvalds 			release_sock(sk);
25211da177e4SLinus Torvalds 		}
25221da177e4SLinus Torvalds 		break;
25231da177e4SLinus Torvalds 
25241da177e4SLinus Torvalds 	case UDP_ENCAP:
25251da177e4SLinus Torvalds 		switch (val) {
25261da177e4SLinus Torvalds 		case 0:
25271da177e4SLinus Torvalds 		case UDP_ENCAP_ESPINUDP:
25281da177e4SLinus Torvalds 		case UDP_ENCAP_ESPINUDP_NON_IKE:
2529067b207bSJames Chapman 			up->encap_rcv = xfrm4_udp_encap_rcv;
2530067b207bSJames Chapman 			/* FALLTHROUGH */
2531342f0234SJames Chapman 		case UDP_ENCAP_L2TPINUDP:
25321da177e4SLinus Torvalds 			up->encap_type = val;
253360fb9567SPaolo Abeni 			lock_sock(sk);
253460fb9567SPaolo Abeni 			udp_tunnel_encap_enable(sk->sk_socket);
253560fb9567SPaolo Abeni 			release_sock(sk);
25361da177e4SLinus Torvalds 			break;
25371da177e4SLinus Torvalds 		default:
25381da177e4SLinus Torvalds 			err = -ENOPROTOOPT;
25391da177e4SLinus Torvalds 			break;
25401da177e4SLinus Torvalds 		}
25411da177e4SLinus Torvalds 		break;
25421da177e4SLinus Torvalds 
25431c19448cSTom Herbert 	case UDP_NO_CHECK6_TX:
25441c19448cSTom Herbert 		up->no_check6_tx = valbool;
25451c19448cSTom Herbert 		break;
25461c19448cSTom Herbert 
25471c19448cSTom Herbert 	case UDP_NO_CHECK6_RX:
25481c19448cSTom Herbert 		up->no_check6_rx = valbool;
25491c19448cSTom Herbert 		break;
25501c19448cSTom Herbert 
2551bec1f6f6SWillem de Bruijn 	case UDP_SEGMENT:
2552bec1f6f6SWillem de Bruijn 		if (val < 0 || val > USHRT_MAX)
2553bec1f6f6SWillem de Bruijn 			return -EINVAL;
2554bec1f6f6SWillem de Bruijn 		up->gso_size = val;
2555bec1f6f6SWillem de Bruijn 		break;
2556bec1f6f6SWillem de Bruijn 
2557e20cf8d3SPaolo Abeni 	case UDP_GRO:
2558e20cf8d3SPaolo Abeni 		lock_sock(sk);
2559e20cf8d3SPaolo Abeni 		if (valbool)
2560e20cf8d3SPaolo Abeni 			udp_tunnel_encap_enable(sk->sk_socket);
2561e20cf8d3SPaolo Abeni 		up->gro_enabled = valbool;
2562e20cf8d3SPaolo Abeni 		release_sock(sk);
2563e20cf8d3SPaolo Abeni 		break;
2564e20cf8d3SPaolo Abeni 
2565ba4e58ecSGerrit Renker 	/*
2566ba4e58ecSGerrit Renker 	 * 	UDP-Lite's partial checksum coverage (RFC 3828).
2567ba4e58ecSGerrit Renker 	 */
2568ba4e58ecSGerrit Renker 	/* The sender sets actual checksum coverage length via this option.
2569ba4e58ecSGerrit Renker 	 * The case coverage > packet length is handled by send module. */
2570ba4e58ecSGerrit Renker 	case UDPLITE_SEND_CSCOV:
2571b2bf1e26SWang Chen 		if (!is_udplite)         /* Disable the option on UDP sockets */
2572ba4e58ecSGerrit Renker 			return -ENOPROTOOPT;
2573ba4e58ecSGerrit Renker 		if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
2574ba4e58ecSGerrit Renker 			val = 8;
25754be929beSAlexey Dobriyan 		else if (val > USHRT_MAX)
25764be929beSAlexey Dobriyan 			val = USHRT_MAX;
2577ba4e58ecSGerrit Renker 		up->pcslen = val;
2578ba4e58ecSGerrit Renker 		up->pcflag |= UDPLITE_SEND_CC;
2579ba4e58ecSGerrit Renker 		break;
2580ba4e58ecSGerrit Renker 
2581ba4e58ecSGerrit Renker 	/* The receiver specifies a minimum checksum coverage value. To make
2582ba4e58ecSGerrit Renker 	 * sense, this should be set to at least 8 (as done below). If zero is
2583ba4e58ecSGerrit Renker 	 * used, this again means full checksum coverage.                     */
2584ba4e58ecSGerrit Renker 	case UDPLITE_RECV_CSCOV:
2585b2bf1e26SWang Chen 		if (!is_udplite)         /* Disable the option on UDP sockets */
2586ba4e58ecSGerrit Renker 			return -ENOPROTOOPT;
2587ba4e58ecSGerrit Renker 		if (val != 0 && val < 8) /* Avoid silly minimal values.       */
2588ba4e58ecSGerrit Renker 			val = 8;
25894be929beSAlexey Dobriyan 		else if (val > USHRT_MAX)
25904be929beSAlexey Dobriyan 			val = USHRT_MAX;
2591ba4e58ecSGerrit Renker 		up->pcrlen = val;
2592ba4e58ecSGerrit Renker 		up->pcflag |= UDPLITE_RECV_CC;
2593ba4e58ecSGerrit Renker 		break;
2594ba4e58ecSGerrit Renker 
25951da177e4SLinus Torvalds 	default:
25961da177e4SLinus Torvalds 		err = -ENOPROTOOPT;
25971da177e4SLinus Torvalds 		break;
25986516c655SStephen Hemminger 	}
25991da177e4SLinus Torvalds 
26001da177e4SLinus Torvalds 	return err;
26011da177e4SLinus Torvalds }
2602c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_setsockopt);
26031da177e4SLinus Torvalds 
2604db8dac20SDavid S. Miller int udp_setsockopt(struct sock *sk, int level, int optname,
2605b7058842SDavid S. Miller 		   char __user *optval, unsigned int optlen)
2606db8dac20SDavid S. Miller {
2607db8dac20SDavid S. Miller 	if (level == SOL_UDP  ||  level == SOL_UDPLITE)
2608db8dac20SDavid S. Miller 		return udp_lib_setsockopt(sk, level, optname, optval, optlen,
2609db8dac20SDavid S. Miller 					  udp_push_pending_frames);
2610db8dac20SDavid S. Miller 	return ip_setsockopt(sk, level, optname, optval, optlen);
2611db8dac20SDavid S. Miller }
2612db8dac20SDavid S. Miller 
2613db8dac20SDavid S. Miller #ifdef CONFIG_COMPAT
2614db8dac20SDavid S. Miller int compat_udp_setsockopt(struct sock *sk, int level, int optname,
2615b7058842SDavid S. Miller 			  char __user *optval, unsigned int optlen)
2616db8dac20SDavid S. Miller {
2617db8dac20SDavid S. Miller 	if (level == SOL_UDP  ||  level == SOL_UDPLITE)
2618db8dac20SDavid S. Miller 		return udp_lib_setsockopt(sk, level, optname, optval, optlen,
2619db8dac20SDavid S. Miller 					  udp_push_pending_frames);
2620db8dac20SDavid S. Miller 	return compat_ip_setsockopt(sk, level, optname, optval, optlen);
2621db8dac20SDavid S. Miller }
2622db8dac20SDavid S. Miller #endif
2623db8dac20SDavid S. Miller 
26244c0a6cb0SGerrit Renker int udp_lib_getsockopt(struct sock *sk, int level, int optname,
26251da177e4SLinus Torvalds 		       char __user *optval, int __user *optlen)
26261da177e4SLinus Torvalds {
26271da177e4SLinus Torvalds 	struct udp_sock *up = udp_sk(sk);
26281da177e4SLinus Torvalds 	int val, len;
26291da177e4SLinus Torvalds 
26301da177e4SLinus Torvalds 	if (get_user(len, optlen))
26311da177e4SLinus Torvalds 		return -EFAULT;
26321da177e4SLinus Torvalds 
26331da177e4SLinus Torvalds 	len = min_t(unsigned int, len, sizeof(int));
26341da177e4SLinus Torvalds 
26351da177e4SLinus Torvalds 	if (len < 0)
26361da177e4SLinus Torvalds 		return -EINVAL;
26371da177e4SLinus Torvalds 
26381da177e4SLinus Torvalds 	switch (optname) {
26391da177e4SLinus Torvalds 	case UDP_CORK:
26401da177e4SLinus Torvalds 		val = up->corkflag;
26411da177e4SLinus Torvalds 		break;
26421da177e4SLinus Torvalds 
26431da177e4SLinus Torvalds 	case UDP_ENCAP:
26441da177e4SLinus Torvalds 		val = up->encap_type;
26451da177e4SLinus Torvalds 		break;
26461da177e4SLinus Torvalds 
26471c19448cSTom Herbert 	case UDP_NO_CHECK6_TX:
26481c19448cSTom Herbert 		val = up->no_check6_tx;
26491c19448cSTom Herbert 		break;
26501c19448cSTom Herbert 
26511c19448cSTom Herbert 	case UDP_NO_CHECK6_RX:
26521c19448cSTom Herbert 		val = up->no_check6_rx;
26531c19448cSTom Herbert 		break;
26541c19448cSTom Herbert 
2655bec1f6f6SWillem de Bruijn 	case UDP_SEGMENT:
2656bec1f6f6SWillem de Bruijn 		val = up->gso_size;
2657bec1f6f6SWillem de Bruijn 		break;
2658bec1f6f6SWillem de Bruijn 
2659ba4e58ecSGerrit Renker 	/* The following two cannot be changed on UDP sockets, the return is
2660ba4e58ecSGerrit Renker 	 * always 0 (which corresponds to the full checksum coverage of UDP). */
2661ba4e58ecSGerrit Renker 	case UDPLITE_SEND_CSCOV:
2662ba4e58ecSGerrit Renker 		val = up->pcslen;
2663ba4e58ecSGerrit Renker 		break;
2664ba4e58ecSGerrit Renker 
2665ba4e58ecSGerrit Renker 	case UDPLITE_RECV_CSCOV:
2666ba4e58ecSGerrit Renker 		val = up->pcrlen;
2667ba4e58ecSGerrit Renker 		break;
2668ba4e58ecSGerrit Renker 
26691da177e4SLinus Torvalds 	default:
26701da177e4SLinus Torvalds 		return -ENOPROTOOPT;
26716516c655SStephen Hemminger 	}
26721da177e4SLinus Torvalds 
26731da177e4SLinus Torvalds 	if (put_user(len, optlen))
26741da177e4SLinus Torvalds 		return -EFAULT;
26751da177e4SLinus Torvalds 	if (copy_to_user(optval, &val, len))
26761da177e4SLinus Torvalds 		return -EFAULT;
26771da177e4SLinus Torvalds 	return 0;
26781da177e4SLinus Torvalds }
2679c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_getsockopt);
26801da177e4SLinus Torvalds 
2681db8dac20SDavid S. Miller int udp_getsockopt(struct sock *sk, int level, int optname,
2682db8dac20SDavid S. Miller 		   char __user *optval, int __user *optlen)
2683db8dac20SDavid S. Miller {
2684db8dac20SDavid S. Miller 	if (level == SOL_UDP  ||  level == SOL_UDPLITE)
2685db8dac20SDavid S. Miller 		return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2686db8dac20SDavid S. Miller 	return ip_getsockopt(sk, level, optname, optval, optlen);
2687db8dac20SDavid S. Miller }
2688db8dac20SDavid S. Miller 
2689db8dac20SDavid S. Miller #ifdef CONFIG_COMPAT
2690db8dac20SDavid S. Miller int compat_udp_getsockopt(struct sock *sk, int level, int optname,
2691db8dac20SDavid S. Miller 				 char __user *optval, int __user *optlen)
2692db8dac20SDavid S. Miller {
2693db8dac20SDavid S. Miller 	if (level == SOL_UDP  ||  level == SOL_UDPLITE)
2694db8dac20SDavid S. Miller 		return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2695db8dac20SDavid S. Miller 	return compat_ip_getsockopt(sk, level, optname, optval, optlen);
2696db8dac20SDavid S. Miller }
2697db8dac20SDavid S. Miller #endif
26981da177e4SLinus Torvalds /**
26991da177e4SLinus Torvalds  * 	udp_poll - wait for a UDP event.
27001da177e4SLinus Torvalds  *	@file - file struct
27011da177e4SLinus Torvalds  *	@sock - socket
2702a11e1d43SLinus Torvalds  *	@wait - poll table
27031da177e4SLinus Torvalds  *
27041da177e4SLinus Torvalds  *	This is same as datagram poll, except for the special case of
27051da177e4SLinus Torvalds  *	blocking sockets. If application is using a blocking fd
27061da177e4SLinus Torvalds  *	and a packet with checksum error is in the queue;
27071da177e4SLinus Torvalds  *	then it could get return from select indicating data available
27081da177e4SLinus Torvalds  *	but then block when reading it. Add special case code
27091da177e4SLinus Torvalds  *	to work around these arguably broken applications.
27101da177e4SLinus Torvalds  */
2711a11e1d43SLinus Torvalds __poll_t udp_poll(struct file *file, struct socket *sock, poll_table *wait)
27121da177e4SLinus Torvalds {
2713a11e1d43SLinus Torvalds 	__poll_t mask = datagram_poll(file, sock, wait);
27141da177e4SLinus Torvalds 	struct sock *sk = sock->sk;
27151da177e4SLinus Torvalds 
27162276f58aSPaolo Abeni 	if (!skb_queue_empty(&udp_sk(sk)->reader_queue))
2717a9a08845SLinus Torvalds 		mask |= EPOLLIN | EPOLLRDNORM;
27182276f58aSPaolo Abeni 
27191da177e4SLinus Torvalds 	/* Check for false positives due to checksum errors */
2720a11e1d43SLinus Torvalds 	if ((mask & EPOLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
2721e83c6744SEric Dumazet 	    !(sk->sk_shutdown & RCV_SHUTDOWN) && first_packet_length(sk) == -1)
2722a9a08845SLinus Torvalds 		mask &= ~(EPOLLIN | EPOLLRDNORM);
27231da177e4SLinus Torvalds 
27241da177e4SLinus Torvalds 	return mask;
27251da177e4SLinus Torvalds 
27261da177e4SLinus Torvalds }
2727a11e1d43SLinus Torvalds EXPORT_SYMBOL(udp_poll);
27281da177e4SLinus Torvalds 
27295d77dca8SDavid Ahern int udp_abort(struct sock *sk, int err)
27305d77dca8SDavid Ahern {
27315d77dca8SDavid Ahern 	lock_sock(sk);
27325d77dca8SDavid Ahern 
27335d77dca8SDavid Ahern 	sk->sk_err = err;
27345d77dca8SDavid Ahern 	sk->sk_error_report(sk);
2735286c72deSEric Dumazet 	__udp_disconnect(sk, 0);
27365d77dca8SDavid Ahern 
27375d77dca8SDavid Ahern 	release_sock(sk);
27385d77dca8SDavid Ahern 
27395d77dca8SDavid Ahern 	return 0;
27405d77dca8SDavid Ahern }
27415d77dca8SDavid Ahern EXPORT_SYMBOL_GPL(udp_abort);
27425d77dca8SDavid Ahern 
2743db8dac20SDavid S. Miller struct proto udp_prot = {
2744db8dac20SDavid S. Miller 	.name			= "UDP",
2745db8dac20SDavid S. Miller 	.owner			= THIS_MODULE,
2746db8dac20SDavid S. Miller 	.close			= udp_lib_close,
2747d74bad4eSAndrey Ignatov 	.pre_connect		= udp_pre_connect,
2748db8dac20SDavid S. Miller 	.connect		= ip4_datagram_connect,
2749db8dac20SDavid S. Miller 	.disconnect		= udp_disconnect,
2750db8dac20SDavid S. Miller 	.ioctl			= udp_ioctl,
2751850cbaddSPaolo Abeni 	.init			= udp_init_sock,
2752db8dac20SDavid S. Miller 	.destroy		= udp_destroy_sock,
2753db8dac20SDavid S. Miller 	.setsockopt		= udp_setsockopt,
2754db8dac20SDavid S. Miller 	.getsockopt		= udp_getsockopt,
2755db8dac20SDavid S. Miller 	.sendmsg		= udp_sendmsg,
2756db8dac20SDavid S. Miller 	.recvmsg		= udp_recvmsg,
2757db8dac20SDavid S. Miller 	.sendpage		= udp_sendpage,
27588141ed9fSSteffen Klassert 	.release_cb		= ip4_datagram_release_cb,
2759db8dac20SDavid S. Miller 	.hash			= udp_lib_hash,
2760db8dac20SDavid S. Miller 	.unhash			= udp_lib_unhash,
2761719f8358SEric Dumazet 	.rehash			= udp_v4_rehash,
2762db8dac20SDavid S. Miller 	.get_port		= udp_v4_get_port,
2763db8dac20SDavid S. Miller 	.memory_allocated	= &udp_memory_allocated,
2764db8dac20SDavid S. Miller 	.sysctl_mem		= sysctl_udp_mem,
27651e802951STonghao Zhang 	.sysctl_wmem_offset	= offsetof(struct net, ipv4.sysctl_udp_wmem_min),
27661e802951STonghao Zhang 	.sysctl_rmem_offset	= offsetof(struct net, ipv4.sysctl_udp_rmem_min),
2767db8dac20SDavid S. Miller 	.obj_size		= sizeof(struct udp_sock),
2768645ca708SEric Dumazet 	.h.udp_table		= &udp_table,
2769db8dac20SDavid S. Miller #ifdef CONFIG_COMPAT
2770db8dac20SDavid S. Miller 	.compat_setsockopt	= compat_udp_setsockopt,
2771db8dac20SDavid S. Miller 	.compat_getsockopt	= compat_udp_getsockopt,
2772db8dac20SDavid S. Miller #endif
27735d77dca8SDavid Ahern 	.diag_destroy		= udp_abort,
2774db8dac20SDavid S. Miller };
2775c482c568SEric Dumazet EXPORT_SYMBOL(udp_prot);
27761da177e4SLinus Torvalds 
27771da177e4SLinus Torvalds /* ------------------------------------------------------------------------ */
27781da177e4SLinus Torvalds #ifdef CONFIG_PROC_FS
27791da177e4SLinus Torvalds 
2780645ca708SEric Dumazet static struct sock *udp_get_first(struct seq_file *seq, int start)
27811da177e4SLinus Torvalds {
27821da177e4SLinus Torvalds 	struct sock *sk;
2783a3d2599bSChristoph Hellwig 	struct udp_seq_afinfo *afinfo = PDE_DATA(file_inode(seq->file));
27841da177e4SLinus Torvalds 	struct udp_iter_state *state = seq->private;
27856f191efeSDenis V. Lunev 	struct net *net = seq_file_net(seq);
27861da177e4SLinus Torvalds 
2787a3d2599bSChristoph Hellwig 	for (state->bucket = start; state->bucket <= afinfo->udp_table->mask;
2788f86dcc5aSEric Dumazet 	     ++state->bucket) {
2789a3d2599bSChristoph Hellwig 		struct udp_hslot *hslot = &afinfo->udp_table->hash[state->bucket];
2790f86dcc5aSEric Dumazet 
2791ca065d0cSEric Dumazet 		if (hlist_empty(&hslot->head))
2792f86dcc5aSEric Dumazet 			continue;
2793f86dcc5aSEric Dumazet 
2794645ca708SEric Dumazet 		spin_lock_bh(&hslot->lock);
2795ca065d0cSEric Dumazet 		sk_for_each(sk, &hslot->head) {
2796878628fbSYOSHIFUJI Hideaki 			if (!net_eq(sock_net(sk), net))
2797a91275efSDaniel Lezcano 				continue;
2798a3d2599bSChristoph Hellwig 			if (sk->sk_family == afinfo->family)
27991da177e4SLinus Torvalds 				goto found;
28001da177e4SLinus Torvalds 		}
2801645ca708SEric Dumazet 		spin_unlock_bh(&hslot->lock);
28021da177e4SLinus Torvalds 	}
28031da177e4SLinus Torvalds 	sk = NULL;
28041da177e4SLinus Torvalds found:
28051da177e4SLinus Torvalds 	return sk;
28061da177e4SLinus Torvalds }
28071da177e4SLinus Torvalds 
28081da177e4SLinus Torvalds static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
28091da177e4SLinus Torvalds {
2810a3d2599bSChristoph Hellwig 	struct udp_seq_afinfo *afinfo = PDE_DATA(file_inode(seq->file));
28111da177e4SLinus Torvalds 	struct udp_iter_state *state = seq->private;
28126f191efeSDenis V. Lunev 	struct net *net = seq_file_net(seq);
28131da177e4SLinus Torvalds 
28141da177e4SLinus Torvalds 	do {
2815ca065d0cSEric Dumazet 		sk = sk_next(sk);
2816a3d2599bSChristoph Hellwig 	} while (sk && (!net_eq(sock_net(sk), net) || sk->sk_family != afinfo->family));
28171da177e4SLinus Torvalds 
2818645ca708SEric Dumazet 	if (!sk) {
2819a3d2599bSChristoph Hellwig 		if (state->bucket <= afinfo->udp_table->mask)
2820a3d2599bSChristoph Hellwig 			spin_unlock_bh(&afinfo->udp_table->hash[state->bucket].lock);
2821645ca708SEric Dumazet 		return udp_get_first(seq, state->bucket + 1);
28221da177e4SLinus Torvalds 	}
28231da177e4SLinus Torvalds 	return sk;
28241da177e4SLinus Torvalds }
28251da177e4SLinus Torvalds 
28261da177e4SLinus Torvalds static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
28271da177e4SLinus Torvalds {
2828645ca708SEric Dumazet 	struct sock *sk = udp_get_first(seq, 0);
28291da177e4SLinus Torvalds 
28301da177e4SLinus Torvalds 	if (sk)
28311da177e4SLinus Torvalds 		while (pos && (sk = udp_get_next(seq, sk)) != NULL)
28321da177e4SLinus Torvalds 			--pos;
28331da177e4SLinus Torvalds 	return pos ? NULL : sk;
28341da177e4SLinus Torvalds }
28351da177e4SLinus Torvalds 
2836a3d2599bSChristoph Hellwig void *udp_seq_start(struct seq_file *seq, loff_t *pos)
28371da177e4SLinus Torvalds {
283830842f29SVitaly Mayatskikh 	struct udp_iter_state *state = seq->private;
2839f86dcc5aSEric Dumazet 	state->bucket = MAX_UDP_PORTS;
284030842f29SVitaly Mayatskikh 
2841b50660f1SYOSHIFUJI Hideaki 	return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
28421da177e4SLinus Torvalds }
2843a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_start);
28441da177e4SLinus Torvalds 
2845a3d2599bSChristoph Hellwig void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
28461da177e4SLinus Torvalds {
28471da177e4SLinus Torvalds 	struct sock *sk;
28481da177e4SLinus Torvalds 
2849b50660f1SYOSHIFUJI Hideaki 	if (v == SEQ_START_TOKEN)
28501da177e4SLinus Torvalds 		sk = udp_get_idx(seq, 0);
28511da177e4SLinus Torvalds 	else
28521da177e4SLinus Torvalds 		sk = udp_get_next(seq, v);
28531da177e4SLinus Torvalds 
28541da177e4SLinus Torvalds 	++*pos;
28551da177e4SLinus Torvalds 	return sk;
28561da177e4SLinus Torvalds }
2857a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_next);
28581da177e4SLinus Torvalds 
2859a3d2599bSChristoph Hellwig void udp_seq_stop(struct seq_file *seq, void *v)
28601da177e4SLinus Torvalds {
2861a3d2599bSChristoph Hellwig 	struct udp_seq_afinfo *afinfo = PDE_DATA(file_inode(seq->file));
2862645ca708SEric Dumazet 	struct udp_iter_state *state = seq->private;
2863645ca708SEric Dumazet 
2864a3d2599bSChristoph Hellwig 	if (state->bucket <= afinfo->udp_table->mask)
2865a3d2599bSChristoph Hellwig 		spin_unlock_bh(&afinfo->udp_table->hash[state->bucket].lock);
28661da177e4SLinus Torvalds }
2867a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_stop);
2868db8dac20SDavid S. Miller 
2869db8dac20SDavid S. Miller /* ------------------------------------------------------------------------ */
28705e659e4cSPavel Emelyanov static void udp4_format_sock(struct sock *sp, struct seq_file *f,
2871652586dfSTetsuo Handa 		int bucket)
2872db8dac20SDavid S. Miller {
2873db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sp);
2874c720c7e8SEric Dumazet 	__be32 dest = inet->inet_daddr;
2875c720c7e8SEric Dumazet 	__be32 src  = inet->inet_rcv_saddr;
2876c720c7e8SEric Dumazet 	__u16 destp	  = ntohs(inet->inet_dport);
2877c720c7e8SEric Dumazet 	__u16 srcp	  = ntohs(inet->inet_sport);
2878db8dac20SDavid S. Miller 
2879f86dcc5aSEric Dumazet 	seq_printf(f, "%5d: %08X:%04X %08X:%04X"
2880ea9a0379SPatrick Talbert 		" %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %u",
2881db8dac20SDavid S. Miller 		bucket, src, srcp, dest, destp, sp->sk_state,
288231e6d363SEric Dumazet 		sk_wmem_alloc_get(sp),
28836c206b20SPaolo Abeni 		udp_rqueue_get(sp),
2884a7cb5a49SEric W. Biederman 		0, 0L, 0,
2885a7cb5a49SEric W. Biederman 		from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
2886a7cb5a49SEric W. Biederman 		0, sock_i_ino(sp),
288741c6d650SReshetova, Elena 		refcount_read(&sp->sk_refcnt), sp,
2888652586dfSTetsuo Handa 		atomic_read(&sp->sk_drops));
2889db8dac20SDavid S. Miller }
2890db8dac20SDavid S. Miller 
2891db8dac20SDavid S. Miller int udp4_seq_show(struct seq_file *seq, void *v)
2892db8dac20SDavid S. Miller {
2893652586dfSTetsuo Handa 	seq_setwidth(seq, 127);
2894db8dac20SDavid S. Miller 	if (v == SEQ_START_TOKEN)
2895652586dfSTetsuo Handa 		seq_puts(seq, "  sl  local_address rem_address   st tx_queue "
2896db8dac20SDavid S. Miller 			   "rx_queue tr tm->when retrnsmt   uid  timeout "
2897cb61cb9bSEric Dumazet 			   "inode ref pointer drops");
2898db8dac20SDavid S. Miller 	else {
2899db8dac20SDavid S. Miller 		struct udp_iter_state *state = seq->private;
2900db8dac20SDavid S. Miller 
2901652586dfSTetsuo Handa 		udp4_format_sock(v, seq, state->bucket);
2902db8dac20SDavid S. Miller 	}
2903652586dfSTetsuo Handa 	seq_pad(seq, '\n');
2904db8dac20SDavid S. Miller 	return 0;
2905db8dac20SDavid S. Miller }
2906db8dac20SDavid S. Miller 
2907c3506372SChristoph Hellwig const struct seq_operations udp_seq_ops = {
2908a3d2599bSChristoph Hellwig 	.start		= udp_seq_start,
2909a3d2599bSChristoph Hellwig 	.next		= udp_seq_next,
2910a3d2599bSChristoph Hellwig 	.stop		= udp_seq_stop,
2911a3d2599bSChristoph Hellwig 	.show		= udp4_seq_show,
2912a3d2599bSChristoph Hellwig };
2913c3506372SChristoph Hellwig EXPORT_SYMBOL(udp_seq_ops);
291473cb88ecSArjan van de Ven 
2915db8dac20SDavid S. Miller static struct udp_seq_afinfo udp4_seq_afinfo = {
2916db8dac20SDavid S. Miller 	.family		= AF_INET,
2917645ca708SEric Dumazet 	.udp_table	= &udp_table,
2918db8dac20SDavid S. Miller };
2919db8dac20SDavid S. Miller 
29202c8c1e72SAlexey Dobriyan static int __net_init udp4_proc_init_net(struct net *net)
292115439febSPavel Emelyanov {
2922c3506372SChristoph Hellwig 	if (!proc_create_net_data("udp", 0444, net->proc_net, &udp_seq_ops,
2923c3506372SChristoph Hellwig 			sizeof(struct udp_iter_state), &udp4_seq_afinfo))
2924a3d2599bSChristoph Hellwig 		return -ENOMEM;
2925a3d2599bSChristoph Hellwig 	return 0;
292615439febSPavel Emelyanov }
292715439febSPavel Emelyanov 
29282c8c1e72SAlexey Dobriyan static void __net_exit udp4_proc_exit_net(struct net *net)
292915439febSPavel Emelyanov {
2930a3d2599bSChristoph Hellwig 	remove_proc_entry("udp", net->proc_net);
293115439febSPavel Emelyanov }
293215439febSPavel Emelyanov 
293315439febSPavel Emelyanov static struct pernet_operations udp4_net_ops = {
293415439febSPavel Emelyanov 	.init = udp4_proc_init_net,
293515439febSPavel Emelyanov 	.exit = udp4_proc_exit_net,
293615439febSPavel Emelyanov };
293715439febSPavel Emelyanov 
2938db8dac20SDavid S. Miller int __init udp4_proc_init(void)
2939db8dac20SDavid S. Miller {
294015439febSPavel Emelyanov 	return register_pernet_subsys(&udp4_net_ops);
2941db8dac20SDavid S. Miller }
2942db8dac20SDavid S. Miller 
2943db8dac20SDavid S. Miller void udp4_proc_exit(void)
2944db8dac20SDavid S. Miller {
294515439febSPavel Emelyanov 	unregister_pernet_subsys(&udp4_net_ops);
2946db8dac20SDavid S. Miller }
29471da177e4SLinus Torvalds #endif /* CONFIG_PROC_FS */
29481da177e4SLinus Torvalds 
2949f86dcc5aSEric Dumazet static __initdata unsigned long uhash_entries;
2950f86dcc5aSEric Dumazet static int __init set_uhash_entries(char *str)
2951645ca708SEric Dumazet {
2952413c27d8SEldad Zack 	ssize_t ret;
2953413c27d8SEldad Zack 
2954f86dcc5aSEric Dumazet 	if (!str)
2955f86dcc5aSEric Dumazet 		return 0;
2956413c27d8SEldad Zack 
2957413c27d8SEldad Zack 	ret = kstrtoul(str, 0, &uhash_entries);
2958413c27d8SEldad Zack 	if (ret)
2959413c27d8SEldad Zack 		return 0;
2960413c27d8SEldad Zack 
2961f86dcc5aSEric Dumazet 	if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
2962f86dcc5aSEric Dumazet 		uhash_entries = UDP_HTABLE_SIZE_MIN;
2963f86dcc5aSEric Dumazet 	return 1;
2964f86dcc5aSEric Dumazet }
2965f86dcc5aSEric Dumazet __setup("uhash_entries=", set_uhash_entries);
2966645ca708SEric Dumazet 
2967f86dcc5aSEric Dumazet void __init udp_table_init(struct udp_table *table, const char *name)
2968f86dcc5aSEric Dumazet {
2969f86dcc5aSEric Dumazet 	unsigned int i;
2970f86dcc5aSEric Dumazet 
2971f86dcc5aSEric Dumazet 	table->hash = alloc_large_system_hash(name,
2972512615b6SEric Dumazet 					      2 * sizeof(struct udp_hslot),
2973f86dcc5aSEric Dumazet 					      uhash_entries,
2974f86dcc5aSEric Dumazet 					      21, /* one slot per 2 MB */
2975f86dcc5aSEric Dumazet 					      0,
2976f86dcc5aSEric Dumazet 					      &table->log,
2977f86dcc5aSEric Dumazet 					      &table->mask,
297831fe62b9STim Bird 					      UDP_HTABLE_SIZE_MIN,
2979f86dcc5aSEric Dumazet 					      64 * 1024);
298031fe62b9STim Bird 
2981512615b6SEric Dumazet 	table->hash2 = table->hash + (table->mask + 1);
2982f86dcc5aSEric Dumazet 	for (i = 0; i <= table->mask; i++) {
2983ca065d0cSEric Dumazet 		INIT_HLIST_HEAD(&table->hash[i].head);
2984fdcc8aa9SEric Dumazet 		table->hash[i].count = 0;
2985645ca708SEric Dumazet 		spin_lock_init(&table->hash[i].lock);
2986645ca708SEric Dumazet 	}
2987512615b6SEric Dumazet 	for (i = 0; i <= table->mask; i++) {
2988ca065d0cSEric Dumazet 		INIT_HLIST_HEAD(&table->hash2[i].head);
2989512615b6SEric Dumazet 		table->hash2[i].count = 0;
2990512615b6SEric Dumazet 		spin_lock_init(&table->hash2[i].lock);
2991512615b6SEric Dumazet 	}
2992645ca708SEric Dumazet }
2993645ca708SEric Dumazet 
2994723b8e46STom Herbert u32 udp_flow_hashrnd(void)
2995723b8e46STom Herbert {
2996723b8e46STom Herbert 	static u32 hashrnd __read_mostly;
2997723b8e46STom Herbert 
2998723b8e46STom Herbert 	net_get_random_once(&hashrnd, sizeof(hashrnd));
2999723b8e46STom Herbert 
3000723b8e46STom Herbert 	return hashrnd;
3001723b8e46STom Herbert }
3002723b8e46STom Herbert EXPORT_SYMBOL(udp_flow_hashrnd);
3003723b8e46STom Herbert 
30041e802951STonghao Zhang static void __udp_sysctl_init(struct net *net)
30051e802951STonghao Zhang {
30061e802951STonghao Zhang 	net->ipv4.sysctl_udp_rmem_min = SK_MEM_QUANTUM;
30071e802951STonghao Zhang 	net->ipv4.sysctl_udp_wmem_min = SK_MEM_QUANTUM;
30081e802951STonghao Zhang 
30091e802951STonghao Zhang #ifdef CONFIG_NET_L3_MASTER_DEV
30101e802951STonghao Zhang 	net->ipv4.sysctl_udp_l3mdev_accept = 0;
30111e802951STonghao Zhang #endif
30121e802951STonghao Zhang }
30131e802951STonghao Zhang 
30141e802951STonghao Zhang static int __net_init udp_sysctl_init(struct net *net)
30151e802951STonghao Zhang {
30161e802951STonghao Zhang 	__udp_sysctl_init(net);
30171e802951STonghao Zhang 	return 0;
30181e802951STonghao Zhang }
30191e802951STonghao Zhang 
30201e802951STonghao Zhang static struct pernet_operations __net_initdata udp_sysctl_ops = {
30211e802951STonghao Zhang 	.init	= udp_sysctl_init,
30221e802951STonghao Zhang };
30231e802951STonghao Zhang 
302495766fffSHideo Aoki void __init udp_init(void)
302595766fffSHideo Aoki {
3026f03d78dbSEric Dumazet 	unsigned long limit;
30274b272750SEric Dumazet 	unsigned int i;
302895766fffSHideo Aoki 
3029f86dcc5aSEric Dumazet 	udp_table_init(&udp_table, "UDP");
3030f03d78dbSEric Dumazet 	limit = nr_free_buffer_pages() / 8;
303195766fffSHideo Aoki 	limit = max(limit, 128UL);
303295766fffSHideo Aoki 	sysctl_udp_mem[0] = limit / 4 * 3;
303395766fffSHideo Aoki 	sysctl_udp_mem[1] = limit;
303495766fffSHideo Aoki 	sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
303595766fffSHideo Aoki 
30361e802951STonghao Zhang 	__udp_sysctl_init(&init_net);
30374b272750SEric Dumazet 
30384b272750SEric Dumazet 	/* 16 spinlocks per cpu */
30394b272750SEric Dumazet 	udp_busylocks_log = ilog2(nr_cpu_ids) + 4;
30404b272750SEric Dumazet 	udp_busylocks = kmalloc(sizeof(spinlock_t) << udp_busylocks_log,
30414b272750SEric Dumazet 				GFP_KERNEL);
30424b272750SEric Dumazet 	if (!udp_busylocks)
30434b272750SEric Dumazet 		panic("UDP: failed to alloc udp_busylocks\n");
30444b272750SEric Dumazet 	for (i = 0; i < (1U << udp_busylocks_log); i++)
30454b272750SEric Dumazet 		spin_lock_init(udp_busylocks + i);
30461e802951STonghao Zhang 
30471e802951STonghao Zhang 	if (register_pernet_subsys(&udp_sysctl_ops))
30481e802951STonghao Zhang 		panic("UDP: failed to init sysctl parameters.\n");
304995766fffSHideo Aoki }
3050