xref: /linux/net/ipv4/udp.c (revision 9410645520e9b820069761f3450ef6661418e279)
12874c5fdSThomas Gleixner // SPDX-License-Identifier: GPL-2.0-or-later
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  * INET		An implementation of the TCP/IP protocol suite for the LINUX
41da177e4SLinus Torvalds  *		operating system.  INET is implemented using the  BSD Socket
51da177e4SLinus Torvalds  *		interface as the means of communication with the user level.
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  *		The User Datagram Protocol (UDP).
81da177e4SLinus Torvalds  *
902c30a84SJesper Juhl  * Authors:	Ross Biro
101da177e4SLinus Torvalds  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
111da177e4SLinus Torvalds  *		Arnt Gulbrandsen, <agulbra@nvg.unit.no>
12113aa838SAlan Cox  *		Alan Cox, <alan@lxorguk.ukuu.org.uk>
131da177e4SLinus Torvalds  *		Hirokazu Takahashi, <taka@valinux.co.jp>
141da177e4SLinus Torvalds  *
151da177e4SLinus Torvalds  * Fixes:
161da177e4SLinus Torvalds  *		Alan Cox	:	verify_area() calls
171da177e4SLinus Torvalds  *		Alan Cox	: 	stopped close while in use off icmp
181da177e4SLinus Torvalds  *					messages. Not a fix but a botch that
191da177e4SLinus Torvalds  *					for udp at least is 'valid'.
201da177e4SLinus Torvalds  *		Alan Cox	:	Fixed icmp handling properly
211da177e4SLinus Torvalds  *		Alan Cox	: 	Correct error for oversized datagrams
221da177e4SLinus Torvalds  *		Alan Cox	:	Tidied select() semantics.
231da177e4SLinus Torvalds  *		Alan Cox	:	udp_err() fixed properly, also now
241da177e4SLinus Torvalds  *					select and read wake correctly on errors
251da177e4SLinus Torvalds  *		Alan Cox	:	udp_send verify_area moved to avoid mem leak
261da177e4SLinus Torvalds  *		Alan Cox	:	UDP can count its memory
271da177e4SLinus Torvalds  *		Alan Cox	:	send to an unknown connection causes
281da177e4SLinus Torvalds  *					an ECONNREFUSED off the icmp, but
291da177e4SLinus Torvalds  *					does NOT close.
301da177e4SLinus Torvalds  *		Alan Cox	:	Switched to new sk_buff handlers. No more backlog!
311da177e4SLinus Torvalds  *		Alan Cox	:	Using generic datagram code. Even smaller and the PEEK
321da177e4SLinus Torvalds  *					bug no longer crashes it.
331da177e4SLinus Torvalds  *		Fred Van Kempen	: 	Net2e support for sk->broadcast.
341da177e4SLinus Torvalds  *		Alan Cox	:	Uses skb_free_datagram
351da177e4SLinus Torvalds  *		Alan Cox	:	Added get/set sockopt support.
361da177e4SLinus Torvalds  *		Alan Cox	:	Broadcasting without option set returns EACCES.
371da177e4SLinus Torvalds  *		Alan Cox	:	No wakeup calls. Instead we now use the callbacks.
381da177e4SLinus Torvalds  *		Alan Cox	:	Use ip_tos and ip_ttl
391da177e4SLinus Torvalds  *		Alan Cox	:	SNMP Mibs
401da177e4SLinus Torvalds  *		Alan Cox	:	MSG_DONTROUTE, and 0.0.0.0 support.
411da177e4SLinus Torvalds  *		Matt Dillon	:	UDP length checks.
421da177e4SLinus Torvalds  *		Alan Cox	:	Smarter af_inet used properly.
431da177e4SLinus Torvalds  *		Alan Cox	:	Use new kernel side addressing.
441da177e4SLinus Torvalds  *		Alan Cox	:	Incorrect return on truncated datagram receive.
451da177e4SLinus Torvalds  *	Arnt Gulbrandsen 	:	New udp_send and stuff
461da177e4SLinus Torvalds  *		Alan Cox	:	Cache last socket
471da177e4SLinus Torvalds  *		Alan Cox	:	Route cache
481da177e4SLinus Torvalds  *		Jon Peatfield	:	Minor efficiency fix to sendto().
491da177e4SLinus Torvalds  *		Mike Shaver	:	RFC1122 checks.
501da177e4SLinus Torvalds  *		Alan Cox	:	Nonblocking error fix.
511da177e4SLinus Torvalds  *	Willy Konynenberg	:	Transparent proxying support.
521da177e4SLinus Torvalds  *		Mike McLagan	:	Routing by source
531da177e4SLinus Torvalds  *		David S. Miller	:	New socket lookup architecture.
541da177e4SLinus Torvalds  *					Last socket cache retained as it
551da177e4SLinus Torvalds  *					does have a high hit rate.
561da177e4SLinus Torvalds  *		Olaf Kirch	:	Don't linearise iovec on sendmsg.
571da177e4SLinus Torvalds  *		Andi Kleen	:	Some cleanups, cache destination entry
581da177e4SLinus Torvalds  *					for connect.
591da177e4SLinus Torvalds  *	Vitaly E. Lavrov	:	Transparent proxy revived after year coma.
601da177e4SLinus Torvalds  *		Melvin Smith	:	Check msg_name not msg_namelen in sendto(),
611da177e4SLinus Torvalds  *					return ENOTCONN for unconnected sockets (POSIX)
621da177e4SLinus Torvalds  *		Janos Farkas	:	don't deliver multi/broadcasts to a different
631da177e4SLinus Torvalds  *					bound-to-device socket
641da177e4SLinus Torvalds  *	Hirokazu Takahashi	:	HW checksumming for outgoing UDP
651da177e4SLinus Torvalds  *					datagrams.
661da177e4SLinus Torvalds  *	Hirokazu Takahashi	:	sendfile() on UDP works now.
671da177e4SLinus Torvalds  *		Arnaldo C. Melo :	convert /proc/net/udp to seq_file
681da177e4SLinus Torvalds  *	YOSHIFUJI Hideaki @USAGI and:	Support IPV6_V6ONLY socket option, which
691da177e4SLinus Torvalds  *	Alexey Kuznetsov:		allow both IPv4 and IPv6 sockets to bind
701da177e4SLinus Torvalds  *					a single port at the same time.
711da177e4SLinus Torvalds  *	Derek Atkins <derek@ihtfp.com>: Add Encapulation Support
72342f0234SJames Chapman  *	James Chapman		:	Add L2TP encapsulation type.
731da177e4SLinus Torvalds  */
741da177e4SLinus Torvalds 
75afd46503SJoe Perches #define pr_fmt(fmt) "UDP: " fmt
76afd46503SJoe Perches 
77aef2fedaSJakub Kicinski #include <linux/bpf-cgroup.h>
787c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
791da177e4SLinus Torvalds #include <asm/ioctls.h>
8057c8a661SMike Rapoport #include <linux/memblock.h>
818203efb3SEric Dumazet #include <linux/highmem.h>
821da177e4SLinus Torvalds #include <linux/types.h>
831da177e4SLinus Torvalds #include <linux/fcntl.h>
841da177e4SLinus Torvalds #include <linux/module.h>
851da177e4SLinus Torvalds #include <linux/socket.h>
861da177e4SLinus Torvalds #include <linux/sockios.h>
8714c85021SArnaldo Carvalho de Melo #include <linux/igmp.h>
886e540309SShawn Bohrer #include <linux/inetdevice.h>
891da177e4SLinus Torvalds #include <linux/in.h>
901da177e4SLinus Torvalds #include <linux/errno.h>
911da177e4SLinus Torvalds #include <linux/timer.h>
921da177e4SLinus Torvalds #include <linux/mm.h>
931da177e4SLinus Torvalds #include <linux/inet.h>
941da177e4SLinus Torvalds #include <linux/netdevice.h>
955a0e3ad6STejun Heo #include <linux/slab.h>
96c752f073SArnaldo Carvalho de Melo #include <net/tcp_states.h>
971da177e4SLinus Torvalds #include <linux/skbuff.h>
981da177e4SLinus Torvalds #include <linux/proc_fs.h>
991da177e4SLinus Torvalds #include <linux/seq_file.h>
100457c4cbcSEric W. Biederman #include <net/net_namespace.h>
1011da177e4SLinus Torvalds #include <net/icmp.h>
102421b3885SShawn Bohrer #include <net/inet_hashtables.h>
103e7cc0824SStefano Brivio #include <net/ip_tunnels.h>
1041da177e4SLinus Torvalds #include <net/route.h>
1051da177e4SLinus Torvalds #include <net/checksum.h>
106d457a0e3SEric Dumazet #include <net/gso.h>
1071da177e4SLinus Torvalds #include <net/xfrm.h>
108296f7ea7SSatoru Moriya #include <trace/events/udp.h>
109447167bfSEric Dumazet #include <linux/static_key.h>
110951cf368SYonghong Song #include <linux/btf_ids.h>
11122911fc5SEric Dumazet #include <trace/events/skb.h>
112076bb0c8SEliezer Tamir #include <net/busy_poll.h>
113ba4e58ecSGerrit Renker #include "udp_impl.h"
114e32ea7e7SCraig Gallek #include <net/sock_reuseport.h>
115217375a0SEric Dumazet #include <net/addrconf.h>
11660fb9567SPaolo Abeni #include <net/udp_tunnel.h>
1177938cd15SRichard Gobert #include <net/gro.h>
118*b6791ac5SIdo Schimmel #include <net/inet_dscp.h>
1190146dca7SSabrina Dubroca #if IS_ENABLED(CONFIG_IPV6)
1200146dca7SSabrina Dubroca #include <net/ipv6_stubs.h>
1210146dca7SSabrina Dubroca #endif
1221da177e4SLinus Torvalds 
123f86dcc5aSEric Dumazet struct udp_table udp_table __read_mostly;
124645ca708SEric Dumazet EXPORT_SYMBOL(udp_table);
1251da177e4SLinus Torvalds 
1268d987e5cSEric Dumazet long sysctl_udp_mem[3] __read_mostly;
12795766fffSHideo Aoki EXPORT_SYMBOL(sysctl_udp_mem);
128c482c568SEric Dumazet 
12991b6d325SEric Dumazet atomic_long_t udp_memory_allocated ____cacheline_aligned_in_smp;
13095766fffSHideo Aoki EXPORT_SYMBOL(udp_memory_allocated);
1310defbb0aSEric Dumazet DEFINE_PER_CPU(int, udp_memory_per_cpu_fw_alloc);
1320defbb0aSEric Dumazet EXPORT_PER_CPU_SYMBOL_GPL(udp_memory_per_cpu_fw_alloc);
13395766fffSHideo Aoki 
134f86dcc5aSEric Dumazet #define MAX_UDP_PORTS 65536
1359804985bSKuniyuki Iwashima #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN_PERNET)
13698322f22SEric Dumazet 
udp_get_table_prot(struct sock * sk)13767fb4330SKuniyuki Iwashima static struct udp_table *udp_get_table_prot(struct sock *sk)
13867fb4330SKuniyuki Iwashima {
13967fb4330SKuniyuki Iwashima 	return sk->sk_prot->h.udp_table ? : sock_net(sk)->ipv4.udp_table;
14067fb4330SKuniyuki Iwashima }
14167fb4330SKuniyuki Iwashima 
udp_lib_lport_inuse(struct net * net,__u16 num,const struct udp_hslot * hslot,unsigned long * bitmap,struct sock * sk,unsigned int log)142f24d43c0SEric Dumazet static int udp_lib_lport_inuse(struct net *net, __u16 num,
143645ca708SEric Dumazet 			       const struct udp_hslot *hslot,
14498322f22SEric Dumazet 			       unsigned long *bitmap,
145fe38d2a1SJosef Bacik 			       struct sock *sk, unsigned int log)
14625030a7fSGerrit Renker {
147f24d43c0SEric Dumazet 	struct sock *sk2;
148ba418fa3STom Herbert 	kuid_t uid = sock_i_uid(sk);
14925030a7fSGerrit Renker 
150ca065d0cSEric Dumazet 	sk_for_each(sk2, &hslot->head) {
151f24d43c0SEric Dumazet 		if (net_eq(sock_net(sk2), net) &&
152f24d43c0SEric Dumazet 		    sk2 != sk &&
153d4cada4aSEric Dumazet 		    (bitmap || udp_sk(sk2)->udp_port_hash == num) &&
154f24d43c0SEric Dumazet 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
1559d4fb27dSJoe Perches 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
1569d4fb27dSJoe Perches 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
157fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, true)) {
158df560056SEric Garver 			if (sk2->sk_reuseport && sk->sk_reuseport &&
159df560056SEric Garver 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
160df560056SEric Garver 			    uid_eq(uid, sock_i_uid(sk2))) {
161df560056SEric Garver 				if (!bitmap)
162df560056SEric Garver 					return 0;
163df560056SEric Garver 			} else {
1644243cdc2SJoe Perches 				if (!bitmap)
165fc038410SDavid S. Miller 					return 1;
166df560056SEric Garver 				__set_bit(udp_sk(sk2)->udp_port_hash >> log,
167df560056SEric Garver 					  bitmap);
168df560056SEric Garver 			}
1694243cdc2SJoe Perches 		}
17098322f22SEric Dumazet 	}
17125030a7fSGerrit Renker 	return 0;
17225030a7fSGerrit Renker }
17325030a7fSGerrit Renker 
17430fff923SEric Dumazet /*
17530fff923SEric Dumazet  * Note: we still hold spinlock of primary hash chain, so no other writer
17630fff923SEric Dumazet  * can insert/delete a socket with local_port == num
17730fff923SEric Dumazet  */
udp_lib_lport_inuse2(struct net * net,__u16 num,struct udp_hslot * hslot2,struct sock * sk)17830fff923SEric Dumazet static int udp_lib_lport_inuse2(struct net *net, __u16 num,
17930fff923SEric Dumazet 				struct udp_hslot *hslot2,
180fe38d2a1SJosef Bacik 				struct sock *sk)
18130fff923SEric Dumazet {
18230fff923SEric Dumazet 	struct sock *sk2;
183ba418fa3STom Herbert 	kuid_t uid = sock_i_uid(sk);
18430fff923SEric Dumazet 	int res = 0;
18530fff923SEric Dumazet 
18630fff923SEric Dumazet 	spin_lock(&hslot2->lock);
187ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry(sk2, &hslot2->head) {
18830fff923SEric Dumazet 		if (net_eq(sock_net(sk2), net) &&
18930fff923SEric Dumazet 		    sk2 != sk &&
19030fff923SEric Dumazet 		    (udp_sk(sk2)->udp_port_hash == num) &&
19130fff923SEric Dumazet 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
1929d4fb27dSJoe Perches 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
1939d4fb27dSJoe Perches 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
194fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, true)) {
195df560056SEric Garver 			if (sk2->sk_reuseport && sk->sk_reuseport &&
196df560056SEric Garver 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
197df560056SEric Garver 			    uid_eq(uid, sock_i_uid(sk2))) {
198df560056SEric Garver 				res = 0;
199df560056SEric Garver 			} else {
20030fff923SEric Dumazet 				res = 1;
201df560056SEric Garver 			}
20230fff923SEric Dumazet 			break;
20330fff923SEric Dumazet 		}
2044243cdc2SJoe Perches 	}
20530fff923SEric Dumazet 	spin_unlock(&hslot2->lock);
20630fff923SEric Dumazet 	return res;
20730fff923SEric Dumazet }
20830fff923SEric Dumazet 
udp_reuseport_add_sock(struct sock * sk,struct udp_hslot * hslot)209fe38d2a1SJosef Bacik static int udp_reuseport_add_sock(struct sock *sk, struct udp_hslot *hslot)
210e32ea7e7SCraig Gallek {
211e32ea7e7SCraig Gallek 	struct net *net = sock_net(sk);
212e32ea7e7SCraig Gallek 	kuid_t uid = sock_i_uid(sk);
213e32ea7e7SCraig Gallek 	struct sock *sk2;
214e32ea7e7SCraig Gallek 
215ca065d0cSEric Dumazet 	sk_for_each(sk2, &hslot->head) {
216e32ea7e7SCraig Gallek 		if (net_eq(sock_net(sk2), net) &&
217e32ea7e7SCraig Gallek 		    sk2 != sk &&
218e32ea7e7SCraig Gallek 		    sk2->sk_family == sk->sk_family &&
219e32ea7e7SCraig Gallek 		    ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
220e32ea7e7SCraig Gallek 		    (udp_sk(sk2)->udp_port_hash == udp_sk(sk)->udp_port_hash) &&
221e32ea7e7SCraig Gallek 		    (sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
222e32ea7e7SCraig Gallek 		    sk2->sk_reuseport && uid_eq(uid, sock_i_uid(sk2)) &&
223fe38d2a1SJosef Bacik 		    inet_rcv_saddr_equal(sk, sk2, false)) {
2242dbb9b9eSMartin KaFai Lau 			return reuseport_add_sock(sk, sk2,
2252dbb9b9eSMartin KaFai Lau 						  inet_rcv_saddr_any(sk));
226e32ea7e7SCraig Gallek 		}
227e32ea7e7SCraig Gallek 	}
228e32ea7e7SCraig Gallek 
2292dbb9b9eSMartin KaFai Lau 	return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
230e32ea7e7SCraig Gallek }
231e32ea7e7SCraig Gallek 
23225030a7fSGerrit Renker /**
2336ba5a3c5SPavel Emelyanov  *  udp_lib_get_port  -  UDP/-Lite port lookup for IPv4 and IPv6
23425030a7fSGerrit Renker  *
23525030a7fSGerrit Renker  *  @sk:          socket struct in question
23625030a7fSGerrit Renker  *  @snum:        port number to look up
23725985edcSLucas De Marchi  *  @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
23830fff923SEric Dumazet  *                   with NULL address
23925030a7fSGerrit Renker  */
udp_lib_get_port(struct sock * sk,unsigned short snum,unsigned int hash2_nulladdr)2406ba5a3c5SPavel Emelyanov int udp_lib_get_port(struct sock *sk, unsigned short snum,
24130fff923SEric Dumazet 		     unsigned int hash2_nulladdr)
2421da177e4SLinus Torvalds {
24367fb4330SKuniyuki Iwashima 	struct udp_table *udptable = udp_get_table_prot(sk);
244919dfa0bSKuniyuki Iwashima 	struct udp_hslot *hslot, *hslot2;
2453b1e0a65SYOSHIFUJI Hideaki 	struct net *net = sock_net(sk);
2467a7160edSKuniyuki Iwashima 	int error = -EADDRINUSE;
2471da177e4SLinus Torvalds 
24832c1da70SStephen Hemminger 	if (!snum) {
249919dfa0bSKuniyuki Iwashima 		DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
250919dfa0bSKuniyuki Iwashima 		unsigned short first, last;
2519088c560SEric Dumazet 		int low, high, remaining;
25295c96174SEric Dumazet 		unsigned int rand;
2531da177e4SLinus Torvalds 
25491d0b78cSJakub Sitnicki 		inet_sk_get_local_port_range(sk, &low, &high);
255a25de534SAnton Arapov 		remaining = (high - low) + 1;
256227b60f5SStephen Hemminger 
257a251c17aSJason A. Donenfeld 		rand = get_random_u32();
2588fc54f68SDaniel Borkmann 		first = reciprocal_scale(rand, remaining) + low;
25998322f22SEric Dumazet 		/*
26098322f22SEric Dumazet 		 * force rand to be an odd multiple of UDP_HTABLE_SIZE
26198322f22SEric Dumazet 		 */
262f86dcc5aSEric Dumazet 		rand = (rand | 1) * (udptable->mask + 1);
2635781b235SEric Dumazet 		last = first + udptable->mask + 1;
2645781b235SEric Dumazet 		do {
265f86dcc5aSEric Dumazet 			hslot = udp_hashslot(udptable, net, first);
26698322f22SEric Dumazet 			bitmap_zero(bitmap, PORTS_PER_CHAIN);
267645ca708SEric Dumazet 			spin_lock_bh(&hslot->lock);
26898322f22SEric Dumazet 			udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
269fe38d2a1SJosef Bacik 					    udptable->log);
27098322f22SEric Dumazet 
27198322f22SEric Dumazet 			snum = first;
27298322f22SEric Dumazet 			/*
27398322f22SEric Dumazet 			 * Iterate on all possible values of snum for this hash.
27498322f22SEric Dumazet 			 * Using steps of an odd multiple of UDP_HTABLE_SIZE
27598322f22SEric Dumazet 			 * give us randomization and full range coverage.
27698322f22SEric Dumazet 			 */
2779088c560SEric Dumazet 			do {
27898322f22SEric Dumazet 				if (low <= snum && snum <= high &&
279e3826f1eSAmerigo Wang 				    !test_bit(snum >> udptable->log, bitmap) &&
280122ff243SWANG Cong 				    !inet_is_local_reserved_port(net, snum))
28198322f22SEric Dumazet 					goto found;
28298322f22SEric Dumazet 				snum += rand;
28398322f22SEric Dumazet 			} while (snum != first);
28498322f22SEric Dumazet 			spin_unlock_bh(&hslot->lock);
285df560056SEric Garver 			cond_resched();
2865781b235SEric Dumazet 		} while (++first != last);
28798322f22SEric Dumazet 		goto fail;
288645ca708SEric Dumazet 	} else {
289f86dcc5aSEric Dumazet 		hslot = udp_hashslot(udptable, net, snum);
290645ca708SEric Dumazet 		spin_lock_bh(&hslot->lock);
29130fff923SEric Dumazet 		if (hslot->count > 10) {
29230fff923SEric Dumazet 			int exist;
29330fff923SEric Dumazet 			unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
29430fff923SEric Dumazet 
29530fff923SEric Dumazet 			slot2          &= udptable->mask;
29630fff923SEric Dumazet 			hash2_nulladdr &= udptable->mask;
29730fff923SEric Dumazet 
29830fff923SEric Dumazet 			hslot2 = udp_hashslot2(udptable, slot2);
29930fff923SEric Dumazet 			if (hslot->count < hslot2->count)
30030fff923SEric Dumazet 				goto scan_primary_hash;
30130fff923SEric Dumazet 
302fe38d2a1SJosef Bacik 			exist = udp_lib_lport_inuse2(net, snum, hslot2, sk);
30330fff923SEric Dumazet 			if (!exist && (hash2_nulladdr != slot2)) {
30430fff923SEric Dumazet 				hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
30530fff923SEric Dumazet 				exist = udp_lib_lport_inuse2(net, snum, hslot2,
306fe38d2a1SJosef Bacik 							     sk);
30730fff923SEric Dumazet 			}
30830fff923SEric Dumazet 			if (exist)
30930fff923SEric Dumazet 				goto fail_unlock;
31030fff923SEric Dumazet 			else
31130fff923SEric Dumazet 				goto found;
31230fff923SEric Dumazet 		}
31330fff923SEric Dumazet scan_primary_hash:
314fe38d2a1SJosef Bacik 		if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, 0))
315645ca708SEric Dumazet 			goto fail_unlock;
316645ca708SEric Dumazet 	}
31798322f22SEric Dumazet found:
318c720c7e8SEric Dumazet 	inet_sk(sk)->inet_num = snum;
319d4cada4aSEric Dumazet 	udp_sk(sk)->udp_port_hash = snum;
320d4cada4aSEric Dumazet 	udp_sk(sk)->udp_portaddr_hash ^= snum;
3211da177e4SLinus Torvalds 	if (sk_unhashed(sk)) {
322e32ea7e7SCraig Gallek 		if (sk->sk_reuseport &&
323fe38d2a1SJosef Bacik 		    udp_reuseport_add_sock(sk, hslot)) {
324e32ea7e7SCraig Gallek 			inet_sk(sk)->inet_num = 0;
325e32ea7e7SCraig Gallek 			udp_sk(sk)->udp_port_hash = 0;
326e32ea7e7SCraig Gallek 			udp_sk(sk)->udp_portaddr_hash ^= snum;
327e32ea7e7SCraig Gallek 			goto fail_unlock;
328e32ea7e7SCraig Gallek 		}
329e32ea7e7SCraig Gallek 
3305c0b485aSKuniyuki Iwashima 		sock_set_flag(sk, SOCK_RCU_FREE);
3315c0b485aSKuniyuki Iwashima 
332ca065d0cSEric Dumazet 		sk_add_node_rcu(sk, &hslot->head);
333fdcc8aa9SEric Dumazet 		hslot->count++;
334c29a0bc4SPavel Emelyanov 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
335512615b6SEric Dumazet 
336512615b6SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
337512615b6SEric Dumazet 		spin_lock(&hslot2->lock);
338d894ba18SCraig Gallek 		if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
339d894ba18SCraig Gallek 		    sk->sk_family == AF_INET6)
3401602f49bSDavid S. Miller 			hlist_add_tail_rcu(&udp_sk(sk)->udp_portaddr_node,
341d894ba18SCraig Gallek 					   &hslot2->head);
342d894ba18SCraig Gallek 		else
343ca065d0cSEric Dumazet 			hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
344512615b6SEric Dumazet 					   &hslot2->head);
345512615b6SEric Dumazet 		hslot2->count++;
346512615b6SEric Dumazet 		spin_unlock(&hslot2->lock);
3471da177e4SLinus Torvalds 	}
3485c0b485aSKuniyuki Iwashima 
34925030a7fSGerrit Renker 	error = 0;
350645ca708SEric Dumazet fail_unlock:
351645ca708SEric Dumazet 	spin_unlock_bh(&hslot->lock);
3521da177e4SLinus Torvalds fail:
35325030a7fSGerrit Renker 	return error;
3541da177e4SLinus Torvalds }
355c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_get_port);
3561da177e4SLinus Torvalds 
udp_v4_get_port(struct sock * sk,unsigned short snum)3576ba5a3c5SPavel Emelyanov int udp_v4_get_port(struct sock *sk, unsigned short snum)
358db8dac20SDavid S. Miller {
35930fff923SEric Dumazet 	unsigned int hash2_nulladdr =
360f0b1e64cSMartin KaFai Lau 		ipv4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
36130fff923SEric Dumazet 	unsigned int hash2_partial =
362f0b1e64cSMartin KaFai Lau 		ipv4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
36330fff923SEric Dumazet 
364d4cada4aSEric Dumazet 	/* precompute partial secondary hash */
36530fff923SEric Dumazet 	udp_sk(sk)->udp_portaddr_hash = hash2_partial;
366fe38d2a1SJosef Bacik 	return udp_lib_get_port(sk, snum, hash2_nulladdr);
367db8dac20SDavid S. Miller }
368db8dac20SDavid S. Miller 
compute_score(struct sock * sk,const struct net * net,__be32 saddr,__be16 sport,__be32 daddr,unsigned short hnum,int dif,int sdif)369b9abcbb1SEric Dumazet static int compute_score(struct sock *sk, const struct net *net,
370d1e37288SSu, Xuemin 			 __be32 saddr, __be16 sport,
371fb74c277SDavid Ahern 			 __be32 daddr, unsigned short hnum,
37273545373STim Beale 			 int dif, int sdif)
373645ca708SEric Dumazet {
37460c04aecSJoe Perches 	int score;
37560c04aecSJoe Perches 	struct inet_sock *inet;
3766da5b0f0SMike Manning 	bool dev_match;
377645ca708SEric Dumazet 
37860c04aecSJoe Perches 	if (!net_eq(sock_net(sk), net) ||
37960c04aecSJoe Perches 	    udp_sk(sk)->udp_port_hash != hnum ||
38060c04aecSJoe Perches 	    ipv6_only_sock(sk))
38160c04aecSJoe Perches 		return -1;
382645ca708SEric Dumazet 
3834cdeeee9SPeter Oskolkov 	if (sk->sk_rcv_saddr != daddr)
384645ca708SEric Dumazet 		return -1;
38560c04aecSJoe Perches 
3864cdeeee9SPeter Oskolkov 	score = (sk->sk_family == PF_INET) ? 2 : 1;
3874cdeeee9SPeter Oskolkov 
3884cdeeee9SPeter Oskolkov 	inet = inet_sk(sk);
389c720c7e8SEric Dumazet 	if (inet->inet_daddr) {
390c720c7e8SEric Dumazet 		if (inet->inet_daddr != saddr)
391645ca708SEric Dumazet 			return -1;
392ba418fa3STom Herbert 		score += 4;
393645ca708SEric Dumazet 	}
39460c04aecSJoe Perches 
395c720c7e8SEric Dumazet 	if (inet->inet_dport) {
396c720c7e8SEric Dumazet 		if (inet->inet_dport != sport)
397645ca708SEric Dumazet 			return -1;
398ba418fa3STom Herbert 		score += 4;
399645ca708SEric Dumazet 	}
40060c04aecSJoe Perches 
4016da5b0f0SMike Manning 	dev_match = udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if,
4026da5b0f0SMike Manning 					dif, sdif);
40369678bcdSPaolo Abeni 	if (!dev_match)
404645ca708SEric Dumazet 		return -1;
4058d6c414cSMike Manning 	if (sk->sk_bound_dev_if)
406ba418fa3STom Herbert 		score += 4;
407fb74c277SDavid Ahern 
4087170a977SEric Dumazet 	if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
40970da268bSEric Dumazet 		score++;
410645ca708SEric Dumazet 	return score;
411645ca708SEric Dumazet }
412645ca708SEric Dumazet 
4130f495f76SLorenz Bauer INDIRECT_CALLABLE_SCOPE
udp_ehashfn(const struct net * net,const __be32 laddr,const __u16 lport,const __be32 faddr,const __be16 fport)4140f495f76SLorenz Bauer u32 udp_ehashfn(const struct net *net, const __be32 laddr, const __u16 lport,
4150f495f76SLorenz Bauer 		const __be32 faddr, const __be16 fport)
41665cd8033SHannes Frederic Sowa {
4171bbdceefSHannes Frederic Sowa 	net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret));
4181bbdceefSHannes Frederic Sowa 
41965cd8033SHannes Frederic Sowa 	return __inet_ehashfn(laddr, lport, faddr, fport,
4201bbdceefSHannes Frederic Sowa 			      udp_ehash_secret + net_hash_mix(net));
42165cd8033SHannes Frederic Sowa }
42265cd8033SHannes Frederic Sowa 
423d1e37288SSu, Xuemin /* called with rcu_read_lock() */
udp4_lib_lookup2(const struct net * net,__be32 saddr,__be16 sport,__be32 daddr,unsigned int hnum,int dif,int sdif,struct udp_hslot * hslot2,struct sk_buff * skb)424b9abcbb1SEric Dumazet static struct sock *udp4_lib_lookup2(const struct net *net,
4255051ebd2SEric Dumazet 				     __be32 saddr, __be16 sport,
426fb74c277SDavid Ahern 				     __be32 daddr, unsigned int hnum,
42773545373STim Beale 				     int dif, int sdif,
428d1e37288SSu, Xuemin 				     struct udp_hslot *hslot2,
4291134158bSCraig Gallek 				     struct sk_buff *skb)
4305051ebd2SEric Dumazet {
4315051ebd2SEric Dumazet 	struct sock *sk, *result;
432e94a62f5SPaolo Abeni 	int score, badness;
43350aee97dSGabriel Krisman Bertazi 	bool need_rescore;
4345051ebd2SEric Dumazet 
4355051ebd2SEric Dumazet 	result = NULL;
436ba418fa3STom Herbert 	badness = 0;
437ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
43850aee97dSGabriel Krisman Bertazi 		need_rescore = false;
43950aee97dSGabriel Krisman Bertazi rescore:
44050aee97dSGabriel Krisman Bertazi 		score = compute_score(need_rescore ? result : sk, net, saddr,
44150aee97dSGabriel Krisman Bertazi 				      sport, daddr, hnum, dif, sdif);
4425051ebd2SEric Dumazet 		if (score > badness) {
443ca065d0cSEric Dumazet 			badness = score;
4440f495f76SLorenz Bauer 
44550aee97dSGabriel Krisman Bertazi 			if (need_rescore)
44650aee97dSGabriel Krisman Bertazi 				continue;
44750aee97dSGabriel Krisman Bertazi 
4480f495f76SLorenz Bauer 			if (sk->sk_state == TCP_ESTABLISHED) {
4490f495f76SLorenz Bauer 				result = sk;
4500f495f76SLorenz Bauer 				continue;
4510f495f76SLorenz Bauer 			}
4520f495f76SLorenz Bauer 
4530f495f76SLorenz Bauer 			result = inet_lookup_reuseport(net, sk, skb, sizeof(struct udphdr),
4540f495f76SLorenz Bauer 						       saddr, sport, daddr, hnum, udp_ehashfn);
455f0ea27e7SLorenz Bauer 			if (!result) {
456f0ea27e7SLorenz Bauer 				result = sk;
457f0ea27e7SLorenz Bauer 				continue;
458f0ea27e7SLorenz Bauer 			}
459f0ea27e7SLorenz Bauer 
460e32ea7e7SCraig Gallek 			/* Fall back to scoring if group has connections */
461f0ea27e7SLorenz Bauer 			if (!reuseport_has_conns(sk))
462ba418fa3STom Herbert 				return result;
463ba418fa3STom Herbert 
464f0ea27e7SLorenz Bauer 			/* Reuseport logic returned an error, keep original score. */
465f0ea27e7SLorenz Bauer 			if (IS_ERR(result))
466f0ea27e7SLorenz Bauer 				continue;
467f0ea27e7SLorenz Bauer 
46850aee97dSGabriel Krisman Bertazi 			/* compute_score is too long of a function to be
46950aee97dSGabriel Krisman Bertazi 			 * inlined, and calling it again here yields
47050aee97dSGabriel Krisman Bertazi 			 * measureable overhead for some
47150aee97dSGabriel Krisman Bertazi 			 * workloads. Work around it by jumping
47250aee97dSGabriel Krisman Bertazi 			 * backwards to rescore 'result'.
47350aee97dSGabriel Krisman Bertazi 			 */
47450aee97dSGabriel Krisman Bertazi 			need_rescore = true;
47550aee97dSGabriel Krisman Bertazi 			goto rescore;
4765051ebd2SEric Dumazet 		}
4775051ebd2SEric Dumazet 	}
4785051ebd2SEric Dumazet 	return result;
4795051ebd2SEric Dumazet }
4805051ebd2SEric Dumazet 
481db8dac20SDavid S. Miller /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
482db8dac20SDavid S. Miller  * harder than this. -DaveM
483db8dac20SDavid S. Miller  */
__udp4_lib_lookup(const struct net * net,__be32 saddr,__be16 sport,__be32 daddr,__be16 dport,int dif,int sdif,struct udp_table * udptable,struct sk_buff * skb)484b9abcbb1SEric Dumazet struct sock *__udp4_lib_lookup(const struct net *net, __be32 saddr,
485fb74c277SDavid Ahern 		__be16 sport, __be32 daddr, __be16 dport, int dif,
486fb74c277SDavid Ahern 		int sdif, struct udp_table *udptable, struct sk_buff *skb)
487db8dac20SDavid S. Miller {
488db8dac20SDavid S. Miller 	unsigned short hnum = ntohs(dport);
4894cdeeee9SPeter Oskolkov 	unsigned int hash2, slot2;
4904cdeeee9SPeter Oskolkov 	struct udp_hslot *hslot2;
49172f7e944SJakub Sitnicki 	struct sock *result, *sk;
492db8dac20SDavid S. Miller 
493f0b1e64cSMartin KaFai Lau 	hash2 = ipv4_portaddr_hash(net, daddr, hnum);
4945051ebd2SEric Dumazet 	slot2 = hash2 & udptable->mask;
4955051ebd2SEric Dumazet 	hslot2 = &udptable->hash2[slot2];
4965051ebd2SEric Dumazet 
49772f7e944SJakub Sitnicki 	/* Lookup connected or non-wildcard socket */
4985051ebd2SEric Dumazet 	result = udp4_lib_lookup2(net, saddr, sport,
499fb74c277SDavid Ahern 				  daddr, hnum, dif, sdif,
50073545373STim Beale 				  hslot2, skb);
50172f7e944SJakub Sitnicki 	if (!IS_ERR_OR_NULL(result) && result->sk_state == TCP_ESTABLISHED)
50272f7e944SJakub Sitnicki 		goto done;
50372f7e944SJakub Sitnicki 
50472f7e944SJakub Sitnicki 	/* Lookup redirect from BPF */
5056c886db2SLorenz Bauer 	if (static_branch_unlikely(&bpf_sk_lookup_enabled) &&
5066c886db2SLorenz Bauer 	    udptable == net->ipv4.udp_table) {
5076c886db2SLorenz Bauer 		sk = inet_lookup_run_sk_lookup(net, IPPROTO_UDP, skb, sizeof(struct udphdr),
5086c886db2SLorenz Bauer 					       saddr, sport, daddr, hnum, dif,
5096c886db2SLorenz Bauer 					       udp_ehashfn);
51072f7e944SJakub Sitnicki 		if (sk) {
51172f7e944SJakub Sitnicki 			result = sk;
51272f7e944SJakub Sitnicki 			goto done;
51372f7e944SJakub Sitnicki 		}
51472f7e944SJakub Sitnicki 	}
51572f7e944SJakub Sitnicki 
51672f7e944SJakub Sitnicki 	/* Got non-wildcard socket or error on first lookup */
51772f7e944SJakub Sitnicki 	if (result)
51872f7e944SJakub Sitnicki 		goto done;
51972f7e944SJakub Sitnicki 
52072f7e944SJakub Sitnicki 	/* Lookup wildcard sockets */
521f0b1e64cSMartin KaFai Lau 	hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
5225051ebd2SEric Dumazet 	slot2 = hash2 & udptable->mask;
5235051ebd2SEric Dumazet 	hslot2 = &udptable->hash2[slot2];
5245051ebd2SEric Dumazet 
5251223c67cSJorge Boncompte [DTI2] 	result = udp4_lib_lookup2(net, saddr, sport,
5264cdeeee9SPeter Oskolkov 				  htonl(INADDR_ANY), hnum, dif, sdif,
52773545373STim Beale 				  hslot2, skb);
52872f7e944SJakub Sitnicki done:
52988e235b8SEnrico Weigelt 	if (IS_ERR(result))
5308217ca65SMartin KaFai Lau 		return NULL;
5315051ebd2SEric Dumazet 	return result;
5325051ebd2SEric Dumazet }
533fce82338SPavel Emelyanov EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
534db8dac20SDavid S. Miller 
__udp4_lib_lookup_skb(struct sk_buff * skb,__be16 sport,__be16 dport,struct udp_table * udptable)535607c4aafSKOVACS Krisztian static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
536607c4aafSKOVACS Krisztian 						 __be16 sport, __be16 dport,
537645ca708SEric Dumazet 						 struct udp_table *udptable)
538607c4aafSKOVACS Krisztian {
539607c4aafSKOVACS Krisztian 	const struct iphdr *iph = ip_hdr(skb);
540607c4aafSKOVACS Krisztian 
541ed7cbbceSAlexander Duyck 	return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
542607c4aafSKOVACS Krisztian 				 iph->daddr, dport, inet_iif(skb),
543fb74c277SDavid Ahern 				 inet_sdif(skb), udptable, skb);
544607c4aafSKOVACS Krisztian }
545607c4aafSKOVACS Krisztian 
udp4_lib_lookup_skb(const struct sk_buff * skb,__be16 sport,__be16 dport)5467b58e63eSEric Dumazet struct sock *udp4_lib_lookup_skb(const struct sk_buff *skb,
54763058308STom Herbert 				 __be16 sport, __be16 dport)
54863058308STom Herbert {
5495ef31ea5SRichard Gobert 	const u16 offset = NAPI_GRO_CB(skb)->network_offsets[skb->encapsulation];
5505ef31ea5SRichard Gobert 	const struct iphdr *iph = (struct iphdr *)(skb->data + offset);
551ba6aac15SKuniyuki Iwashima 	struct net *net = dev_net(skb->dev);
5527938cd15SRichard Gobert 	int iif, sdif;
5537938cd15SRichard Gobert 
5547938cd15SRichard Gobert 	inet_get_iif_sdif(skb, &iif, &sdif);
555257a525fSMartin KaFai Lau 
556ba6aac15SKuniyuki Iwashima 	return __udp4_lib_lookup(net, iph->saddr, sport,
5577938cd15SRichard Gobert 				 iph->daddr, dport, iif,
5587938cd15SRichard Gobert 				 sdif, net->ipv4.udp_table, NULL);
55963058308STom Herbert }
56063058308STom Herbert 
561ca065d0cSEric Dumazet /* Must be called under rcu_read_lock().
562ca065d0cSEric Dumazet  * Does increment socket refcount.
563ca065d0cSEric Dumazet  */
5646e86000cSArnd Bergmann #if IS_ENABLED(CONFIG_NF_TPROXY_IPV4) || IS_ENABLED(CONFIG_NF_SOCKET_IPV4)
udp4_lib_lookup(const struct net * net,__be32 saddr,__be16 sport,__be32 daddr,__be16 dport,int dif)565b9abcbb1SEric Dumazet struct sock *udp4_lib_lookup(const struct net *net, __be32 saddr, __be16 sport,
566bcd41303SKOVACS Krisztian 			     __be32 daddr, __be16 dport, int dif)
567bcd41303SKOVACS Krisztian {
568ca065d0cSEric Dumazet 	struct sock *sk;
569ca065d0cSEric Dumazet 
570ca065d0cSEric Dumazet 	sk = __udp4_lib_lookup(net, saddr, sport, daddr, dport,
571ba6aac15SKuniyuki Iwashima 			       dif, 0, net->ipv4.udp_table, NULL);
57241c6d650SReshetova, Elena 	if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
573ca065d0cSEric Dumazet 		sk = NULL;
574ca065d0cSEric Dumazet 	return sk;
575bcd41303SKOVACS Krisztian }
576bcd41303SKOVACS Krisztian EXPORT_SYMBOL_GPL(udp4_lib_lookup);
577ca065d0cSEric Dumazet #endif
578bcd41303SKOVACS Krisztian 
__udp_is_mcast_sock(struct net * net,const struct sock * sk,__be16 loc_port,__be32 loc_addr,__be16 rmt_port,__be32 rmt_addr,int dif,int sdif,unsigned short hnum)579a0a989d3SEric Dumazet static inline bool __udp_is_mcast_sock(struct net *net, const struct sock *sk,
580421b3885SShawn Bohrer 				       __be16 loc_port, __be32 loc_addr,
581421b3885SShawn Bohrer 				       __be16 rmt_port, __be32 rmt_addr,
582fb74c277SDavid Ahern 				       int dif, int sdif, unsigned short hnum)
583421b3885SShawn Bohrer {
584a0a989d3SEric Dumazet 	const struct inet_sock *inet = inet_sk(sk);
585421b3885SShawn Bohrer 
586421b3885SShawn Bohrer 	if (!net_eq(sock_net(sk), net) ||
587421b3885SShawn Bohrer 	    udp_sk(sk)->udp_port_hash != hnum ||
588421b3885SShawn Bohrer 	    (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
589421b3885SShawn Bohrer 	    (inet->inet_dport != rmt_port && inet->inet_dport) ||
590421b3885SShawn Bohrer 	    (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) ||
591421b3885SShawn Bohrer 	    ipv6_only_sock(sk) ||
59282ba25c6STim Beale 	    !udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif))
593421b3885SShawn Bohrer 		return false;
59460d9b031SDavid Ahern 	if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif, sdif))
595421b3885SShawn Bohrer 		return false;
596421b3885SShawn Bohrer 	return true;
597421b3885SShawn Bohrer }
598421b3885SShawn Bohrer 
599a36e185eSStefano Brivio DEFINE_STATIC_KEY_FALSE(udp_encap_needed_key);
6003d010c80SAntoine Tenart EXPORT_SYMBOL(udp_encap_needed_key);
6013d010c80SAntoine Tenart 
6023d010c80SAntoine Tenart #if IS_ENABLED(CONFIG_IPV6)
6033d010c80SAntoine Tenart DEFINE_STATIC_KEY_FALSE(udpv6_encap_needed_key);
6043d010c80SAntoine Tenart EXPORT_SYMBOL(udpv6_encap_needed_key);
6053d010c80SAntoine Tenart #endif
6063d010c80SAntoine Tenart 
udp_encap_enable(void)607a36e185eSStefano Brivio void udp_encap_enable(void)
608a36e185eSStefano Brivio {
6099c480601SPaolo Abeni 	static_branch_inc(&udp_encap_needed_key);
610a36e185eSStefano Brivio }
611a36e185eSStefano Brivio EXPORT_SYMBOL(udp_encap_enable);
612a36e185eSStefano Brivio 
udp_encap_disable(void)613a4a600ddSXin Long void udp_encap_disable(void)
614a4a600ddSXin Long {
615a4a600ddSXin Long 	static_branch_dec(&udp_encap_needed_key);
616a4a600ddSXin Long }
617a4a600ddSXin Long EXPORT_SYMBOL(udp_encap_disable);
618a4a600ddSXin Long 
619e7cc0824SStefano Brivio /* Handler for tunnels with arbitrary destination ports: no socket lookup, go
620e7cc0824SStefano Brivio  * through error handlers in encapsulations looking for a match.
621e7cc0824SStefano Brivio  */
__udp4_lib_err_encap_no_sk(struct sk_buff * skb,u32 info)622e7cc0824SStefano Brivio static int __udp4_lib_err_encap_no_sk(struct sk_buff *skb, u32 info)
623e7cc0824SStefano Brivio {
624e7cc0824SStefano Brivio 	int i;
625e7cc0824SStefano Brivio 
626e7cc0824SStefano Brivio 	for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) {
627e7cc0824SStefano Brivio 		int (*handler)(struct sk_buff *skb, u32 info);
62892b95364SPaolo Abeni 		const struct ip_tunnel_encap_ops *encap;
629e7cc0824SStefano Brivio 
63092b95364SPaolo Abeni 		encap = rcu_dereference(iptun_encaps[i]);
63192b95364SPaolo Abeni 		if (!encap)
632e7cc0824SStefano Brivio 			continue;
63392b95364SPaolo Abeni 		handler = encap->err_handler;
634e7cc0824SStefano Brivio 		if (handler && !handler(skb, info))
635e7cc0824SStefano Brivio 			return 0;
636e7cc0824SStefano Brivio 	}
637e7cc0824SStefano Brivio 
638e7cc0824SStefano Brivio 	return -ENOENT;
639e7cc0824SStefano Brivio }
640e7cc0824SStefano Brivio 
641a36e185eSStefano Brivio /* Try to match ICMP errors to UDP tunnels by looking up a socket without
642a36e185eSStefano Brivio  * reversing source and destination port: this will match tunnels that force the
643a36e185eSStefano Brivio  * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that
644a36e185eSStefano Brivio  * lwtunnels might actually break this assumption by being configured with
645a36e185eSStefano Brivio  * different destination ports on endpoints, in this case we won't be able to
646a36e185eSStefano Brivio  * trace ICMP messages back to them.
647a36e185eSStefano Brivio  *
648e7cc0824SStefano Brivio  * If this doesn't match any socket, probe tunnels with arbitrary destination
649e7cc0824SStefano Brivio  * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port
650e7cc0824SStefano Brivio  * we've sent packets to won't necessarily match the local destination port.
651e7cc0824SStefano Brivio  *
652a36e185eSStefano Brivio  * Then ask the tunnel implementation to match the error against a valid
653a36e185eSStefano Brivio  * association.
654a36e185eSStefano Brivio  *
655e7cc0824SStefano Brivio  * Return an error if we can't find a match, the socket if we need further
656e7cc0824SStefano Brivio  * processing, zero otherwise.
657a36e185eSStefano Brivio  */
__udp4_lib_err_encap(struct net * net,const struct iphdr * iph,struct udphdr * uh,struct udp_table * udptable,struct sock * sk,struct sk_buff * skb,u32 info)658a36e185eSStefano Brivio static struct sock *__udp4_lib_err_encap(struct net *net,
659a36e185eSStefano Brivio 					 const struct iphdr *iph,
660a36e185eSStefano Brivio 					 struct udphdr *uh,
661a36e185eSStefano Brivio 					 struct udp_table *udptable,
6629bfce73cSVadim Fedorenko 					 struct sock *sk,
663e7cc0824SStefano Brivio 					 struct sk_buff *skb, u32 info)
664a36e185eSStefano Brivio {
6659bfce73cSVadim Fedorenko 	int (*lookup)(struct sock *sk, struct sk_buff *skb);
666a36e185eSStefano Brivio 	int network_offset, transport_offset;
6679bfce73cSVadim Fedorenko 	struct udp_sock *up;
668a36e185eSStefano Brivio 
669a36e185eSStefano Brivio 	network_offset = skb_network_offset(skb);
670a36e185eSStefano Brivio 	transport_offset = skb_transport_offset(skb);
671a36e185eSStefano Brivio 
672a36e185eSStefano Brivio 	/* Network header needs to point to the outer IPv4 header inside ICMP */
673a36e185eSStefano Brivio 	skb_reset_network_header(skb);
674a36e185eSStefano Brivio 
675a36e185eSStefano Brivio 	/* Transport header needs to point to the UDP header */
676a36e185eSStefano Brivio 	skb_set_transport_header(skb, iph->ihl << 2);
677a36e185eSStefano Brivio 
6789bfce73cSVadim Fedorenko 	if (sk) {
6799bfce73cSVadim Fedorenko 		up = udp_sk(sk);
6809bfce73cSVadim Fedorenko 
6819bfce73cSVadim Fedorenko 		lookup = READ_ONCE(up->encap_err_lookup);
6829bfce73cSVadim Fedorenko 		if (lookup && lookup(sk, skb))
6839bfce73cSVadim Fedorenko 			sk = NULL;
6849bfce73cSVadim Fedorenko 
6859bfce73cSVadim Fedorenko 		goto out;
6869bfce73cSVadim Fedorenko 	}
6879bfce73cSVadim Fedorenko 
688e7cc0824SStefano Brivio 	sk = __udp4_lib_lookup(net, iph->daddr, uh->source,
689e7cc0824SStefano Brivio 			       iph->saddr, uh->dest, skb->dev->ifindex, 0,
690e7cc0824SStefano Brivio 			       udptable, NULL);
691e7cc0824SStefano Brivio 	if (sk) {
6929bfce73cSVadim Fedorenko 		up = udp_sk(sk);
693e7cc0824SStefano Brivio 
694a36e185eSStefano Brivio 		lookup = READ_ONCE(up->encap_err_lookup);
695a36e185eSStefano Brivio 		if (!lookup || lookup(sk, skb))
696a36e185eSStefano Brivio 			sk = NULL;
697e7cc0824SStefano Brivio 	}
698e7cc0824SStefano Brivio 
6999bfce73cSVadim Fedorenko out:
700e7cc0824SStefano Brivio 	if (!sk)
701e7cc0824SStefano Brivio 		sk = ERR_PTR(__udp4_lib_err_encap_no_sk(skb, info));
702a36e185eSStefano Brivio 
703a36e185eSStefano Brivio 	skb_set_transport_header(skb, transport_offset);
704a36e185eSStefano Brivio 	skb_set_network_header(skb, network_offset);
705a36e185eSStefano Brivio 
706a36e185eSStefano Brivio 	return sk;
707a36e185eSStefano Brivio }
708a36e185eSStefano Brivio 
709db8dac20SDavid S. Miller /*
710db8dac20SDavid S. Miller  * This routine is called by the ICMP module when it gets some
711db8dac20SDavid S. Miller  * sort of error condition.  If err < 0 then the socket should
712db8dac20SDavid S. Miller  * be closed and the error returned to the user.  If err > 0
713db8dac20SDavid S. Miller  * it's just the icmp type << 8 | icmp code.
714db8dac20SDavid S. Miller  * Header points to the ip header of the error packet. We move
715db8dac20SDavid S. Miller  * on past this. Then (as it used to claim before adjustment)
716db8dac20SDavid S. Miller  * header points to the first 8 bytes of the udp header.  We need
717db8dac20SDavid S. Miller  * to find the appropriate port.
718db8dac20SDavid S. Miller  */
719db8dac20SDavid S. Miller 
__udp4_lib_err(struct sk_buff * skb,u32 info,struct udp_table * udptable)72032bbd879SStefano Brivio int __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
721db8dac20SDavid S. Miller {
722db8dac20SDavid S. Miller 	struct inet_sock *inet;
723b71d1d42SEric Dumazet 	const struct iphdr *iph = (const struct iphdr *)skb->data;
724db8dac20SDavid S. Miller 	struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
725db8dac20SDavid S. Miller 	const int type = icmp_hdr(skb)->type;
726db8dac20SDavid S. Miller 	const int code = icmp_hdr(skb)->code;
727a36e185eSStefano Brivio 	bool tunnel = false;
728db8dac20SDavid S. Miller 	struct sock *sk;
729db8dac20SDavid S. Miller 	int harderr;
730db8dac20SDavid S. Miller 	int err;
731fd54d716SPavel Emelyanov 	struct net *net = dev_net(skb->dev);
732db8dac20SDavid S. Miller 
733fd54d716SPavel Emelyanov 	sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
734f64bf6b8SMike Manning 			       iph->saddr, uh->source, skb->dev->ifindex,
735f64bf6b8SMike Manning 			       inet_sdif(skb), udptable, NULL);
7369bfce73cSVadim Fedorenko 
73770a36f57SEric Dumazet 	if (!sk || READ_ONCE(udp_sk(sk)->encap_type)) {
738a36e185eSStefano Brivio 		/* No socket for error: try tunnels before discarding */
739e7cc0824SStefano Brivio 		if (static_branch_unlikely(&udp_encap_needed_key)) {
7409bfce73cSVadim Fedorenko 			sk = __udp4_lib_err_encap(net, iph, uh, udptable, sk, skb,
741e7cc0824SStefano Brivio 						  info);
742e7cc0824SStefano Brivio 			if (!sk)
743e7cc0824SStefano Brivio 				return 0;
7449bfce73cSVadim Fedorenko 		} else
7459bfce73cSVadim Fedorenko 			sk = ERR_PTR(-ENOENT);
746e7cc0824SStefano Brivio 
747e7cc0824SStefano Brivio 		if (IS_ERR(sk)) {
748e7cc0824SStefano Brivio 			__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
749e7cc0824SStefano Brivio 			return PTR_ERR(sk);
750e7cc0824SStefano Brivio 		}
751e7cc0824SStefano Brivio 
752a36e185eSStefano Brivio 		tunnel = true;
753db8dac20SDavid S. Miller 	}
754db8dac20SDavid S. Miller 
755db8dac20SDavid S. Miller 	err = 0;
756db8dac20SDavid S. Miller 	harderr = 0;
757db8dac20SDavid S. Miller 	inet = inet_sk(sk);
758db8dac20SDavid S. Miller 
759db8dac20SDavid S. Miller 	switch (type) {
760db8dac20SDavid S. Miller 	default:
761db8dac20SDavid S. Miller 	case ICMP_TIME_EXCEEDED:
762db8dac20SDavid S. Miller 		err = EHOSTUNREACH;
763db8dac20SDavid S. Miller 		break;
764db8dac20SDavid S. Miller 	case ICMP_SOURCE_QUENCH:
765db8dac20SDavid S. Miller 		goto out;
766db8dac20SDavid S. Miller 	case ICMP_PARAMETERPROB:
767db8dac20SDavid S. Miller 		err = EPROTO;
768db8dac20SDavid S. Miller 		harderr = 1;
769db8dac20SDavid S. Miller 		break;
770db8dac20SDavid S. Miller 	case ICMP_DEST_UNREACH:
771db8dac20SDavid S. Miller 		if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
77236393395SDavid S. Miller 			ipv4_sk_update_pmtu(skb, sk, info);
773ceaa7141SEric Dumazet 			if (READ_ONCE(inet->pmtudisc) != IP_PMTUDISC_DONT) {
774db8dac20SDavid S. Miller 				err = EMSGSIZE;
775db8dac20SDavid S. Miller 				harderr = 1;
776db8dac20SDavid S. Miller 				break;
777db8dac20SDavid S. Miller 			}
778db8dac20SDavid S. Miller 			goto out;
779db8dac20SDavid S. Miller 		}
780db8dac20SDavid S. Miller 		err = EHOSTUNREACH;
781db8dac20SDavid S. Miller 		if (code <= NR_ICMP_UNREACH) {
782db8dac20SDavid S. Miller 			harderr = icmp_err_convert[code].fatal;
783db8dac20SDavid S. Miller 			err = icmp_err_convert[code].errno;
784db8dac20SDavid S. Miller 		}
785db8dac20SDavid S. Miller 		break;
78655be7a9cSDavid S. Miller 	case ICMP_REDIRECT:
78755be7a9cSDavid S. Miller 		ipv4_sk_redirect(skb, sk);
7881a462d18SDuan Jiong 		goto out;
789db8dac20SDavid S. Miller 	}
790db8dac20SDavid S. Miller 
791db8dac20SDavid S. Miller 	/*
792db8dac20SDavid S. Miller 	 *      RFC1122: OK.  Passes ICMP errors back to application, as per
793db8dac20SDavid S. Miller 	 *	4.1.3.3.
794db8dac20SDavid S. Miller 	 */
795a36e185eSStefano Brivio 	if (tunnel) {
796a36e185eSStefano Brivio 		/* ...not for tunnels though: we don't have a sending socket */
797ac56a0b4SDavid Howells 		if (udp_sk(sk)->encap_err_rcv)
79842fb06b3SDavid Howells 			udp_sk(sk)->encap_err_rcv(sk, skb, err, uh->dest, info,
79942fb06b3SDavid Howells 						  (u8 *)(uh+1));
800a36e185eSStefano Brivio 		goto out;
801a36e185eSStefano Brivio 	}
8026b5f43eaSEric Dumazet 	if (!inet_test_bit(RECVERR, sk)) {
803db8dac20SDavid S. Miller 		if (!harderr || sk->sk_state != TCP_ESTABLISHED)
804db8dac20SDavid S. Miller 			goto out;
805b1faf566SEric Dumazet 	} else
806db8dac20SDavid S. Miller 		ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
807b1faf566SEric Dumazet 
808db8dac20SDavid S. Miller 	sk->sk_err = err;
809e3ae2365SAlexander Aring 	sk_error_report(sk);
810db8dac20SDavid S. Miller out:
81132bbd879SStefano Brivio 	return 0;
812db8dac20SDavid S. Miller }
813db8dac20SDavid S. Miller 
udp_err(struct sk_buff * skb,u32 info)81432bbd879SStefano Brivio int udp_err(struct sk_buff *skb, u32 info)
815db8dac20SDavid S. Miller {
816ba6aac15SKuniyuki Iwashima 	return __udp4_lib_err(skb, info, dev_net(skb->dev)->ipv4.udp_table);
817db8dac20SDavid S. Miller }
818db8dac20SDavid S. Miller 
819db8dac20SDavid S. Miller /*
820db8dac20SDavid S. Miller  * Throw away all pending data and cancel the corking. Socket is locked.
821db8dac20SDavid S. Miller  */
udp_flush_pending_frames(struct sock * sk)82236d926b9SDenis V. Lunev void udp_flush_pending_frames(struct sock *sk)
823db8dac20SDavid S. Miller {
824db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
825db8dac20SDavid S. Miller 
826db8dac20SDavid S. Miller 	if (up->pending) {
827db8dac20SDavid S. Miller 		up->len = 0;
828482521d8SEric Dumazet 		WRITE_ONCE(up->pending, 0);
829db8dac20SDavid S. Miller 		ip_flush_pending_frames(sk);
830db8dac20SDavid S. Miller 	}
831db8dac20SDavid S. Miller }
83236d926b9SDenis V. Lunev EXPORT_SYMBOL(udp_flush_pending_frames);
833db8dac20SDavid S. Miller 
834db8dac20SDavid S. Miller /**
835f6b9664fSHerbert Xu  * 	udp4_hwcsum  -  handle outgoing HW checksumming
836db8dac20SDavid S. Miller  * 	@skb: 	sk_buff containing the filled-in UDP header
837db8dac20SDavid S. Miller  * 	        (checksum field must be zeroed out)
838f6b9664fSHerbert Xu  *	@src:	source IP address
839f6b9664fSHerbert Xu  *	@dst:	destination IP address
840db8dac20SDavid S. Miller  */
udp4_hwcsum(struct sk_buff * skb,__be32 src,__be32 dst)841c26bf4a5SThomas Graf void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
842db8dac20SDavid S. Miller {
843db8dac20SDavid S. Miller 	struct udphdr *uh = udp_hdr(skb);
844f6b9664fSHerbert Xu 	int offset = skb_transport_offset(skb);
845f6b9664fSHerbert Xu 	int len = skb->len - offset;
846f6b9664fSHerbert Xu 	int hlen = len;
847db8dac20SDavid S. Miller 	__wsum csum = 0;
848db8dac20SDavid S. Miller 
849ebbe495fSWANG Cong 	if (!skb_has_frag_list(skb)) {
850db8dac20SDavid S. Miller 		/*
851db8dac20SDavid S. Miller 		 * Only one fragment on the socket.
852db8dac20SDavid S. Miller 		 */
853db8dac20SDavid S. Miller 		skb->csum_start = skb_transport_header(skb) - skb->head;
854db8dac20SDavid S. Miller 		skb->csum_offset = offsetof(struct udphdr, check);
855f6b9664fSHerbert Xu 		uh->check = ~csum_tcpudp_magic(src, dst, len,
856f6b9664fSHerbert Xu 					       IPPROTO_UDP, 0);
857db8dac20SDavid S. Miller 	} else {
858ebbe495fSWANG Cong 		struct sk_buff *frags;
859ebbe495fSWANG Cong 
860db8dac20SDavid S. Miller 		/*
861db8dac20SDavid S. Miller 		 * HW-checksum won't work as there are two or more
862db8dac20SDavid S. Miller 		 * fragments on the socket so that all csums of sk_buffs
863db8dac20SDavid S. Miller 		 * should be together
864db8dac20SDavid S. Miller 		 */
865ebbe495fSWANG Cong 		skb_walk_frags(skb, frags) {
866f6b9664fSHerbert Xu 			csum = csum_add(csum, frags->csum);
867f6b9664fSHerbert Xu 			hlen -= frags->len;
868ebbe495fSWANG Cong 		}
869db8dac20SDavid S. Miller 
870f6b9664fSHerbert Xu 		csum = skb_checksum(skb, offset, hlen, csum);
871db8dac20SDavid S. Miller 		skb->ip_summed = CHECKSUM_NONE;
872db8dac20SDavid S. Miller 
873db8dac20SDavid S. Miller 		uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
874db8dac20SDavid S. Miller 		if (uh->check == 0)
875db8dac20SDavid S. Miller 			uh->check = CSUM_MANGLED_0;
876db8dac20SDavid S. Miller 	}
877db8dac20SDavid S. Miller }
878c26bf4a5SThomas Graf EXPORT_SYMBOL_GPL(udp4_hwcsum);
879db8dac20SDavid S. Miller 
880af5fcba7STom Herbert /* Function to set UDP checksum for an IPv4 UDP packet. This is intended
881af5fcba7STom Herbert  * for the simple case like when setting the checksum for a UDP tunnel.
882af5fcba7STom Herbert  */
udp_set_csum(bool nocheck,struct sk_buff * skb,__be32 saddr,__be32 daddr,int len)883af5fcba7STom Herbert void udp_set_csum(bool nocheck, struct sk_buff *skb,
884af5fcba7STom Herbert 		  __be32 saddr, __be32 daddr, int len)
885af5fcba7STom Herbert {
886af5fcba7STom Herbert 	struct udphdr *uh = udp_hdr(skb);
887af5fcba7STom Herbert 
888179bc67fSEdward Cree 	if (nocheck) {
889af5fcba7STom Herbert 		uh->check = 0;
890179bc67fSEdward Cree 	} else if (skb_is_gso(skb)) {
891af5fcba7STom Herbert 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
892179bc67fSEdward Cree 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) {
893179bc67fSEdward Cree 		uh->check = 0;
894179bc67fSEdward Cree 		uh->check = udp_v4_check(len, saddr, daddr, lco_csum(skb));
895179bc67fSEdward Cree 		if (uh->check == 0)
896179bc67fSEdward Cree 			uh->check = CSUM_MANGLED_0;
897d75f1306SEdward Cree 	} else {
898af5fcba7STom Herbert 		skb->ip_summed = CHECKSUM_PARTIAL;
899af5fcba7STom Herbert 		skb->csum_start = skb_transport_header(skb) - skb->head;
900af5fcba7STom Herbert 		skb->csum_offset = offsetof(struct udphdr, check);
901af5fcba7STom Herbert 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
902af5fcba7STom Herbert 	}
903af5fcba7STom Herbert }
904af5fcba7STom Herbert EXPORT_SYMBOL(udp_set_csum);
905af5fcba7STom Herbert 
udp_send_skb(struct sk_buff * skb,struct flowi4 * fl4,struct inet_cork * cork)906bec1f6f6SWillem de Bruijn static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4,
907bec1f6f6SWillem de Bruijn 			struct inet_cork *cork)
908f6b9664fSHerbert Xu {
909f6b9664fSHerbert Xu 	struct sock *sk = skb->sk;
910f6b9664fSHerbert Xu 	struct inet_sock *inet = inet_sk(sk);
911f6b9664fSHerbert Xu 	struct udphdr *uh;
912cffb8f61SMenglong Dong 	int err;
913f6b9664fSHerbert Xu 	int is_udplite = IS_UDPLITE(sk);
914f6b9664fSHerbert Xu 	int offset = skb_transport_offset(skb);
915f6b9664fSHerbert Xu 	int len = skb->len - offset;
9164094871dSJosh Hunt 	int datalen = len - sizeof(*uh);
917f6b9664fSHerbert Xu 	__wsum csum = 0;
918f6b9664fSHerbert Xu 
919f6b9664fSHerbert Xu 	/*
920f6b9664fSHerbert Xu 	 * Create a UDP header
921f6b9664fSHerbert Xu 	 */
922f6b9664fSHerbert Xu 	uh = udp_hdr(skb);
923f6b9664fSHerbert Xu 	uh->source = inet->inet_sport;
92479ab0531SDavid S. Miller 	uh->dest = fl4->fl4_dport;
925f6b9664fSHerbert Xu 	uh->len = htons(len);
926f6b9664fSHerbert Xu 	uh->check = 0;
927f6b9664fSHerbert Xu 
928bec1f6f6SWillem de Bruijn 	if (cork->gso_size) {
929bec1f6f6SWillem de Bruijn 		const int hlen = skb_network_header_len(skb) +
930bec1f6f6SWillem de Bruijn 				 sizeof(struct udphdr);
931bec1f6f6SWillem de Bruijn 
9320f149c9fSWillem de Bruijn 		if (hlen + cork->gso_size > cork->fragsize) {
9330f149c9fSWillem de Bruijn 			kfree_skb(skb);
934bec1f6f6SWillem de Bruijn 			return -EINVAL;
9350f149c9fSWillem de Bruijn 		}
936158390e4SJianguo Wu 		if (datalen > cork->gso_size * UDP_MAX_SEGMENTS) {
9370f149c9fSWillem de Bruijn 			kfree_skb(skb);
938bec1f6f6SWillem de Bruijn 			return -EINVAL;
9390f149c9fSWillem de Bruijn 		}
9400f149c9fSWillem de Bruijn 		if (sk->sk_no_check_tx) {
9410f149c9fSWillem de Bruijn 			kfree_skb(skb);
942a8c744a8SWillem de Bruijn 			return -EINVAL;
9430f149c9fSWillem de Bruijn 		}
94410154dbdSJakub Sitnicki 		if (is_udplite || dst_xfrm(skb_dst(skb))) {
9450f149c9fSWillem de Bruijn 			kfree_skb(skb);
946bec1f6f6SWillem de Bruijn 			return -EIO;
9470f149c9fSWillem de Bruijn 		}
948bec1f6f6SWillem de Bruijn 
9494094871dSJosh Hunt 		if (datalen > cork->gso_size) {
950bec1f6f6SWillem de Bruijn 			skb_shinfo(skb)->gso_size = cork->gso_size;
951bec1f6f6SWillem de Bruijn 			skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4;
9524094871dSJosh Hunt 			skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(datalen,
953dfec0ee2SAlexander Duyck 								 cork->gso_size);
9544094871dSJosh Hunt 		}
955a8c744a8SWillem de Bruijn 		goto csum_partial;
956bec1f6f6SWillem de Bruijn 	}
957bec1f6f6SWillem de Bruijn 
958f6b9664fSHerbert Xu 	if (is_udplite)  				 /*     UDP-Lite      */
959f6b9664fSHerbert Xu 		csum = udplite_csum(skb);
960f6b9664fSHerbert Xu 
961ab2fb7e3SWillem de Bruijn 	else if (sk->sk_no_check_tx) {			 /* UDP csum off */
962f6b9664fSHerbert Xu 
963f6b9664fSHerbert Xu 		skb->ip_summed = CHECKSUM_NONE;
964f6b9664fSHerbert Xu 		goto send;
965f6b9664fSHerbert Xu 
966f6b9664fSHerbert Xu 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
967a8c744a8SWillem de Bruijn csum_partial:
968f6b9664fSHerbert Xu 
96979ab0531SDavid S. Miller 		udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
970f6b9664fSHerbert Xu 		goto send;
971f6b9664fSHerbert Xu 
972f6b9664fSHerbert Xu 	} else
973f6b9664fSHerbert Xu 		csum = udp_csum(skb);
974f6b9664fSHerbert Xu 
975f6b9664fSHerbert Xu 	/* add protocol-dependent pseudo-header */
97679ab0531SDavid S. Miller 	uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
977f6b9664fSHerbert Xu 				      sk->sk_protocol, csum);
978f6b9664fSHerbert Xu 	if (uh->check == 0)
979f6b9664fSHerbert Xu 		uh->check = CSUM_MANGLED_0;
980f6b9664fSHerbert Xu 
981f6b9664fSHerbert Xu send:
982b5ec8eeaSEric Dumazet 	err = ip_send_skb(sock_net(sk), skb);
983f6b9664fSHerbert Xu 	if (err) {
9846b5f43eaSEric Dumazet 		if (err == -ENOBUFS &&
9856b5f43eaSEric Dumazet 		    !inet_test_bit(RECVERR, sk)) {
9866aef70a8SEric Dumazet 			UDP_INC_STATS(sock_net(sk),
987f6b9664fSHerbert Xu 				      UDP_MIB_SNDBUFERRORS, is_udplite);
988f6b9664fSHerbert Xu 			err = 0;
989f6b9664fSHerbert Xu 		}
990f6b9664fSHerbert Xu 	} else
9916aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
992f6b9664fSHerbert Xu 			      UDP_MIB_OUTDATAGRAMS, is_udplite);
993f6b9664fSHerbert Xu 	return err;
994f6b9664fSHerbert Xu }
995f6b9664fSHerbert Xu 
996db8dac20SDavid S. Miller /*
997db8dac20SDavid S. Miller  * Push out all pending data as one UDP datagram. Socket is locked.
998db8dac20SDavid S. Miller  */
udp_push_pending_frames(struct sock * sk)9998822b64aSHannes Frederic Sowa int udp_push_pending_frames(struct sock *sk)
1000db8dac20SDavid S. Miller {
1001db8dac20SDavid S. Miller 	struct udp_sock  *up = udp_sk(sk);
1002db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1003b6f21b26SDavid S. Miller 	struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
1004db8dac20SDavid S. Miller 	struct sk_buff *skb;
1005db8dac20SDavid S. Miller 	int err = 0;
1006db8dac20SDavid S. Miller 
100777968b78SDavid S. Miller 	skb = ip_finish_skb(sk, fl4);
1008f6b9664fSHerbert Xu 	if (!skb)
1009db8dac20SDavid S. Miller 		goto out;
1010db8dac20SDavid S. Miller 
1011bec1f6f6SWillem de Bruijn 	err = udp_send_skb(skb, fl4, &inet->cork.base);
1012db8dac20SDavid S. Miller 
1013db8dac20SDavid S. Miller out:
1014db8dac20SDavid S. Miller 	up->len = 0;
1015482521d8SEric Dumazet 	WRITE_ONCE(up->pending, 0);
1016db8dac20SDavid S. Miller 	return err;
1017db8dac20SDavid S. Miller }
10188822b64aSHannes Frederic Sowa EXPORT_SYMBOL(udp_push_pending_frames);
1019db8dac20SDavid S. Miller 
__udp_cmsg_send(struct cmsghdr * cmsg,u16 * gso_size)10202e8de857SWillem de Bruijn static int __udp_cmsg_send(struct cmsghdr *cmsg, u16 *gso_size)
10212e8de857SWillem de Bruijn {
10222e8de857SWillem de Bruijn 	switch (cmsg->cmsg_type) {
10232e8de857SWillem de Bruijn 	case UDP_SEGMENT:
10242e8de857SWillem de Bruijn 		if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u16)))
10252e8de857SWillem de Bruijn 			return -EINVAL;
10262e8de857SWillem de Bruijn 		*gso_size = *(__u16 *)CMSG_DATA(cmsg);
10272e8de857SWillem de Bruijn 		return 0;
10282e8de857SWillem de Bruijn 	default:
10292e8de857SWillem de Bruijn 		return -EINVAL;
10302e8de857SWillem de Bruijn 	}
10312e8de857SWillem de Bruijn }
10322e8de857SWillem de Bruijn 
udp_cmsg_send(struct sock * sk,struct msghdr * msg,u16 * gso_size)10332e8de857SWillem de Bruijn int udp_cmsg_send(struct sock *sk, struct msghdr *msg, u16 *gso_size)
10342e8de857SWillem de Bruijn {
10352e8de857SWillem de Bruijn 	struct cmsghdr *cmsg;
10362e8de857SWillem de Bruijn 	bool need_ip = false;
10372e8de857SWillem de Bruijn 	int err;
10382e8de857SWillem de Bruijn 
10392e8de857SWillem de Bruijn 	for_each_cmsghdr(cmsg, msg) {
10402e8de857SWillem de Bruijn 		if (!CMSG_OK(msg, cmsg))
10412e8de857SWillem de Bruijn 			return -EINVAL;
10422e8de857SWillem de Bruijn 
10432e8de857SWillem de Bruijn 		if (cmsg->cmsg_level != SOL_UDP) {
10442e8de857SWillem de Bruijn 			need_ip = true;
10452e8de857SWillem de Bruijn 			continue;
10462e8de857SWillem de Bruijn 		}
10472e8de857SWillem de Bruijn 
10482e8de857SWillem de Bruijn 		err = __udp_cmsg_send(cmsg, gso_size);
10492e8de857SWillem de Bruijn 		if (err)
10502e8de857SWillem de Bruijn 			return err;
10512e8de857SWillem de Bruijn 	}
10522e8de857SWillem de Bruijn 
10532e8de857SWillem de Bruijn 	return need_ip;
10542e8de857SWillem de Bruijn }
10552e8de857SWillem de Bruijn EXPORT_SYMBOL_GPL(udp_cmsg_send);
10562e8de857SWillem de Bruijn 
udp_sendmsg(struct sock * sk,struct msghdr * msg,size_t len)10571b784140SYing Xue int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1058db8dac20SDavid S. Miller {
1059db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1060db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
10611cedee13SAndrey Ignatov 	DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
1062e474995fSDavid S. Miller 	struct flowi4 fl4_stack;
1063b6f21b26SDavid S. Miller 	struct flowi4 *fl4;
1064db8dac20SDavid S. Miller 	int ulen = len;
1065db8dac20SDavid S. Miller 	struct ipcm_cookie ipc;
1066db8dac20SDavid S. Miller 	struct rtable *rt = NULL;
1067db8dac20SDavid S. Miller 	int free = 0;
1068db8dac20SDavid S. Miller 	int connected = 0;
1069db8dac20SDavid S. Miller 	__be32 daddr, faddr, saddr;
10700e26371dSGuillaume Nault 	u8 tos, scope;
1071db8dac20SDavid S. Miller 	__be16 dport;
1072db8dac20SDavid S. Miller 	int err, is_udplite = IS_UDPLITE(sk);
107381b36803SEric Dumazet 	int corkreq = udp_test_bit(CORK, sk) || msg->msg_flags & MSG_MORE;
1074db8dac20SDavid S. Miller 	int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
1075903ab86dSHerbert Xu 	struct sk_buff *skb;
1076f6d8bd05SEric Dumazet 	struct ip_options_data opt_copy;
1077959d5c11SEric Dumazet 	int uc_index;
1078db8dac20SDavid S. Miller 
1079db8dac20SDavid S. Miller 	if (len > 0xFFFF)
1080db8dac20SDavid S. Miller 		return -EMSGSIZE;
1081db8dac20SDavid S. Miller 
1082db8dac20SDavid S. Miller 	/*
1083db8dac20SDavid S. Miller 	 *	Check the flags.
1084db8dac20SDavid S. Miller 	 */
1085db8dac20SDavid S. Miller 
1086db8dac20SDavid S. Miller 	if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
1087db8dac20SDavid S. Miller 		return -EOPNOTSUPP;
1088db8dac20SDavid S. Miller 
1089903ab86dSHerbert Xu 	getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
1090903ab86dSHerbert Xu 
1091f5fca608SDavid S. Miller 	fl4 = &inet->cork.fl.u.ip4;
1092482521d8SEric Dumazet 	if (READ_ONCE(up->pending)) {
1093db8dac20SDavid S. Miller 		/*
1094db8dac20SDavid S. Miller 		 * There are pending frames.
1095db8dac20SDavid S. Miller 		 * The socket lock must be held while it's corked.
1096db8dac20SDavid S. Miller 		 */
1097db8dac20SDavid S. Miller 		lock_sock(sk);
1098db8dac20SDavid S. Miller 		if (likely(up->pending)) {
1099db8dac20SDavid S. Miller 			if (unlikely(up->pending != AF_INET)) {
1100db8dac20SDavid S. Miller 				release_sock(sk);
1101db8dac20SDavid S. Miller 				return -EINVAL;
1102db8dac20SDavid S. Miller 			}
1103db8dac20SDavid S. Miller 			goto do_append_data;
1104db8dac20SDavid S. Miller 		}
1105db8dac20SDavid S. Miller 		release_sock(sk);
1106db8dac20SDavid S. Miller 	}
1107db8dac20SDavid S. Miller 	ulen += sizeof(struct udphdr);
1108db8dac20SDavid S. Miller 
1109db8dac20SDavid S. Miller 	/*
1110db8dac20SDavid S. Miller 	 *	Get and verify the address.
1111db8dac20SDavid S. Miller 	 */
11121cedee13SAndrey Ignatov 	if (usin) {
1113db8dac20SDavid S. Miller 		if (msg->msg_namelen < sizeof(*usin))
1114db8dac20SDavid S. Miller 			return -EINVAL;
1115db8dac20SDavid S. Miller 		if (usin->sin_family != AF_INET) {
1116db8dac20SDavid S. Miller 			if (usin->sin_family != AF_UNSPEC)
1117db8dac20SDavid S. Miller 				return -EAFNOSUPPORT;
1118db8dac20SDavid S. Miller 		}
1119db8dac20SDavid S. Miller 
1120db8dac20SDavid S. Miller 		daddr = usin->sin_addr.s_addr;
1121db8dac20SDavid S. Miller 		dport = usin->sin_port;
1122db8dac20SDavid S. Miller 		if (dport == 0)
1123db8dac20SDavid S. Miller 			return -EINVAL;
1124db8dac20SDavid S. Miller 	} else {
1125db8dac20SDavid S. Miller 		if (sk->sk_state != TCP_ESTABLISHED)
1126db8dac20SDavid S. Miller 			return -EDESTADDRREQ;
1127c720c7e8SEric Dumazet 		daddr = inet->inet_daddr;
1128c720c7e8SEric Dumazet 		dport = inet->inet_dport;
1129db8dac20SDavid S. Miller 		/* Open fast path for connected socket.
1130db8dac20SDavid S. Miller 		   Route will not be used, if at least one option is set.
1131db8dac20SDavid S. Miller 		 */
1132db8dac20SDavid S. Miller 		connected = 1;
1133db8dac20SDavid S. Miller 	}
1134c14ac945SSoheil Hassas Yeganeh 
113535178206SWillem de Bruijn 	ipcm_init_sk(&ipc, inet);
113618a419baSEric Dumazet 	ipc.gso_size = READ_ONCE(up->gso_size);
1137bf84a010SDaniel Borkmann 
1138db8dac20SDavid S. Miller 	if (msg->msg_controllen) {
11392e8de857SWillem de Bruijn 		err = udp_cmsg_send(sk, msg, &ipc.gso_size);
1140680d11f6SYick Xie 		if (err > 0) {
11412e8de857SWillem de Bruijn 			err = ip_cmsg_send(sk, msg, &ipc,
11422e8de857SWillem de Bruijn 					   sk->sk_family == AF_INET6);
1143680d11f6SYick Xie 			connected = 0;
1144680d11f6SYick Xie 		}
11452e8de857SWillem de Bruijn 		if (unlikely(err < 0)) {
114691948309SEric Dumazet 			kfree(ipc.opt);
1147db8dac20SDavid S. Miller 			return err;
114891948309SEric Dumazet 		}
1149db8dac20SDavid S. Miller 		if (ipc.opt)
1150db8dac20SDavid S. Miller 			free = 1;
1151db8dac20SDavid S. Miller 	}
1152f6d8bd05SEric Dumazet 	if (!ipc.opt) {
1153f6d8bd05SEric Dumazet 		struct ip_options_rcu *inet_opt;
1154f6d8bd05SEric Dumazet 
1155f6d8bd05SEric Dumazet 		rcu_read_lock();
1156f6d8bd05SEric Dumazet 		inet_opt = rcu_dereference(inet->inet_opt);
1157f6d8bd05SEric Dumazet 		if (inet_opt) {
1158f6d8bd05SEric Dumazet 			memcpy(&opt_copy, inet_opt,
1159f6d8bd05SEric Dumazet 			       sizeof(*inet_opt) + inet_opt->opt.optlen);
1160f6d8bd05SEric Dumazet 			ipc.opt = &opt_copy.opt;
1161f6d8bd05SEric Dumazet 		}
1162f6d8bd05SEric Dumazet 		rcu_read_unlock();
1163f6d8bd05SEric Dumazet 	}
1164db8dac20SDavid S. Miller 
11656fc88c35SDave Marchevsky 	if (cgroup_bpf_enabled(CGROUP_UDP4_SENDMSG) && !connected) {
11661cedee13SAndrey Ignatov 		err = BPF_CGROUP_RUN_PROG_UDP4_SENDMSG_LOCK(sk,
1167fefba7d1SDaan De Meyer 					    (struct sockaddr *)usin,
1168fefba7d1SDaan De Meyer 					    &msg->msg_namelen,
1169fefba7d1SDaan De Meyer 					    &ipc.addr);
11701cedee13SAndrey Ignatov 		if (err)
11711cedee13SAndrey Ignatov 			goto out_free;
11721cedee13SAndrey Ignatov 		if (usin) {
11731cedee13SAndrey Ignatov 			if (usin->sin_port == 0) {
11741cedee13SAndrey Ignatov 				/* BPF program set invalid port. Reject it. */
11751cedee13SAndrey Ignatov 				err = -EINVAL;
11761cedee13SAndrey Ignatov 				goto out_free;
11771cedee13SAndrey Ignatov 			}
11781cedee13SAndrey Ignatov 			daddr = usin->sin_addr.s_addr;
11791cedee13SAndrey Ignatov 			dport = usin->sin_port;
11801cedee13SAndrey Ignatov 		}
11811cedee13SAndrey Ignatov 	}
11821cedee13SAndrey Ignatov 
1183db8dac20SDavid S. Miller 	saddr = ipc.addr;
1184db8dac20SDavid S. Miller 	ipc.addr = faddr = daddr;
1185db8dac20SDavid S. Miller 
1186f6d8bd05SEric Dumazet 	if (ipc.opt && ipc.opt->opt.srr) {
11871b97013bSAndrey Ignatov 		if (!daddr) {
11881b97013bSAndrey Ignatov 			err = -EINVAL;
11891b97013bSAndrey Ignatov 			goto out_free;
11901b97013bSAndrey Ignatov 		}
1191f6d8bd05SEric Dumazet 		faddr = ipc.opt->opt.faddr;
1192db8dac20SDavid S. Miller 		connected = 0;
1193db8dac20SDavid S. Miller 	}
1194aa661581SFrancesco Fusco 	tos = get_rttos(&ipc, inet);
11950e26371dSGuillaume Nault 	scope = ip_sendmsg_scope(inet, &ipc, msg);
11960e26371dSGuillaume Nault 	if (scope == RT_SCOPE_LINK)
1197db8dac20SDavid S. Miller 		connected = 0;
1198db8dac20SDavid S. Miller 
1199959d5c11SEric Dumazet 	uc_index = READ_ONCE(inet->uc_index);
1200db8dac20SDavid S. Miller 	if (ipv4_is_multicast(daddr)) {
1201854da991SRobert Shearman 		if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif))
120202715925SEric Dumazet 			ipc.oif = READ_ONCE(inet->mc_index);
1203db8dac20SDavid S. Miller 		if (!saddr)
120402715925SEric Dumazet 			saddr = READ_ONCE(inet->mc_addr);
1205db8dac20SDavid S. Miller 		connected = 0;
12069515a2e0SDavid Ahern 	} else if (!ipc.oif) {
1207959d5c11SEric Dumazet 		ipc.oif = uc_index;
1208959d5c11SEric Dumazet 	} else if (ipv4_is_lbcast(daddr) && uc_index) {
12099515a2e0SDavid Ahern 		/* oif is set, packet is to local broadcast and
12102bdcc73cSRandy Dunlap 		 * uc_index is set. oif is most likely set
12119515a2e0SDavid Ahern 		 * by sk_bound_dev_if. If uc_index != oif check if the
12129515a2e0SDavid Ahern 		 * oif is an L3 master and uc_index is an L3 slave.
12139515a2e0SDavid Ahern 		 * If so, we want to allow the send using the uc_index.
12149515a2e0SDavid Ahern 		 */
1215959d5c11SEric Dumazet 		if (ipc.oif != uc_index &&
12169515a2e0SDavid Ahern 		    ipc.oif == l3mdev_master_ifindex_by_index(sock_net(sk),
1217959d5c11SEric Dumazet 							      uc_index)) {
1218959d5c11SEric Dumazet 			ipc.oif = uc_index;
12199515a2e0SDavid Ahern 		}
12209515a2e0SDavid Ahern 	}
1221db8dac20SDavid S. Miller 
1222db8dac20SDavid S. Miller 	if (connected)
122305d6d492SEric Dumazet 		rt = dst_rtable(sk_dst_check(sk, 0));
1224db8dac20SDavid S. Miller 
122551456b29SIan Morris 	if (!rt) {
122684a3aa00SPavel Emelyanov 		struct net *net = sock_net(sk);
12279a24abfaSDavid Ahern 		__u8 flow_flags = inet_sk_flowi_flags(sk);
122884a3aa00SPavel Emelyanov 
1229e474995fSDavid S. Miller 		fl4 = &fl4_stack;
12309a24abfaSDavid Ahern 
12310e26371dSGuillaume Nault 		flowi4_init_output(fl4, ipc.oif, ipc.sockc.mark, tos, scope,
12320e26371dSGuillaume Nault 				   sk->sk_protocol, flow_flags, faddr, saddr,
12330e26371dSGuillaume Nault 				   dport, inet->inet_sport, sk->sk_uid);
1234c0951cbcSDavid S. Miller 
12353df98d79SPaul Moore 		security_sk_classify_flow(sk, flowi4_to_flowi_common(fl4));
1236e474995fSDavid S. Miller 		rt = ip_route_output_flow(net, fl4, sk);
1237b23dd4feSDavid S. Miller 		if (IS_ERR(rt)) {
1238b23dd4feSDavid S. Miller 			err = PTR_ERR(rt);
123906dc94b1SDavid S. Miller 			rt = NULL;
1240db8dac20SDavid S. Miller 			if (err == -ENETUNREACH)
1241f1d8cba6SEric Dumazet 				IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
1242db8dac20SDavid S. Miller 			goto out;
1243db8dac20SDavid S. Miller 		}
1244db8dac20SDavid S. Miller 
1245db8dac20SDavid S. Miller 		err = -EACCES;
1246db8dac20SDavid S. Miller 		if ((rt->rt_flags & RTCF_BROADCAST) &&
1247db8dac20SDavid S. Miller 		    !sock_flag(sk, SOCK_BROADCAST))
1248db8dac20SDavid S. Miller 			goto out;
1249db8dac20SDavid S. Miller 		if (connected)
1250d8d1f30bSChangli Gao 			sk_dst_set(sk, dst_clone(&rt->dst));
1251db8dac20SDavid S. Miller 	}
1252db8dac20SDavid S. Miller 
1253db8dac20SDavid S. Miller 	if (msg->msg_flags&MSG_CONFIRM)
1254db8dac20SDavid S. Miller 		goto do_confirm;
1255db8dac20SDavid S. Miller back_from_confirm:
1256db8dac20SDavid S. Miller 
1257e474995fSDavid S. Miller 	saddr = fl4->saddr;
1258db8dac20SDavid S. Miller 	if (!ipc.addr)
1259e474995fSDavid S. Miller 		daddr = ipc.addr = fl4->daddr;
1260db8dac20SDavid S. Miller 
1261903ab86dSHerbert Xu 	/* Lockless fast path for the non-corking case. */
1262903ab86dSHerbert Xu 	if (!corkreq) {
12631cd7884dSWillem de Bruijn 		struct inet_cork cork;
12641cd7884dSWillem de Bruijn 
1265f69e6d13SAl Viro 		skb = ip_make_skb(sk, fl4, getfrag, msg, ulen,
1266903ab86dSHerbert Xu 				  sizeof(struct udphdr), &ipc, &rt,
12671cd7884dSWillem de Bruijn 				  &cork, msg->msg_flags);
1268903ab86dSHerbert Xu 		err = PTR_ERR(skb);
126950c3a487SYOSHIFUJI Hideaki / 吉藤英明 		if (!IS_ERR_OR_NULL(skb))
1270bec1f6f6SWillem de Bruijn 			err = udp_send_skb(skb, fl4, &cork);
1271903ab86dSHerbert Xu 		goto out;
1272903ab86dSHerbert Xu 	}
1273903ab86dSHerbert Xu 
1274db8dac20SDavid S. Miller 	lock_sock(sk);
1275db8dac20SDavid S. Miller 	if (unlikely(up->pending)) {
1276db8dac20SDavid S. Miller 		/* The socket is already corked while preparing it. */
1277db8dac20SDavid S. Miller 		/* ... which is an evident application bug. --ANK */
1278db8dac20SDavid S. Miller 		release_sock(sk);
1279db8dac20SDavid S. Miller 
1280197df02cSMatteo Croce 		net_dbg_ratelimited("socket already corked\n");
1281db8dac20SDavid S. Miller 		err = -EINVAL;
1282db8dac20SDavid S. Miller 		goto out;
1283db8dac20SDavid S. Miller 	}
1284db8dac20SDavid S. Miller 	/*
1285db8dac20SDavid S. Miller 	 *	Now cork the socket to pend data.
1286db8dac20SDavid S. Miller 	 */
1287b6f21b26SDavid S. Miller 	fl4 = &inet->cork.fl.u.ip4;
1288b6f21b26SDavid S. Miller 	fl4->daddr = daddr;
1289b6f21b26SDavid S. Miller 	fl4->saddr = saddr;
12909cce96dfSDavid S. Miller 	fl4->fl4_dport = dport;
12919cce96dfSDavid S. Miller 	fl4->fl4_sport = inet->inet_sport;
1292482521d8SEric Dumazet 	WRITE_ONCE(up->pending, AF_INET);
1293db8dac20SDavid S. Miller 
1294db8dac20SDavid S. Miller do_append_data:
1295db8dac20SDavid S. Miller 	up->len += ulen;
1296f69e6d13SAl Viro 	err = ip_append_data(sk, fl4, getfrag, msg, ulen,
12972e77d89bSEric Dumazet 			     sizeof(struct udphdr), &ipc, &rt,
1298db8dac20SDavid S. Miller 			     corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
1299db8dac20SDavid S. Miller 	if (err)
1300db8dac20SDavid S. Miller 		udp_flush_pending_frames(sk);
1301db8dac20SDavid S. Miller 	else if (!corkreq)
1302db8dac20SDavid S. Miller 		err = udp_push_pending_frames(sk);
1303db8dac20SDavid S. Miller 	else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
1304482521d8SEric Dumazet 		WRITE_ONCE(up->pending, 0);
1305db8dac20SDavid S. Miller 	release_sock(sk);
1306db8dac20SDavid S. Miller 
1307db8dac20SDavid S. Miller out:
1308db8dac20SDavid S. Miller 	ip_rt_put(rt);
13091b97013bSAndrey Ignatov out_free:
1310db8dac20SDavid S. Miller 	if (free)
1311db8dac20SDavid S. Miller 		kfree(ipc.opt);
1312db8dac20SDavid S. Miller 	if (!err)
1313db8dac20SDavid S. Miller 		return len;
1314db8dac20SDavid S. Miller 	/*
1315db8dac20SDavid S. Miller 	 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space.  Reporting
1316db8dac20SDavid S. Miller 	 * ENOBUFS might not be good (it's not tunable per se), but otherwise
1317db8dac20SDavid S. Miller 	 * we don't have a good statistic (IpOutDiscards but it can be too many
1318db8dac20SDavid S. Miller 	 * things).  We could add another new stat but at least for now that
1319db8dac20SDavid S. Miller 	 * seems like overkill.
1320db8dac20SDavid S. Miller 	 */
1321db8dac20SDavid S. Miller 	if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
13226aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
1323629ca23cSPavel Emelyanov 			      UDP_MIB_SNDBUFERRORS, is_udplite);
1324db8dac20SDavid S. Miller 	}
1325db8dac20SDavid S. Miller 	return err;
1326db8dac20SDavid S. Miller 
1327db8dac20SDavid S. Miller do_confirm:
13280dec879fSJulian Anastasov 	if (msg->msg_flags & MSG_PROBE)
13290dec879fSJulian Anastasov 		dst_confirm_neigh(&rt->dst, &fl4->daddr);
1330db8dac20SDavid S. Miller 	if (!(msg->msg_flags&MSG_PROBE) || len)
1331db8dac20SDavid S. Miller 		goto back_from_confirm;
1332db8dac20SDavid S. Miller 	err = 0;
1333db8dac20SDavid S. Miller 	goto out;
1334db8dac20SDavid S. Miller }
1335c482c568SEric Dumazet EXPORT_SYMBOL(udp_sendmsg);
1336db8dac20SDavid S. Miller 
udp_splice_eof(struct socket * sock)13371d7e4538SDavid Howells void udp_splice_eof(struct socket *sock)
13381d7e4538SDavid Howells {
13391d7e4538SDavid Howells 	struct sock *sk = sock->sk;
13401d7e4538SDavid Howells 	struct udp_sock *up = udp_sk(sk);
13411d7e4538SDavid Howells 
1342482521d8SEric Dumazet 	if (!READ_ONCE(up->pending) || udp_test_bit(CORK, sk))
13431d7e4538SDavid Howells 		return;
13441d7e4538SDavid Howells 
13451d7e4538SDavid Howells 	lock_sock(sk);
134681b36803SEric Dumazet 	if (up->pending && !udp_test_bit(CORK, sk))
13471d7e4538SDavid Howells 		udp_push_pending_frames(sk);
13481d7e4538SDavid Howells 	release_sock(sk);
13491d7e4538SDavid Howells }
13501d7e4538SDavid Howells EXPORT_SYMBOL_GPL(udp_splice_eof);
13511d7e4538SDavid Howells 
1352dce4551cSPaolo Abeni #define UDP_SKB_IS_STATELESS 0x80000000
1353dce4551cSPaolo Abeni 
1354677bf08cSFlorian Westphal /* all head states (dst, sk, nf conntrack) except skb extensions are
1355677bf08cSFlorian Westphal  * cleared by udp_rcv().
1356677bf08cSFlorian Westphal  *
1357677bf08cSFlorian Westphal  * We need to preserve secpath, if present, to eventually process
1358677bf08cSFlorian Westphal  * IP_CMSG_PASSSEC at recvmsg() time.
1359677bf08cSFlorian Westphal  *
1360677bf08cSFlorian Westphal  * Other extensions can be cleared.
1361677bf08cSFlorian Westphal  */
udp_try_make_stateless(struct sk_buff * skb)1362677bf08cSFlorian Westphal static bool udp_try_make_stateless(struct sk_buff *skb)
1363677bf08cSFlorian Westphal {
1364677bf08cSFlorian Westphal 	if (!skb_has_extensions(skb))
1365677bf08cSFlorian Westphal 		return true;
1366677bf08cSFlorian Westphal 
1367677bf08cSFlorian Westphal 	if (!secpath_exists(skb)) {
1368677bf08cSFlorian Westphal 		skb_ext_reset(skb);
1369677bf08cSFlorian Westphal 		return true;
1370677bf08cSFlorian Westphal 	}
1371677bf08cSFlorian Westphal 
1372677bf08cSFlorian Westphal 	return false;
1373677bf08cSFlorian Westphal }
1374677bf08cSFlorian Westphal 
udp_set_dev_scratch(struct sk_buff * skb)1375b65ac446SPaolo Abeni static void udp_set_dev_scratch(struct sk_buff *skb)
1376b65ac446SPaolo Abeni {
1377dce4551cSPaolo Abeni 	struct udp_dev_scratch *scratch = udp_skb_scratch(skb);
1378b65ac446SPaolo Abeni 
1379b65ac446SPaolo Abeni 	BUILD_BUG_ON(sizeof(struct udp_dev_scratch) > sizeof(long));
1380dce4551cSPaolo Abeni 	scratch->_tsize_state = skb->truesize;
1381dce4551cSPaolo Abeni #if BITS_PER_LONG == 64
1382b65ac446SPaolo Abeni 	scratch->len = skb->len;
1383b65ac446SPaolo Abeni 	scratch->csum_unnecessary = !!skb_csum_unnecessary(skb);
1384b65ac446SPaolo Abeni 	scratch->is_linear = !skb_is_nonlinear(skb);
1385b65ac446SPaolo Abeni #endif
1386677bf08cSFlorian Westphal 	if (udp_try_make_stateless(skb))
1387dce4551cSPaolo Abeni 		scratch->_tsize_state |= UDP_SKB_IS_STATELESS;
1388dce4551cSPaolo Abeni }
1389dce4551cSPaolo Abeni 
udp_skb_csum_unnecessary_set(struct sk_buff * skb)1390a793183cSEric Dumazet static void udp_skb_csum_unnecessary_set(struct sk_buff *skb)
1391a793183cSEric Dumazet {
1392a793183cSEric Dumazet 	/* We come here after udp_lib_checksum_complete() returned 0.
1393a793183cSEric Dumazet 	 * This means that __skb_checksum_complete() might have
1394a793183cSEric Dumazet 	 * set skb->csum_valid to 1.
1395a793183cSEric Dumazet 	 * On 64bit platforms, we can set csum_unnecessary
1396a793183cSEric Dumazet 	 * to true, but only if the skb is not shared.
1397a793183cSEric Dumazet 	 */
1398a793183cSEric Dumazet #if BITS_PER_LONG == 64
1399a793183cSEric Dumazet 	if (!skb_shared(skb))
1400a793183cSEric Dumazet 		udp_skb_scratch(skb)->csum_unnecessary = true;
1401a793183cSEric Dumazet #endif
1402a793183cSEric Dumazet }
1403a793183cSEric Dumazet 
udp_skb_truesize(struct sk_buff * skb)1404dce4551cSPaolo Abeni static int udp_skb_truesize(struct sk_buff *skb)
1405dce4551cSPaolo Abeni {
1406dce4551cSPaolo Abeni 	return udp_skb_scratch(skb)->_tsize_state & ~UDP_SKB_IS_STATELESS;
1407dce4551cSPaolo Abeni }
1408dce4551cSPaolo Abeni 
udp_skb_has_head_state(struct sk_buff * skb)1409dce4551cSPaolo Abeni static bool udp_skb_has_head_state(struct sk_buff *skb)
1410dce4551cSPaolo Abeni {
1411dce4551cSPaolo Abeni 	return !(udp_skb_scratch(skb)->_tsize_state & UDP_SKB_IS_STATELESS);
1412dce4551cSPaolo Abeni }
1413b65ac446SPaolo Abeni 
14147c13f97fSPaolo Abeni /* fully reclaim rmem/fwd memory allocated for skb */
udp_rmem_release(struct sock * sk,int size,int partial,bool rx_queue_lock_held)14156dfb4367SPaolo Abeni static void udp_rmem_release(struct sock *sk, int size, int partial,
14166dfb4367SPaolo Abeni 			     bool rx_queue_lock_held)
1417f970bd9eSPaolo Abeni {
14186b229cf7SEric Dumazet 	struct udp_sock *up = udp_sk(sk);
14192276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue;
1420f970bd9eSPaolo Abeni 	int amt;
1421f970bd9eSPaolo Abeni 
14226b229cf7SEric Dumazet 	if (likely(partial)) {
14236b229cf7SEric Dumazet 		up->forward_deficit += size;
14246b229cf7SEric Dumazet 		size = up->forward_deficit;
14258a3854c7SPaolo Abeni 		if (size < READ_ONCE(up->forward_threshold) &&
1426d39ca259SPaolo Abeni 		    !skb_queue_empty(&up->reader_queue))
14276b229cf7SEric Dumazet 			return;
14286b229cf7SEric Dumazet 	} else {
14296b229cf7SEric Dumazet 		size += up->forward_deficit;
14306b229cf7SEric Dumazet 	}
14316b229cf7SEric Dumazet 	up->forward_deficit = 0;
14326b229cf7SEric Dumazet 
14336dfb4367SPaolo Abeni 	/* acquire the sk_receive_queue for fwd allocated memory scheduling,
14346dfb4367SPaolo Abeni 	 * if the called don't held it already
14356dfb4367SPaolo Abeni 	 */
14362276f58aSPaolo Abeni 	sk_queue = &sk->sk_receive_queue;
14376dfb4367SPaolo Abeni 	if (!rx_queue_lock_held)
14382276f58aSPaolo Abeni 		spin_lock(&sk_queue->lock);
14392276f58aSPaolo Abeni 
14406dfb4367SPaolo Abeni 
14415e6300e7SEric Dumazet 	sk_forward_alloc_add(sk, size);
1442100fdd1fSEric Dumazet 	amt = (sk->sk_forward_alloc - partial) & ~(PAGE_SIZE - 1);
14435e6300e7SEric Dumazet 	sk_forward_alloc_add(sk, -amt);
1444f970bd9eSPaolo Abeni 
1445f970bd9eSPaolo Abeni 	if (amt)
1446100fdd1fSEric Dumazet 		__sk_mem_reduce_allocated(sk, amt >> PAGE_SHIFT);
144702ab0d13SEric Dumazet 
144802ab0d13SEric Dumazet 	atomic_sub(size, &sk->sk_rmem_alloc);
14492276f58aSPaolo Abeni 
14502276f58aSPaolo Abeni 	/* this can save us from acquiring the rx queue lock on next receive */
14512276f58aSPaolo Abeni 	skb_queue_splice_tail_init(sk_queue, &up->reader_queue);
14522276f58aSPaolo Abeni 
14536dfb4367SPaolo Abeni 	if (!rx_queue_lock_held)
14542276f58aSPaolo Abeni 		spin_unlock(&sk_queue->lock);
1455f970bd9eSPaolo Abeni }
1456f970bd9eSPaolo Abeni 
14572276f58aSPaolo Abeni /* Note: called with reader_queue.lock held.
1458c84d9490SEric Dumazet  * Instead of using skb->truesize here, find a copy of it in skb->dev_scratch
1459c84d9490SEric Dumazet  * This avoids a cache line miss while receive_queue lock is held.
1460c84d9490SEric Dumazet  * Look at __udp_enqueue_schedule_skb() to find where this copy is done.
1461c84d9490SEric Dumazet  */
udp_skb_destructor(struct sock * sk,struct sk_buff * skb)14627c13f97fSPaolo Abeni void udp_skb_destructor(struct sock *sk, struct sk_buff *skb)
1463f970bd9eSPaolo Abeni {
1464b65ac446SPaolo Abeni 	prefetch(&skb->data);
1465b65ac446SPaolo Abeni 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, false);
1466f970bd9eSPaolo Abeni }
14677c13f97fSPaolo Abeni EXPORT_SYMBOL(udp_skb_destructor);
1468f970bd9eSPaolo Abeni 
14696dfb4367SPaolo Abeni /* as above, but the caller held the rx queue lock, too */
udp_skb_dtor_locked(struct sock * sk,struct sk_buff * skb)147064f5102dSColin Ian King static void udp_skb_dtor_locked(struct sock *sk, struct sk_buff *skb)
14716dfb4367SPaolo Abeni {
1472b65ac446SPaolo Abeni 	prefetch(&skb->data);
1473b65ac446SPaolo Abeni 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, true);
14746dfb4367SPaolo Abeni }
14756dfb4367SPaolo Abeni 
14764b272750SEric Dumazet /* Idea of busylocks is to let producers grab an extra spinlock
14774b272750SEric Dumazet  * to relieve pressure on the receive_queue spinlock shared by consumer.
14784b272750SEric Dumazet  * Under flood, this means that only one producer can be in line
14794b272750SEric Dumazet  * trying to acquire the receive_queue spinlock.
14804b272750SEric Dumazet  * These busylock can be allocated on a per cpu manner, instead of a
14814b272750SEric Dumazet  * per socket one (that would consume a cache line per socket)
14824b272750SEric Dumazet  */
14834b272750SEric Dumazet static int udp_busylocks_log __read_mostly;
14844b272750SEric Dumazet static spinlock_t *udp_busylocks __read_mostly;
14854b272750SEric Dumazet 
busylock_acquire(void * ptr)14864b272750SEric Dumazet static spinlock_t *busylock_acquire(void *ptr)
14874b272750SEric Dumazet {
14884b272750SEric Dumazet 	spinlock_t *busy;
14894b272750SEric Dumazet 
14904b272750SEric Dumazet 	busy = udp_busylocks + hash_ptr(ptr, udp_busylocks_log);
14914b272750SEric Dumazet 	spin_lock(busy);
14924b272750SEric Dumazet 	return busy;
14934b272750SEric Dumazet }
14944b272750SEric Dumazet 
busylock_release(spinlock_t * busy)14954b272750SEric Dumazet static void busylock_release(spinlock_t *busy)
14964b272750SEric Dumazet {
14974b272750SEric Dumazet 	if (busy)
14984b272750SEric Dumazet 		spin_unlock(busy);
14994b272750SEric Dumazet }
15004b272750SEric Dumazet 
udp_rmem_schedule(struct sock * sk,int size)1501fd9c31f8SJason Xing static int udp_rmem_schedule(struct sock *sk, int size)
1502fd9c31f8SJason Xing {
1503fd9c31f8SJason Xing 	int delta;
1504fd9c31f8SJason Xing 
1505fd9c31f8SJason Xing 	delta = size - sk->sk_forward_alloc;
1506fd9c31f8SJason Xing 	if (delta > 0 && !__sk_mem_schedule(sk, delta, SK_MEM_RECV))
1507fd9c31f8SJason Xing 		return -ENOBUFS;
1508fd9c31f8SJason Xing 
1509fd9c31f8SJason Xing 	return 0;
1510fd9c31f8SJason Xing }
1511fd9c31f8SJason Xing 
__udp_enqueue_schedule_skb(struct sock * sk,struct sk_buff * skb)1512f970bd9eSPaolo Abeni int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb)
1513f970bd9eSPaolo Abeni {
1514f970bd9eSPaolo Abeni 	struct sk_buff_head *list = &sk->sk_receive_queue;
1515fd9c31f8SJason Xing 	int rmem, err = -ENOMEM;
15164b272750SEric Dumazet 	spinlock_t *busy = NULL;
1517612b1c0dSEric Dumazet 	bool becomes_readable;
151860557969SEric Dumazet 	int size, rcvbuf;
1519f970bd9eSPaolo Abeni 
152060557969SEric Dumazet 	/* Immediately drop when the receive queue is full.
152160557969SEric Dumazet 	 * Always allow at least one packet.
1522f970bd9eSPaolo Abeni 	 */
1523f970bd9eSPaolo Abeni 	rmem = atomic_read(&sk->sk_rmem_alloc);
152460557969SEric Dumazet 	rcvbuf = READ_ONCE(sk->sk_rcvbuf);
152560557969SEric Dumazet 	if (rmem > rcvbuf)
1526f970bd9eSPaolo Abeni 		goto drop;
1527f970bd9eSPaolo Abeni 
1528c8c8b127SEric Dumazet 	/* Under mem pressure, it might be helpful to help udp_recvmsg()
1529c8c8b127SEric Dumazet 	 * having linear skbs :
1530c8c8b127SEric Dumazet 	 * - Reduce memory overhead and thus increase receive queue capacity
1531c8c8b127SEric Dumazet 	 * - Less cache line misses at copyout() time
1532c8c8b127SEric Dumazet 	 * - Less work at consume_skb() (less alien page frag freeing)
1533c8c8b127SEric Dumazet 	 */
153460557969SEric Dumazet 	if (rmem > (rcvbuf >> 1)) {
1535c8c8b127SEric Dumazet 		skb_condense(skb);
15364b272750SEric Dumazet 
15374b272750SEric Dumazet 		busy = busylock_acquire(sk);
15384b272750SEric Dumazet 	}
1539c8c8b127SEric Dumazet 	size = skb->truesize;
1540b65ac446SPaolo Abeni 	udp_set_dev_scratch(skb);
1541c8c8b127SEric Dumazet 
15426a1f12ddSEric Dumazet 	atomic_add(size, &sk->sk_rmem_alloc);
1543f970bd9eSPaolo Abeni 
1544f970bd9eSPaolo Abeni 	spin_lock(&list->lock);
1545fd9c31f8SJason Xing 	err = udp_rmem_schedule(sk, size);
1546fd9c31f8SJason Xing 	if (err) {
1547f970bd9eSPaolo Abeni 		spin_unlock(&list->lock);
1548f970bd9eSPaolo Abeni 		goto uncharge_drop;
1549f970bd9eSPaolo Abeni 	}
1550f970bd9eSPaolo Abeni 
15515e6300e7SEric Dumazet 	sk_forward_alloc_add(sk, -size);
1552f970bd9eSPaolo Abeni 
15537c13f97fSPaolo Abeni 	/* no need to setup a destructor, we will explicitly release the
15547c13f97fSPaolo Abeni 	 * forward allocated memory on dequeue
15557c13f97fSPaolo Abeni 	 */
1556f970bd9eSPaolo Abeni 	sock_skb_set_dropcount(sk, skb);
1557f970bd9eSPaolo Abeni 
1558612b1c0dSEric Dumazet 	becomes_readable = skb_queue_empty(list);
1559f970bd9eSPaolo Abeni 	__skb_queue_tail(list, skb);
1560f970bd9eSPaolo Abeni 	spin_unlock(&list->lock);
1561f970bd9eSPaolo Abeni 
1562612b1c0dSEric Dumazet 	if (!sock_flag(sk, SOCK_DEAD)) {
1563612b1c0dSEric Dumazet 		if (becomes_readable ||
1564612b1c0dSEric Dumazet 		    sk->sk_data_ready != sock_def_readable ||
1565612b1c0dSEric Dumazet 		    READ_ONCE(sk->sk_peek_off) >= 0)
1566612b1c0dSEric Dumazet 			INDIRECT_CALL_1(sk->sk_data_ready,
1567612b1c0dSEric Dumazet 					sock_def_readable, sk);
1568612b1c0dSEric Dumazet 		else
15691abe267fSEric Dumazet 			sk_wake_async_rcu(sk, SOCK_WAKE_WAITD, POLL_IN);
1570612b1c0dSEric Dumazet 	}
15714b272750SEric Dumazet 	busylock_release(busy);
1572f970bd9eSPaolo Abeni 	return 0;
1573f970bd9eSPaolo Abeni 
1574f970bd9eSPaolo Abeni uncharge_drop:
1575f970bd9eSPaolo Abeni 	atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
1576f970bd9eSPaolo Abeni 
1577f970bd9eSPaolo Abeni drop:
1578f970bd9eSPaolo Abeni 	atomic_inc(&sk->sk_drops);
15794b272750SEric Dumazet 	busylock_release(busy);
1580f970bd9eSPaolo Abeni 	return err;
1581f970bd9eSPaolo Abeni }
1582f970bd9eSPaolo Abeni EXPORT_SYMBOL_GPL(__udp_enqueue_schedule_skb);
1583f970bd9eSPaolo Abeni 
udp_destruct_common(struct sock * sk)1584d38afeecSKuniyuki Iwashima void udp_destruct_common(struct sock *sk)
1585f970bd9eSPaolo Abeni {
1586f970bd9eSPaolo Abeni 	/* reclaim completely the forward allocated memory */
15872276f58aSPaolo Abeni 	struct udp_sock *up = udp_sk(sk);
15887c13f97fSPaolo Abeni 	unsigned int total = 0;
15897c13f97fSPaolo Abeni 	struct sk_buff *skb;
15907c13f97fSPaolo Abeni 
15912276f58aSPaolo Abeni 	skb_queue_splice_tail_init(&sk->sk_receive_queue, &up->reader_queue);
15922276f58aSPaolo Abeni 	while ((skb = __skb_dequeue(&up->reader_queue)) != NULL) {
15937c13f97fSPaolo Abeni 		total += skb->truesize;
15947c13f97fSPaolo Abeni 		kfree_skb(skb);
15957c13f97fSPaolo Abeni 	}
15966dfb4367SPaolo Abeni 	udp_rmem_release(sk, total, 0, true);
1597d38afeecSKuniyuki Iwashima }
1598d38afeecSKuniyuki Iwashima EXPORT_SYMBOL_GPL(udp_destruct_common);
15997c13f97fSPaolo Abeni 
udp_destruct_sock(struct sock * sk)1600d38afeecSKuniyuki Iwashima static void udp_destruct_sock(struct sock *sk)
1601d38afeecSKuniyuki Iwashima {
1602d38afeecSKuniyuki Iwashima 	udp_destruct_common(sk);
1603f970bd9eSPaolo Abeni 	inet_sock_destruct(sk);
1604f970bd9eSPaolo Abeni }
1605f970bd9eSPaolo Abeni 
udp_init_sock(struct sock * sk)1606f970bd9eSPaolo Abeni int udp_init_sock(struct sock *sk)
1607f970bd9eSPaolo Abeni {
16088a3854c7SPaolo Abeni 	udp_lib_init_sock(sk);
1609f970bd9eSPaolo Abeni 	sk->sk_destruct = udp_destruct_sock;
1610e993ffe3SPavel Begunkov 	set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
1611f970bd9eSPaolo Abeni 	return 0;
1612f970bd9eSPaolo Abeni }
1613f970bd9eSPaolo Abeni 
skb_consume_udp(struct sock * sk,struct sk_buff * skb,int len)1614f970bd9eSPaolo Abeni void skb_consume_udp(struct sock *sk, struct sk_buff *skb, int len)
1615f970bd9eSPaolo Abeni {
1616fecc5155SJakub Kicinski 	if (unlikely(READ_ONCE(udp_sk(sk)->peeking_with_offset)))
1617f970bd9eSPaolo Abeni 		sk_peek_offset_bwd(sk, len);
16180a463c78SPaolo Abeni 
1619ca2c1418SPaolo Abeni 	if (!skb_unref(skb))
1620ca2c1418SPaolo Abeni 		return;
1621ca2c1418SPaolo Abeni 
1622dce4551cSPaolo Abeni 	/* In the more common cases we cleared the head states previously,
1623dce4551cSPaolo Abeni 	 * see __udp_queue_rcv_skb().
16240ddf3fb2SPaolo Abeni 	 */
1625dce4551cSPaolo Abeni 	if (unlikely(udp_skb_has_head_state(skb)))
16260ddf3fb2SPaolo Abeni 		skb_release_head_state(skb);
1627ca2c1418SPaolo Abeni 	__consume_stateless_skb(skb);
1628f970bd9eSPaolo Abeni }
1629f970bd9eSPaolo Abeni EXPORT_SYMBOL_GPL(skb_consume_udp);
1630f970bd9eSPaolo Abeni 
__first_packet_length(struct sock * sk,struct sk_buff_head * rcvq,int * total)16312276f58aSPaolo Abeni static struct sk_buff *__first_packet_length(struct sock *sk,
16322276f58aSPaolo Abeni 					     struct sk_buff_head *rcvq,
16332276f58aSPaolo Abeni 					     int *total)
16342276f58aSPaolo Abeni {
16352276f58aSPaolo Abeni 	struct sk_buff *skb;
16362276f58aSPaolo Abeni 
16379bd780f5SPaolo Abeni 	while ((skb = skb_peek(rcvq)) != NULL) {
16389bd780f5SPaolo Abeni 		if (udp_lib_checksum_complete(skb)) {
16392276f58aSPaolo Abeni 			__UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS,
16402276f58aSPaolo Abeni 					IS_UDPLITE(sk));
16412276f58aSPaolo Abeni 			__UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS,
16422276f58aSPaolo Abeni 					IS_UDPLITE(sk));
16432276f58aSPaolo Abeni 			atomic_inc(&sk->sk_drops);
16442276f58aSPaolo Abeni 			__skb_unlink(skb, rcvq);
16452276f58aSPaolo Abeni 			*total += skb->truesize;
16462276f58aSPaolo Abeni 			kfree_skb(skb);
16479bd780f5SPaolo Abeni 		} else {
1648a793183cSEric Dumazet 			udp_skb_csum_unnecessary_set(skb);
16499bd780f5SPaolo Abeni 			break;
16509bd780f5SPaolo Abeni 		}
16512276f58aSPaolo Abeni 	}
16522276f58aSPaolo Abeni 	return skb;
16532276f58aSPaolo Abeni }
16542276f58aSPaolo Abeni 
165585584672SEric Dumazet /**
165685584672SEric Dumazet  *	first_packet_length	- return length of first packet in receive queue
165785584672SEric Dumazet  *	@sk: socket
165885584672SEric Dumazet  *
165985584672SEric Dumazet  *	Drops all bad checksum frames, until a valid one is found.
1660e83c6744SEric Dumazet  *	Returns the length of found skb, or -1 if none is found.
166185584672SEric Dumazet  */
first_packet_length(struct sock * sk)1662e83c6744SEric Dumazet static int first_packet_length(struct sock *sk)
166385584672SEric Dumazet {
16642276f58aSPaolo Abeni 	struct sk_buff_head *rcvq = &udp_sk(sk)->reader_queue;
16652276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
166685584672SEric Dumazet 	struct sk_buff *skb;
16677c13f97fSPaolo Abeni 	int total = 0;
1668e83c6744SEric Dumazet 	int res;
166985584672SEric Dumazet 
167085584672SEric Dumazet 	spin_lock_bh(&rcvq->lock);
16712276f58aSPaolo Abeni 	skb = __first_packet_length(sk, rcvq, &total);
1672137a0dbeSEric Dumazet 	if (!skb && !skb_queue_empty_lockless(sk_queue)) {
16732276f58aSPaolo Abeni 		spin_lock(&sk_queue->lock);
16742276f58aSPaolo Abeni 		skb_queue_splice_tail_init(sk_queue, rcvq);
16752276f58aSPaolo Abeni 		spin_unlock(&sk_queue->lock);
16762276f58aSPaolo Abeni 
16772276f58aSPaolo Abeni 		skb = __first_packet_length(sk, rcvq, &total);
167885584672SEric Dumazet 	}
1679e83c6744SEric Dumazet 	res = skb ? skb->len : -1;
16807c13f97fSPaolo Abeni 	if (total)
16816dfb4367SPaolo Abeni 		udp_rmem_release(sk, total, 1, false);
168285584672SEric Dumazet 	spin_unlock_bh(&rcvq->lock);
168385584672SEric Dumazet 	return res;
168485584672SEric Dumazet }
168585584672SEric Dumazet 
16861da177e4SLinus Torvalds /*
16871da177e4SLinus Torvalds  *	IOCTL requests applicable to the UDP protocol
16881da177e4SLinus Torvalds  */
16891da177e4SLinus Torvalds 
udp_ioctl(struct sock * sk,int cmd,int * karg)1690e1d001faSBreno Leitao int udp_ioctl(struct sock *sk, int cmd, int *karg)
16911da177e4SLinus Torvalds {
16926516c655SStephen Hemminger 	switch (cmd) {
16931da177e4SLinus Torvalds 	case SIOCOUTQ:
16941da177e4SLinus Torvalds 	{
1695e1d001faSBreno Leitao 		*karg = sk_wmem_alloc_get(sk);
1696e1d001faSBreno Leitao 		return 0;
16971da177e4SLinus Torvalds 	}
16981da177e4SLinus Torvalds 
16991da177e4SLinus Torvalds 	case SIOCINQ:
17001da177e4SLinus Torvalds 	{
1701e1d001faSBreno Leitao 		*karg = max_t(int, 0, first_packet_length(sk));
1702e1d001faSBreno Leitao 		return 0;
17031da177e4SLinus Torvalds 	}
17041da177e4SLinus Torvalds 
17051da177e4SLinus Torvalds 	default:
17061da177e4SLinus Torvalds 		return -ENOIOCTLCMD;
17071da177e4SLinus Torvalds 	}
17086516c655SStephen Hemminger 
17096516c655SStephen Hemminger 	return 0;
17101da177e4SLinus Torvalds }
1711c482c568SEric Dumazet EXPORT_SYMBOL(udp_ioctl);
17121da177e4SLinus Torvalds 
__skb_recv_udp(struct sock * sk,unsigned int flags,int * off,int * err)17132276f58aSPaolo Abeni struct sk_buff *__skb_recv_udp(struct sock *sk, unsigned int flags,
1714ec095263SOliver Hartkopp 			       int *off, int *err)
17152276f58aSPaolo Abeni {
17162276f58aSPaolo Abeni 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
17172276f58aSPaolo Abeni 	struct sk_buff_head *queue;
17182276f58aSPaolo Abeni 	struct sk_buff *last;
17192276f58aSPaolo Abeni 	long timeo;
17202276f58aSPaolo Abeni 	int error;
17212276f58aSPaolo Abeni 
17222276f58aSPaolo Abeni 	queue = &udp_sk(sk)->reader_queue;
17232276f58aSPaolo Abeni 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
17242276f58aSPaolo Abeni 	do {
17252276f58aSPaolo Abeni 		struct sk_buff *skb;
17262276f58aSPaolo Abeni 
17272276f58aSPaolo Abeni 		error = sock_error(sk);
17282276f58aSPaolo Abeni 		if (error)
17292276f58aSPaolo Abeni 			break;
17302276f58aSPaolo Abeni 
17312276f58aSPaolo Abeni 		error = -EAGAIN;
17322276f58aSPaolo Abeni 		do {
17332276f58aSPaolo Abeni 			spin_lock_bh(&queue->lock);
1734e427cad6SPaolo Abeni 			skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1735e427cad6SPaolo Abeni 							err, &last);
17362276f58aSPaolo Abeni 			if (skb) {
1737e427cad6SPaolo Abeni 				if (!(flags & MSG_PEEK))
1738e427cad6SPaolo Abeni 					udp_skb_destructor(sk, skb);
17392276f58aSPaolo Abeni 				spin_unlock_bh(&queue->lock);
17402276f58aSPaolo Abeni 				return skb;
17412276f58aSPaolo Abeni 			}
17422276f58aSPaolo Abeni 
1743137a0dbeSEric Dumazet 			if (skb_queue_empty_lockless(sk_queue)) {
17442276f58aSPaolo Abeni 				spin_unlock_bh(&queue->lock);
17452276f58aSPaolo Abeni 				goto busy_check;
17462276f58aSPaolo Abeni 			}
17472276f58aSPaolo Abeni 
17486dfb4367SPaolo Abeni 			/* refill the reader queue and walk it again
17496dfb4367SPaolo Abeni 			 * keep both queues locked to avoid re-acquiring
17506dfb4367SPaolo Abeni 			 * the sk_receive_queue lock if fwd memory scheduling
17516dfb4367SPaolo Abeni 			 * is needed.
17526dfb4367SPaolo Abeni 			 */
17532276f58aSPaolo Abeni 			spin_lock(&sk_queue->lock);
17542276f58aSPaolo Abeni 			skb_queue_splice_tail_init(sk_queue, queue);
17552276f58aSPaolo Abeni 
1756e427cad6SPaolo Abeni 			skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1757e427cad6SPaolo Abeni 							err, &last);
1758e427cad6SPaolo Abeni 			if (skb && !(flags & MSG_PEEK))
1759e427cad6SPaolo Abeni 				udp_skb_dtor_locked(sk, skb);
17606dfb4367SPaolo Abeni 			spin_unlock(&sk_queue->lock);
17612276f58aSPaolo Abeni 			spin_unlock_bh(&queue->lock);
1762de321ed3SAndrey Vagin 			if (skb)
17632276f58aSPaolo Abeni 				return skb;
17642276f58aSPaolo Abeni 
17652276f58aSPaolo Abeni busy_check:
17662276f58aSPaolo Abeni 			if (!sk_can_busy_loop(sk))
17672276f58aSPaolo Abeni 				break;
17682276f58aSPaolo Abeni 
17692276f58aSPaolo Abeni 			sk_busy_loop(sk, flags & MSG_DONTWAIT);
1770137a0dbeSEric Dumazet 		} while (!skb_queue_empty_lockless(sk_queue));
17712276f58aSPaolo Abeni 
17722276f58aSPaolo Abeni 		/* sk_queue is empty, reader_queue may contain peeked packets */
17732276f58aSPaolo Abeni 	} while (timeo &&
1774b50b0580SSabrina Dubroca 		 !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,
1775b50b0580SSabrina Dubroca 					      &error, &timeo,
17762276f58aSPaolo Abeni 					      (struct sk_buff *)sk_queue));
17772276f58aSPaolo Abeni 
17782276f58aSPaolo Abeni 	*err = error;
17792276f58aSPaolo Abeni 	return NULL;
17802276f58aSPaolo Abeni }
17817e823644SJiri Kosina EXPORT_SYMBOL(__skb_recv_udp);
17822276f58aSPaolo Abeni 
udp_read_skb(struct sock * sk,skb_read_actor_t recv_actor)1783965b57b4SCong Wang int udp_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
1784d7f57118SCong Wang {
1785d7f57118SCong Wang 	struct sk_buff *skb;
178678fa0d61SJohn Fastabend 	int err;
1787d7f57118SCong Wang 
178831f1fbcbSPeilin Ye try_again:
1789ec095263SOliver Hartkopp 	skb = skb_recv_udp(sk, MSG_DONTWAIT, &err);
1790d7f57118SCong Wang 	if (!skb)
1791d7f57118SCong Wang 		return err;
1792099f896fSCong Wang 
1793099f896fSCong Wang 	if (udp_lib_checksum_complete(skb)) {
179431f1fbcbSPeilin Ye 		int is_udplite = IS_UDPLITE(sk);
179531f1fbcbSPeilin Ye 		struct net *net = sock_net(sk);
179631f1fbcbSPeilin Ye 
179731f1fbcbSPeilin Ye 		__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, is_udplite);
179831f1fbcbSPeilin Ye 		__UDP_INC_STATS(net, UDP_MIB_INERRORS, is_udplite);
1799099f896fSCong Wang 		atomic_inc(&sk->sk_drops);
1800099f896fSCong Wang 		kfree_skb(skb);
180131f1fbcbSPeilin Ye 		goto try_again;
1802099f896fSCong Wang 	}
1803099f896fSCong Wang 
1804db39dfdcSPeilin Ye 	WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk));
180578fa0d61SJohn Fastabend 	return recv_actor(sk, skb);
1806d7f57118SCong Wang }
1807965b57b4SCong Wang EXPORT_SYMBOL(udp_read_skb);
1808d7f57118SCong Wang 
1809db8dac20SDavid S. Miller /*
1810db8dac20SDavid S. Miller  * 	This should be easy, if there is something there we
1811db8dac20SDavid S. Miller  * 	return it, otherwise we block.
1812db8dac20SDavid S. Miller  */
1813db8dac20SDavid S. Miller 
udp_recvmsg(struct sock * sk,struct msghdr * msg,size_t len,int flags,int * addr_len)1814ec095263SOliver Hartkopp int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags,
1815ec095263SOliver Hartkopp 		int *addr_len)
1816db8dac20SDavid S. Miller {
1817db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sk);
1818342dfc30SSteffen Hurrle 	DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
1819db8dac20SDavid S. Miller 	struct sk_buff *skb;
182059c2cdaeSDavid S. Miller 	unsigned int ulen, copied;
1821fd69c399SPaolo Abeni 	int off, err, peeking = flags & MSG_PEEK;
1822db8dac20SDavid S. Miller 	int is_udplite = IS_UDPLITE(sk);
1823197c949eSEric Dumazet 	bool checksum_valid = false;
1824db8dac20SDavid S. Miller 
1825db8dac20SDavid S. Miller 	if (flags & MSG_ERRQUEUE)
182685fbaa75SHannes Frederic Sowa 		return ip_recv_error(sk, msg, len, addr_len);
1827db8dac20SDavid S. Miller 
1828db8dac20SDavid S. Miller try_again:
1829a0917e0bSMatthew Dawson 	off = sk_peek_offset(sk, flags);
1830ec095263SOliver Hartkopp 	skb = __skb_recv_udp(sk, flags, &off, &err);
1831db8dac20SDavid S. Miller 	if (!skb)
1832627d2d6bSsamanthakumar 		return err;
1833db8dac20SDavid S. Miller 
1834b65ac446SPaolo Abeni 	ulen = udp_skb_len(skb);
183559c2cdaeSDavid S. Miller 	copied = len;
1836627d2d6bSsamanthakumar 	if (copied > ulen - off)
1837627d2d6bSsamanthakumar 		copied = ulen - off;
183859c2cdaeSDavid S. Miller 	else if (copied < ulen)
1839db8dac20SDavid S. Miller 		msg->msg_flags |= MSG_TRUNC;
1840db8dac20SDavid S. Miller 
1841db8dac20SDavid S. Miller 	/*
1842db8dac20SDavid S. Miller 	 * If checksum is needed at all, try to do it while copying the
1843db8dac20SDavid S. Miller 	 * data.  If the data is truncated, or if we only want a partial
1844db8dac20SDavid S. Miller 	 * coverage checksum (UDP-Lite), do it before the copy.
1845db8dac20SDavid S. Miller 	 */
1846db8dac20SDavid S. Miller 
1847d21dbdfeSEric Dumazet 	if (copied < ulen || peeking ||
1848d21dbdfeSEric Dumazet 	    (is_udplite && UDP_SKB_CB(skb)->partial_cov)) {
1849b65ac446SPaolo Abeni 		checksum_valid = udp_skb_csum_unnecessary(skb) ||
1850b65ac446SPaolo Abeni 				!__udp_lib_checksum_complete(skb);
1851197c949eSEric Dumazet 		if (!checksum_valid)
1852db8dac20SDavid S. Miller 			goto csum_copy_err;
1853db8dac20SDavid S. Miller 	}
1854db8dac20SDavid S. Miller 
1855b65ac446SPaolo Abeni 	if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
1856b65ac446SPaolo Abeni 		if (udp_skb_is_linear(skb))
1857b65ac446SPaolo Abeni 			err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
1858b65ac446SPaolo Abeni 		else
1859627d2d6bSsamanthakumar 			err = skb_copy_datagram_msg(skb, off, msg, copied);
1860b65ac446SPaolo Abeni 	} else {
1861627d2d6bSsamanthakumar 		err = skb_copy_and_csum_datagram_msg(skb, off, msg);
1862db8dac20SDavid S. Miller 
1863db8dac20SDavid S. Miller 		if (err == -EINVAL)
1864db8dac20SDavid S. Miller 			goto csum_copy_err;
1865db8dac20SDavid S. Miller 	}
1866db8dac20SDavid S. Miller 
186722911fc5SEric Dumazet 	if (unlikely(err)) {
1868fd69c399SPaolo Abeni 		if (!peeking) {
1869979402b1SEric Dumazet 			atomic_inc(&sk->sk_drops);
18706aef70a8SEric Dumazet 			UDP_INC_STATS(sock_net(sk),
1871979402b1SEric Dumazet 				      UDP_MIB_INERRORS, is_udplite);
1872979402b1SEric Dumazet 		}
1873850cbaddSPaolo Abeni 		kfree_skb(skb);
1874627d2d6bSsamanthakumar 		return err;
187522911fc5SEric Dumazet 	}
1876db8dac20SDavid S. Miller 
1877fd69c399SPaolo Abeni 	if (!peeking)
18786aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk),
1879629ca23cSPavel Emelyanov 			      UDP_MIB_INDATAGRAMS, is_udplite);
1880db8dac20SDavid S. Miller 
18816fd1d51cSErin MacNeil 	sock_recv_cmsgs(msg, sk, skb);
1882db8dac20SDavid S. Miller 
1883db8dac20SDavid S. Miller 	/* Copy the address. */
1884c482c568SEric Dumazet 	if (sin) {
1885db8dac20SDavid S. Miller 		sin->sin_family = AF_INET;
1886db8dac20SDavid S. Miller 		sin->sin_port = udp_hdr(skb)->source;
1887db8dac20SDavid S. Miller 		sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
1888db8dac20SDavid S. Miller 		memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
1889bceaa902SHannes Frederic Sowa 		*addr_len = sizeof(*sin);
1890983695faSDaniel Borkmann 
1891983695faSDaniel Borkmann 		BPF_CGROUP_RUN_PROG_UDP4_RECVMSG_LOCK(sk,
1892fefba7d1SDaan De Meyer 						      (struct sockaddr *)sin,
1893fefba7d1SDaan De Meyer 						      addr_len);
1894db8dac20SDavid S. Miller 	}
1895bcd1665eSPaolo Abeni 
1896e1dc0615SEric Dumazet 	if (udp_test_bit(GRO_ENABLED, sk))
1897bcd1665eSPaolo Abeni 		udp_cmsg_recv(msg, sk, skb);
1898bcd1665eSPaolo Abeni 
1899c274af22SEric Dumazet 	if (inet_cmsg_flags(inet))
1900ad959036SPaolo Abeni 		ip_cmsg_recv_offset(msg, sk, skb, sizeof(struct udphdr), off);
1901db8dac20SDavid S. Miller 
190259c2cdaeSDavid S. Miller 	err = copied;
1903db8dac20SDavid S. Miller 	if (flags & MSG_TRUNC)
1904db8dac20SDavid S. Miller 		err = ulen;
1905db8dac20SDavid S. Miller 
1906850cbaddSPaolo Abeni 	skb_consume_udp(sk, skb, peeking ? -err : err);
1907db8dac20SDavid S. Miller 	return err;
1908db8dac20SDavid S. Miller 
1909db8dac20SDavid S. Miller csum_copy_err:
19102276f58aSPaolo Abeni 	if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags,
19112276f58aSPaolo Abeni 				 udp_skb_destructor)) {
19126aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
19136aef70a8SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
19146a5dc9e5SEric Dumazet 	}
1915850cbaddSPaolo Abeni 	kfree_skb(skb);
1916db8dac20SDavid S. Miller 
1917beb39db5SEric Dumazet 	/* starting over for a new packet, but check if we need to yield */
1918beb39db5SEric Dumazet 	cond_resched();
19199cfaa8deSXufeng Zhang 	msg->msg_flags &= ~MSG_TRUNC;
1920db8dac20SDavid S. Miller 	goto try_again;
1921db8dac20SDavid S. Miller }
1922db8dac20SDavid S. Miller 
udp_pre_connect(struct sock * sk,struct sockaddr * uaddr,int addr_len)1923d74bad4eSAndrey Ignatov int udp_pre_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
1924d74bad4eSAndrey Ignatov {
1925d74bad4eSAndrey Ignatov 	/* This check is replicated from __ip4_datagram_connect() and
1926d74bad4eSAndrey Ignatov 	 * intended to prevent BPF program called below from accessing bytes
1927d74bad4eSAndrey Ignatov 	 * that are out of the bound specified by user in addr_len.
1928d74bad4eSAndrey Ignatov 	 */
1929d74bad4eSAndrey Ignatov 	if (addr_len < sizeof(struct sockaddr_in))
1930d74bad4eSAndrey Ignatov 		return -EINVAL;
1931d74bad4eSAndrey Ignatov 
1932fefba7d1SDaan De Meyer 	return BPF_CGROUP_RUN_PROG_INET4_CONNECT_LOCK(sk, uaddr, &addr_len);
1933d74bad4eSAndrey Ignatov }
1934d74bad4eSAndrey Ignatov EXPORT_SYMBOL(udp_pre_connect);
1935d74bad4eSAndrey Ignatov 
__udp_disconnect(struct sock * sk,int flags)1936286c72deSEric Dumazet int __udp_disconnect(struct sock *sk, int flags)
19371da177e4SLinus Torvalds {
19381da177e4SLinus Torvalds 	struct inet_sock *inet = inet_sk(sk);
19391da177e4SLinus Torvalds 	/*
19401da177e4SLinus Torvalds 	 *	1003.1g - break association.
19411da177e4SLinus Torvalds 	 */
19421da177e4SLinus Torvalds 
19431da177e4SLinus Torvalds 	sk->sk_state = TCP_CLOSE;
1944c720c7e8SEric Dumazet 	inet->inet_daddr = 0;
1945c720c7e8SEric Dumazet 	inet->inet_dport = 0;
1946bdeab991STom Herbert 	sock_rps_reset_rxhash(sk);
19471da177e4SLinus Torvalds 	sk->sk_bound_dev_if = 0;
1948303d0403SWillem de Bruijn 	if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) {
19491da177e4SLinus Torvalds 		inet_reset_saddr(sk);
1950303d0403SWillem de Bruijn 		if (sk->sk_prot->rehash &&
1951303d0403SWillem de Bruijn 		    (sk->sk_userlocks & SOCK_BINDPORT_LOCK))
1952303d0403SWillem de Bruijn 			sk->sk_prot->rehash(sk);
1953303d0403SWillem de Bruijn 	}
19541da177e4SLinus Torvalds 
19551da177e4SLinus Torvalds 	if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
19561da177e4SLinus Torvalds 		sk->sk_prot->unhash(sk);
1957c720c7e8SEric Dumazet 		inet->inet_sport = 0;
19581da177e4SLinus Torvalds 	}
19591da177e4SLinus Torvalds 	sk_dst_reset(sk);
19601da177e4SLinus Torvalds 	return 0;
19611da177e4SLinus Torvalds }
1962286c72deSEric Dumazet EXPORT_SYMBOL(__udp_disconnect);
1963286c72deSEric Dumazet 
udp_disconnect(struct sock * sk,int flags)1964286c72deSEric Dumazet int udp_disconnect(struct sock *sk, int flags)
1965286c72deSEric Dumazet {
1966286c72deSEric Dumazet 	lock_sock(sk);
1967286c72deSEric Dumazet 	__udp_disconnect(sk, flags);
1968286c72deSEric Dumazet 	release_sock(sk);
1969286c72deSEric Dumazet 	return 0;
1970286c72deSEric Dumazet }
1971c482c568SEric Dumazet EXPORT_SYMBOL(udp_disconnect);
19721da177e4SLinus Torvalds 
udp_lib_unhash(struct sock * sk)1973645ca708SEric Dumazet void udp_lib_unhash(struct sock *sk)
1974645ca708SEric Dumazet {
1975723b4610SEric Dumazet 	if (sk_hashed(sk)) {
197667fb4330SKuniyuki Iwashima 		struct udp_table *udptable = udp_get_table_prot(sk);
1977512615b6SEric Dumazet 		struct udp_hslot *hslot, *hslot2;
1978512615b6SEric Dumazet 
1979512615b6SEric Dumazet 		hslot  = udp_hashslot(udptable, sock_net(sk),
1980d4cada4aSEric Dumazet 				      udp_sk(sk)->udp_port_hash);
1981512615b6SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
1982645ca708SEric Dumazet 
1983c8db3fecSEric Dumazet 		spin_lock_bh(&hslot->lock);
1984e32ea7e7SCraig Gallek 		if (rcu_access_pointer(sk->sk_reuseport_cb))
1985e32ea7e7SCraig Gallek 			reuseport_detach_sock(sk);
1986ca065d0cSEric Dumazet 		if (sk_del_node_init_rcu(sk)) {
1987fdcc8aa9SEric Dumazet 			hslot->count--;
1988c720c7e8SEric Dumazet 			inet_sk(sk)->inet_num = 0;
1989645ca708SEric Dumazet 			sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
1990512615b6SEric Dumazet 
1991512615b6SEric Dumazet 			spin_lock(&hslot2->lock);
1992ca065d0cSEric Dumazet 			hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
1993512615b6SEric Dumazet 			hslot2->count--;
1994512615b6SEric Dumazet 			spin_unlock(&hslot2->lock);
1995645ca708SEric Dumazet 		}
1996c8db3fecSEric Dumazet 		spin_unlock_bh(&hslot->lock);
1997645ca708SEric Dumazet 	}
1998723b4610SEric Dumazet }
1999645ca708SEric Dumazet EXPORT_SYMBOL(udp_lib_unhash);
2000645ca708SEric Dumazet 
2001719f8358SEric Dumazet /*
2002719f8358SEric Dumazet  * inet_rcv_saddr was changed, we must rehash secondary hash
2003719f8358SEric Dumazet  */
udp_lib_rehash(struct sock * sk,u16 newhash)2004719f8358SEric Dumazet void udp_lib_rehash(struct sock *sk, u16 newhash)
2005719f8358SEric Dumazet {
2006719f8358SEric Dumazet 	if (sk_hashed(sk)) {
200767fb4330SKuniyuki Iwashima 		struct udp_table *udptable = udp_get_table_prot(sk);
2008719f8358SEric Dumazet 		struct udp_hslot *hslot, *hslot2, *nhslot2;
2009719f8358SEric Dumazet 
2010719f8358SEric Dumazet 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
2011719f8358SEric Dumazet 		nhslot2 = udp_hashslot2(udptable, newhash);
2012719f8358SEric Dumazet 		udp_sk(sk)->udp_portaddr_hash = newhash;
2013e32ea7e7SCraig Gallek 
2014e32ea7e7SCraig Gallek 		if (hslot2 != nhslot2 ||
2015e32ea7e7SCraig Gallek 		    rcu_access_pointer(sk->sk_reuseport_cb)) {
2016719f8358SEric Dumazet 			hslot = udp_hashslot(udptable, sock_net(sk),
2017719f8358SEric Dumazet 					     udp_sk(sk)->udp_port_hash);
2018719f8358SEric Dumazet 			/* we must lock primary chain too */
2019719f8358SEric Dumazet 			spin_lock_bh(&hslot->lock);
2020e32ea7e7SCraig Gallek 			if (rcu_access_pointer(sk->sk_reuseport_cb))
2021e32ea7e7SCraig Gallek 				reuseport_detach_sock(sk);
2022719f8358SEric Dumazet 
2023e32ea7e7SCraig Gallek 			if (hslot2 != nhslot2) {
2024719f8358SEric Dumazet 				spin_lock(&hslot2->lock);
2025ca065d0cSEric Dumazet 				hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
2026719f8358SEric Dumazet 				hslot2->count--;
2027719f8358SEric Dumazet 				spin_unlock(&hslot2->lock);
2028719f8358SEric Dumazet 
2029719f8358SEric Dumazet 				spin_lock(&nhslot2->lock);
2030ca065d0cSEric Dumazet 				hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
2031719f8358SEric Dumazet 							 &nhslot2->head);
2032719f8358SEric Dumazet 				nhslot2->count++;
2033719f8358SEric Dumazet 				spin_unlock(&nhslot2->lock);
2034e32ea7e7SCraig Gallek 			}
2035719f8358SEric Dumazet 
2036719f8358SEric Dumazet 			spin_unlock_bh(&hslot->lock);
2037719f8358SEric Dumazet 		}
2038719f8358SEric Dumazet 	}
2039719f8358SEric Dumazet }
2040719f8358SEric Dumazet EXPORT_SYMBOL(udp_lib_rehash);
2041719f8358SEric Dumazet 
udp_v4_rehash(struct sock * sk)20428f6b5392SAlexey Kodanev void udp_v4_rehash(struct sock *sk)
2043719f8358SEric Dumazet {
2044f0b1e64cSMartin KaFai Lau 	u16 new_hash = ipv4_portaddr_hash(sock_net(sk),
2045719f8358SEric Dumazet 					  inet_sk(sk)->inet_rcv_saddr,
2046719f8358SEric Dumazet 					  inet_sk(sk)->inet_num);
2047719f8358SEric Dumazet 	udp_lib_rehash(sk, new_hash);
2048719f8358SEric Dumazet }
2049719f8358SEric Dumazet 
__udp_queue_rcv_skb(struct sock * sk,struct sk_buff * skb)2050a3f96c47SPaolo Abeni static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
205193821778SHerbert Xu {
2052fec5e652STom Herbert 	int rc;
205393821778SHerbert Xu 
2054005ec974SShawn Bohrer 	if (inet_sk(sk)->inet_daddr) {
2055bdeab991STom Herbert 		sock_rps_save_rxhash(sk, skb);
2056005ec974SShawn Bohrer 		sk_mark_napi_id(sk, skb);
20572c8c56e1SEric Dumazet 		sk_incoming_cpu_update(sk);
2058e68b6e50SEric Dumazet 	} else {
2059e68b6e50SEric Dumazet 		sk_mark_napi_id_once(sk, skb);
2060005ec974SShawn Bohrer 	}
2061fec5e652STom Herbert 
2062850cbaddSPaolo Abeni 	rc = __udp_enqueue_schedule_skb(sk, skb);
2063766e9037SEric Dumazet 	if (rc < 0) {
2064766e9037SEric Dumazet 		int is_udplite = IS_UDPLITE(sk);
206508d4c037SMenglong Dong 		int drop_reason;
2066766e9037SEric Dumazet 
206793821778SHerbert Xu 		/* Note that an ENOMEM error is charged twice */
206808d4c037SMenglong Dong 		if (rc == -ENOMEM) {
2069e61da9e2SEric Dumazet 			UDP_INC_STATS(sock_net(sk), UDP_MIB_RCVBUFERRORS,
207093821778SHerbert Xu 					is_udplite);
207108d4c037SMenglong Dong 			drop_reason = SKB_DROP_REASON_SOCKET_RCVBUFF;
207208d4c037SMenglong Dong 		} else {
2073a3ce2b10SMenglong Dong 			UDP_INC_STATS(sock_net(sk), UDP_MIB_MEMERRORS,
2074a3ce2b10SMenglong Dong 				      is_udplite);
207508d4c037SMenglong Dong 			drop_reason = SKB_DROP_REASON_PROTO_MEM;
207608d4c037SMenglong Dong 		}
2077e61da9e2SEric Dumazet 		UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
2078e9669a00SBalazs Scheidler 		trace_udp_fail_queue_rcv_skb(rc, sk, skb);
2079fc0cc924SYan Zhai 		sk_skb_reason_drop(sk, skb, drop_reason);
2080766e9037SEric Dumazet 		return -1;
208193821778SHerbert Xu 	}
208293821778SHerbert Xu 
208393821778SHerbert Xu 	return 0;
208493821778SHerbert Xu }
208593821778SHerbert Xu 
2086db8dac20SDavid S. Miller /* returns:
2087db8dac20SDavid S. Miller  *  -1: error
2088db8dac20SDavid S. Miller  *   0: success
2089db8dac20SDavid S. Miller  *  >0: "udp encap" protocol resubmission
2090db8dac20SDavid S. Miller  *
2091db8dac20SDavid S. Miller  * Note that in the success and error cases, the skb is assumed to
2092db8dac20SDavid S. Miller  * have either been requeued or freed.
2093db8dac20SDavid S. Miller  */
udp_queue_rcv_one_skb(struct sock * sk,struct sk_buff * skb)2094cf329aa4SPaolo Abeni static int udp_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
2095db8dac20SDavid S. Miller {
20961379a92dSMenglong Dong 	int drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2097db8dac20SDavid S. Miller 	struct udp_sock *up = udp_sk(sk);
2098db8dac20SDavid S. Miller 	int is_udplite = IS_UDPLITE(sk);
2099db8dac20SDavid S. Miller 
2100db8dac20SDavid S. Miller 	/*
2101db8dac20SDavid S. Miller 	 *	Charge it to the socket, dropping if the queue is full.
2102db8dac20SDavid S. Miller 	 */
21031379a92dSMenglong Dong 	if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
21041379a92dSMenglong Dong 		drop_reason = SKB_DROP_REASON_XFRM_POLICY;
2105db8dac20SDavid S. Miller 		goto drop;
21061379a92dSMenglong Dong 	}
2107895b5c9fSFlorian Westphal 	nf_reset_ct(skb);
2108db8dac20SDavid S. Miller 
210970a36f57SEric Dumazet 	if (static_branch_unlikely(&udp_encap_needed_key) &&
211070a36f57SEric Dumazet 	    READ_ONCE(up->encap_type)) {
21110ad92ad0SEric Dumazet 		int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
21120ad92ad0SEric Dumazet 
2113db8dac20SDavid S. Miller 		/*
2114db8dac20SDavid S. Miller 		 * This is an encapsulation socket so pass the skb to
2115db8dac20SDavid S. Miller 		 * the socket's udp_encap_rcv() hook. Otherwise, just
2116db8dac20SDavid S. Miller 		 * fall through and pass this up the UDP socket.
2117db8dac20SDavid S. Miller 		 * up->encap_rcv() returns the following value:
2118db8dac20SDavid S. Miller 		 * =0 if skb was successfully passed to the encap
2119db8dac20SDavid S. Miller 		 *    handler or was discarded by it.
2120db8dac20SDavid S. Miller 		 * >0 if skb should be passed on to UDP.
2121db8dac20SDavid S. Miller 		 * <0 if skb should be resubmitted as proto -N
2122db8dac20SDavid S. Miller 		 */
2123db8dac20SDavid S. Miller 
2124db8dac20SDavid S. Miller 		/* if we're overly short, let UDP handle it */
21256aa7de05SMark Rutland 		encap_rcv = READ_ONCE(up->encap_rcv);
2126e5aed006SHannes Frederic Sowa 		if (encap_rcv) {
2127db8dac20SDavid S. Miller 			int ret;
2128db8dac20SDavid S. Miller 
21290a80966bSTom Herbert 			/* Verify checksum before giving to encap */
21300a80966bSTom Herbert 			if (udp_lib_checksum_complete(skb))
21310a80966bSTom Herbert 				goto csum_error;
21320a80966bSTom Herbert 
21330ad92ad0SEric Dumazet 			ret = encap_rcv(sk, skb);
2134db8dac20SDavid S. Miller 			if (ret <= 0) {
213502c22347SEric Dumazet 				__UDP_INC_STATS(sock_net(sk),
21360283328eSPavel Emelyanov 						UDP_MIB_INDATAGRAMS,
2137db8dac20SDavid S. Miller 						is_udplite);
2138db8dac20SDavid S. Miller 				return -ret;
2139db8dac20SDavid S. Miller 			}
2140db8dac20SDavid S. Miller 		}
2141db8dac20SDavid S. Miller 
2142db8dac20SDavid S. Miller 		/* FALLTHROUGH -- it's a UDP Packet */
2143db8dac20SDavid S. Miller 	}
2144db8dac20SDavid S. Miller 
2145db8dac20SDavid S. Miller 	/*
2146db8dac20SDavid S. Miller 	 * 	UDP-Lite specific tests, ignored on UDP sockets
2147db8dac20SDavid S. Miller 	 */
2148882af43aSEric Dumazet 	if (udp_test_bit(UDPLITE_RECV_CC, sk) && UDP_SKB_CB(skb)->partial_cov) {
2149882af43aSEric Dumazet 		u16 pcrlen = READ_ONCE(up->pcrlen);
2150db8dac20SDavid S. Miller 
2151db8dac20SDavid S. Miller 		/*
2152db8dac20SDavid S. Miller 		 * MIB statistics other than incrementing the error count are
2153db8dac20SDavid S. Miller 		 * disabled for the following two types of errors: these depend
2154db8dac20SDavid S. Miller 		 * on the application settings, not on the functioning of the
2155db8dac20SDavid S. Miller 		 * protocol stack as such.
2156db8dac20SDavid S. Miller 		 *
2157db8dac20SDavid S. Miller 		 * RFC 3828 here recommends (sec 3.3): "There should also be a
2158db8dac20SDavid S. Miller 		 * way ... to ... at least let the receiving application block
2159db8dac20SDavid S. Miller 		 * delivery of packets with coverage values less than a value
2160db8dac20SDavid S. Miller 		 * provided by the application."
2161db8dac20SDavid S. Miller 		 */
2162882af43aSEric Dumazet 		if (pcrlen == 0) {          /* full coverage was set  */
2163ba7a46f1SJoe Perches 			net_dbg_ratelimited("UDPLite: partial coverage %d while full coverage %d requested\n",
2164db8dac20SDavid S. Miller 					    UDP_SKB_CB(skb)->cscov, skb->len);
2165db8dac20SDavid S. Miller 			goto drop;
2166db8dac20SDavid S. Miller 		}
2167db8dac20SDavid S. Miller 		/* The next case involves violating the min. coverage requested
2168db8dac20SDavid S. Miller 		 * by the receiver. This is subtle: if receiver wants x and x is
2169db8dac20SDavid S. Miller 		 * greater than the buffersize/MTU then receiver will complain
2170db8dac20SDavid S. Miller 		 * that it wants x while sender emits packets of smaller size y.
2171db8dac20SDavid S. Miller 		 * Therefore the above ...()->partial_cov statement is essential.
2172db8dac20SDavid S. Miller 		 */
2173882af43aSEric Dumazet 		if (UDP_SKB_CB(skb)->cscov < pcrlen) {
2174ba7a46f1SJoe Perches 			net_dbg_ratelimited("UDPLite: coverage %d too small, need min %d\n",
2175882af43aSEric Dumazet 					    UDP_SKB_CB(skb)->cscov, pcrlen);
2176db8dac20SDavid S. Miller 			goto drop;
2177db8dac20SDavid S. Miller 		}
2178db8dac20SDavid S. Miller 	}
2179db8dac20SDavid S. Miller 
2180dd99e425SPaolo Abeni 	prefetch(&sk->sk_rmem_alloc);
2181ce25d66aSEric Dumazet 	if (rcu_access_pointer(sk->sk_filter) &&
2182ce25d66aSEric Dumazet 	    udp_lib_checksum_complete(skb))
21836a5dc9e5SEric Dumazet 			goto csum_error;
2184ce25d66aSEric Dumazet 
21851379a92dSMenglong Dong 	if (sk_filter_trim_cap(sk, skb, sizeof(struct udphdr))) {
21861379a92dSMenglong Dong 		drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
2187a6127697SMichal Kubeček 		goto drop;
21881379a92dSMenglong Dong 	}
2189db8dac20SDavid S. Miller 
2190e6afc8acSsamanthakumar 	udp_csum_pull_header(skb);
2191db8dac20SDavid S. Miller 
2192e622502cSNicolas Dichtel 	ipv4_pktinfo_prepare(sk, skb, true);
2193850cbaddSPaolo Abeni 	return __udp_queue_rcv_skb(sk, skb);
2194db8dac20SDavid S. Miller 
21956a5dc9e5SEric Dumazet csum_error:
21961379a92dSMenglong Dong 	drop_reason = SKB_DROP_REASON_UDP_CSUM;
219702c22347SEric Dumazet 	__UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
2198db8dac20SDavid S. Miller drop:
219902c22347SEric Dumazet 	__UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
22008edf19c2SEric Dumazet 	atomic_inc(&sk->sk_drops);
2201fc0cc924SYan Zhai 	sk_skb_reason_drop(sk, skb, drop_reason);
2202db8dac20SDavid S. Miller 	return -1;
2203db8dac20SDavid S. Miller }
2204db8dac20SDavid S. Miller 
udp_queue_rcv_skb(struct sock * sk,struct sk_buff * skb)2205cf329aa4SPaolo Abeni static int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2206cf329aa4SPaolo Abeni {
2207cf329aa4SPaolo Abeni 	struct sk_buff *next, *segs;
2208cf329aa4SPaolo Abeni 	int ret;
2209cf329aa4SPaolo Abeni 
2210cf329aa4SPaolo Abeni 	if (likely(!udp_unexpected_gso(sk, skb)))
2211cf329aa4SPaolo Abeni 		return udp_queue_rcv_one_skb(sk, skb);
2212cf329aa4SPaolo Abeni 
2213a08e7fd9SCambda Zhu 	BUILD_BUG_ON(sizeof(struct udp_skb_cb) > SKB_GSO_CB_OFFSET);
2214cf329aa4SPaolo Abeni 	__skb_push(skb, -skb_mac_offset(skb));
2215cf329aa4SPaolo Abeni 	segs = udp_rcv_segment(sk, skb, true);
22161a186c14SJason A. Donenfeld 	skb_list_walk_safe(segs, skb, next) {
2217cf329aa4SPaolo Abeni 		__skb_pull(skb, skb_transport_offset(skb));
2218000ac44dSPaolo Abeni 
2219000ac44dSPaolo Abeni 		udp_post_segment_fix_csum(skb);
2220cf329aa4SPaolo Abeni 		ret = udp_queue_rcv_one_skb(sk, skb);
2221cf329aa4SPaolo Abeni 		if (ret > 0)
222210c678bdSXin Long 			ip_protocol_deliver_rcu(dev_net(skb->dev), skb, ret);
2223cf329aa4SPaolo Abeni 	}
2224cf329aa4SPaolo Abeni 	return 0;
2225cf329aa4SPaolo Abeni }
2226cf329aa4SPaolo Abeni 
222797502231SEric Dumazet /* For TCP sockets, sk_rx_dst is protected by socket lock
2228e47eb5dfSEric Dumazet  * For UDP, we use xchg() to guard against concurrent changes.
222997502231SEric Dumazet  */
udp_sk_rx_dst_set(struct sock * sk,struct dst_entry * dst)223064f0f5d1SPaolo Abeni bool udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
2231421b3885SShawn Bohrer {
223297502231SEric Dumazet 	struct dst_entry *old;
2233421b3885SShawn Bohrer 
2234d24406c8SWei Wang 	if (dst_hold_safe(dst)) {
2235b4cb4a13SEric Dumazet 		old = unrcu_pointer(xchg(&sk->sk_rx_dst, RCU_INITIALIZER(dst)));
223697502231SEric Dumazet 		dst_release(old);
223764f0f5d1SPaolo Abeni 		return old != dst;
223897502231SEric Dumazet 	}
223964f0f5d1SPaolo Abeni 	return false;
2240d24406c8SWei Wang }
2241c9f2c1aeSPaolo Abeni EXPORT_SYMBOL(udp_sk_rx_dst_set);
2242421b3885SShawn Bohrer 
2243db8dac20SDavid S. Miller /*
2244db8dac20SDavid S. Miller  *	Multicasts and broadcasts go to each listener.
2245db8dac20SDavid S. Miller  *
22461240d137SEric Dumazet  *	Note: called only from the BH handler context.
2247db8dac20SDavid S. Miller  */
__udp4_lib_mcast_deliver(struct net * net,struct sk_buff * skb,struct udphdr * uh,__be32 saddr,__be32 daddr,struct udp_table * udptable,int proto)2248e3163493SPavel Emelyanov static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
2249db8dac20SDavid S. Miller 				    struct udphdr  *uh,
2250db8dac20SDavid S. Miller 				    __be32 saddr, __be32 daddr,
225136cbb245SRick Jones 				    struct udp_table *udptable,
225236cbb245SRick Jones 				    int proto)
2253db8dac20SDavid S. Miller {
2254ca065d0cSEric Dumazet 	struct sock *sk, *first = NULL;
22555cf3d461SDavid Held 	unsigned short hnum = ntohs(uh->dest);
22565cf3d461SDavid Held 	struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum);
22572dc41cffSDavid Held 	unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10);
2258ca065d0cSEric Dumazet 	unsigned int offset = offsetof(typeof(*sk), sk_node);
2259ca065d0cSEric Dumazet 	int dif = skb->dev->ifindex;
2260fb74c277SDavid Ahern 	int sdif = inet_sdif(skb);
2261ca065d0cSEric Dumazet 	struct hlist_node *node;
2262ca065d0cSEric Dumazet 	struct sk_buff *nskb;
22632dc41cffSDavid Held 
22642dc41cffSDavid Held 	if (use_hash2) {
2265f0b1e64cSMartin KaFai Lau 		hash2_any = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum) &
226673e2d5e3SPablo Neira 			    udptable->mask;
2267f0b1e64cSMartin KaFai Lau 		hash2 = ipv4_portaddr_hash(net, daddr, hnum) & udptable->mask;
22682dc41cffSDavid Held start_lookup:
226973e2d5e3SPablo Neira 		hslot = &udptable->hash2[hash2];
22702dc41cffSDavid Held 		offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
22712dc41cffSDavid Held 	}
2272db8dac20SDavid S. Miller 
2273ca065d0cSEric Dumazet 	sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
2274ca065d0cSEric Dumazet 		if (!__udp_is_mcast_sock(net, sk, uh->dest, daddr,
2275fb74c277SDavid Ahern 					 uh->source, saddr, dif, sdif, hnum))
2276ca065d0cSEric Dumazet 			continue;
22771240d137SEric Dumazet 
2278ca065d0cSEric Dumazet 		if (!first) {
2279ca065d0cSEric Dumazet 			first = sk;
2280ca065d0cSEric Dumazet 			continue;
2281ca065d0cSEric Dumazet 		}
2282ca065d0cSEric Dumazet 		nskb = skb_clone(skb, GFP_ATOMIC);
2283ca065d0cSEric Dumazet 
2284ca065d0cSEric Dumazet 		if (unlikely(!nskb)) {
2285ca065d0cSEric Dumazet 			atomic_inc(&sk->sk_drops);
228602c22347SEric Dumazet 			__UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS,
2287ca065d0cSEric Dumazet 					IS_UDPLITE(sk));
228802c22347SEric Dumazet 			__UDP_INC_STATS(net, UDP_MIB_INERRORS,
2289ca065d0cSEric Dumazet 					IS_UDPLITE(sk));
2290ca065d0cSEric Dumazet 			continue;
2291ca065d0cSEric Dumazet 		}
2292ca065d0cSEric Dumazet 		if (udp_queue_rcv_skb(sk, nskb) > 0)
2293ca065d0cSEric Dumazet 			consume_skb(nskb);
2294ca065d0cSEric Dumazet 	}
22951240d137SEric Dumazet 
22962dc41cffSDavid Held 	/* Also lookup *:port if we are using hash2 and haven't done so yet. */
22972dc41cffSDavid Held 	if (use_hash2 && hash2 != hash2_any) {
22982dc41cffSDavid Held 		hash2 = hash2_any;
22992dc41cffSDavid Held 		goto start_lookup;
23002dc41cffSDavid Held 	}
23012dc41cffSDavid Held 
2302ca065d0cSEric Dumazet 	if (first) {
2303ca065d0cSEric Dumazet 		if (udp_queue_rcv_skb(first, skb) > 0)
2304ca065d0cSEric Dumazet 			consume_skb(skb);
23051240d137SEric Dumazet 	} else {
2306ca065d0cSEric Dumazet 		kfree_skb(skb);
230702c22347SEric Dumazet 		__UDP_INC_STATS(net, UDP_MIB_IGNOREDMULTI,
230836cbb245SRick Jones 				proto == IPPROTO_UDPLITE);
23091240d137SEric Dumazet 	}
2310db8dac20SDavid S. Miller 	return 0;
2311db8dac20SDavid S. Miller }
2312db8dac20SDavid S. Miller 
2313db8dac20SDavid S. Miller /* Initialize UDP checksum. If exited with zero value (success),
2314db8dac20SDavid S. Miller  * CHECKSUM_UNNECESSARY means, that no more checks are required.
2315666a3d6eSSu Yanjun  * Otherwise, csum completion requires checksumming packet body,
2316db8dac20SDavid S. Miller  * including udp header and folding it to skb->csum.
2317db8dac20SDavid S. Miller  */
udp4_csum_init(struct sk_buff * skb,struct udphdr * uh,int proto)2318db8dac20SDavid S. Miller static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
2319db8dac20SDavid S. Miller 				 int proto)
2320db8dac20SDavid S. Miller {
2321db8dac20SDavid S. Miller 	int err;
2322db8dac20SDavid S. Miller 
2323db8dac20SDavid S. Miller 	UDP_SKB_CB(skb)->partial_cov = 0;
2324db8dac20SDavid S. Miller 	UDP_SKB_CB(skb)->cscov = skb->len;
2325db8dac20SDavid S. Miller 
2326db8dac20SDavid S. Miller 	if (proto == IPPROTO_UDPLITE) {
2327db8dac20SDavid S. Miller 		err = udplite_checksum_init(skb, uh);
2328db8dac20SDavid S. Miller 		if (err)
2329db8dac20SDavid S. Miller 			return err;
233015f35d49SAlexey Kodanev 
233115f35d49SAlexey Kodanev 		if (UDP_SKB_CB(skb)->partial_cov) {
233215f35d49SAlexey Kodanev 			skb->csum = inet_compute_pseudo(skb, proto);
233315f35d49SAlexey Kodanev 			return 0;
233415f35d49SAlexey Kodanev 		}
2335db8dac20SDavid S. Miller 	}
2336db8dac20SDavid S. Miller 
2337b46d9f62SHannes Frederic Sowa 	/* Note, we are only interested in != 0 or == 0, thus the
2338b46d9f62SHannes Frederic Sowa 	 * force to int.
2339b46d9f62SHannes Frederic Sowa 	 */
2340db4f1be3SSean Tranchetti 	err = (__force int)skb_checksum_init_zero_check(skb, proto, uh->check,
2341ed70fcfcSTom Herbert 							inet_compute_pseudo);
2342db4f1be3SSean Tranchetti 	if (err)
2343db4f1be3SSean Tranchetti 		return err;
2344db4f1be3SSean Tranchetti 
2345db4f1be3SSean Tranchetti 	if (skb->ip_summed == CHECKSUM_COMPLETE && !skb->csum_valid) {
2346db4f1be3SSean Tranchetti 		/* If SW calculated the value, we know it's bad */
2347db4f1be3SSean Tranchetti 		if (skb->csum_complete_sw)
2348db4f1be3SSean Tranchetti 			return 1;
2349db4f1be3SSean Tranchetti 
2350db4f1be3SSean Tranchetti 		/* HW says the value is bad. Let's validate that.
2351db4f1be3SSean Tranchetti 		 * skb->csum is no longer the full packet checksum,
2352db4f1be3SSean Tranchetti 		 * so don't treat it as such.
2353db4f1be3SSean Tranchetti 		 */
2354db4f1be3SSean Tranchetti 		skb_checksum_complete_unset(skb);
2355db4f1be3SSean Tranchetti 	}
2356db4f1be3SSean Tranchetti 
2357db4f1be3SSean Tranchetti 	return 0;
2358db8dac20SDavid S. Miller }
2359db8dac20SDavid S. Miller 
23602b5a9217SPaolo Abeni /* wrapper for udp_queue_rcv_skb tacking care of csum conversion and
23612b5a9217SPaolo Abeni  * return code conversion for ip layer consumption
23622b5a9217SPaolo Abeni  */
udp_unicast_rcv_skb(struct sock * sk,struct sk_buff * skb,struct udphdr * uh)23632b5a9217SPaolo Abeni static int udp_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb,
23642b5a9217SPaolo Abeni 			       struct udphdr *uh)
23652b5a9217SPaolo Abeni {
23662b5a9217SPaolo Abeni 	int ret;
23672b5a9217SPaolo Abeni 
23682b5a9217SPaolo Abeni 	if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk))
2369e4aa33adSLi RongQing 		skb_checksum_try_convert(skb, IPPROTO_UDP, inet_compute_pseudo);
23702b5a9217SPaolo Abeni 
23712b5a9217SPaolo Abeni 	ret = udp_queue_rcv_skb(sk, skb);
23722b5a9217SPaolo Abeni 
23732b5a9217SPaolo Abeni 	/* a return value > 0 means to resubmit the input, but
23742b5a9217SPaolo Abeni 	 * it wants the return to be -protocol, or 0
23752b5a9217SPaolo Abeni 	 */
23762b5a9217SPaolo Abeni 	if (ret > 0)
23772b5a9217SPaolo Abeni 		return -ret;
23782b5a9217SPaolo Abeni 	return 0;
23792b5a9217SPaolo Abeni }
23802b5a9217SPaolo Abeni 
2381db8dac20SDavid S. Miller /*
2382db8dac20SDavid S. Miller  *	All we need to do is get the socket, and then do a checksum.
2383db8dac20SDavid S. Miller  */
2384db8dac20SDavid S. Miller 
__udp4_lib_rcv(struct sk_buff * skb,struct udp_table * udptable,int proto)2385645ca708SEric Dumazet int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
2386db8dac20SDavid S. Miller 		   int proto)
2387db8dac20SDavid S. Miller {
2388fc0cc924SYan Zhai 	struct sock *sk = NULL;
23897b5e56f9SJesper Dangaard Brouer 	struct udphdr *uh;
2390db8dac20SDavid S. Miller 	unsigned short ulen;
2391adf30907SEric Dumazet 	struct rtable *rt = skb_rtable(skb);
23922783ef23SJesper Dangaard Brouer 	__be32 saddr, daddr;
23930283328eSPavel Emelyanov 	struct net *net = dev_net(skb->dev);
239471489e21SJoe Stringer 	bool refcounted;
23951c7fab70SMenglong Dong 	int drop_reason;
23961c7fab70SMenglong Dong 
23971c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2398db8dac20SDavid S. Miller 
2399db8dac20SDavid S. Miller 	/*
2400db8dac20SDavid S. Miller 	 *  Validate the packet.
2401db8dac20SDavid S. Miller 	 */
2402db8dac20SDavid S. Miller 	if (!pskb_may_pull(skb, sizeof(struct udphdr)))
2403db8dac20SDavid S. Miller 		goto drop;		/* No space for header. */
2404db8dac20SDavid S. Miller 
24057b5e56f9SJesper Dangaard Brouer 	uh   = udp_hdr(skb);
2406db8dac20SDavid S. Miller 	ulen = ntohs(uh->len);
2407ccc2d97cSBjørn Mork 	saddr = ip_hdr(skb)->saddr;
2408ccc2d97cSBjørn Mork 	daddr = ip_hdr(skb)->daddr;
2409ccc2d97cSBjørn Mork 
2410db8dac20SDavid S. Miller 	if (ulen > skb->len)
2411db8dac20SDavid S. Miller 		goto short_packet;
2412db8dac20SDavid S. Miller 
2413db8dac20SDavid S. Miller 	if (proto == IPPROTO_UDP) {
2414db8dac20SDavid S. Miller 		/* UDP validates ulen. */
2415db8dac20SDavid S. Miller 		if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
2416db8dac20SDavid S. Miller 			goto short_packet;
2417db8dac20SDavid S. Miller 		uh = udp_hdr(skb);
2418db8dac20SDavid S. Miller 	}
2419db8dac20SDavid S. Miller 
2420db8dac20SDavid S. Miller 	if (udp4_csum_init(skb, uh, proto))
2421db8dac20SDavid S. Miller 		goto csum_error;
2422db8dac20SDavid S. Miller 
24239c02bec9SLorenz Bauer 	sk = inet_steal_sock(net, skb, sizeof(struct udphdr), saddr, uh->source, daddr, uh->dest,
24249c02bec9SLorenz Bauer 			     &refcounted, udp_ehashfn);
24259c02bec9SLorenz Bauer 	if (IS_ERR(sk))
24269c02bec9SLorenz Bauer 		goto no_sk;
24279c02bec9SLorenz Bauer 
24288afdd99aSEric Dumazet 	if (sk) {
242997502231SEric Dumazet 		struct dst_entry *dst = skb_dst(skb);
2430421b3885SShawn Bohrer 		int ret;
2431421b3885SShawn Bohrer 
24328f905c0eSEric Dumazet 		if (unlikely(rcu_dereference(sk->sk_rx_dst) != dst))
243397502231SEric Dumazet 			udp_sk_rx_dst_set(sk, dst);
2434421b3885SShawn Bohrer 
24352b5a9217SPaolo Abeni 		ret = udp_unicast_rcv_skb(sk, skb, uh);
243671489e21SJoe Stringer 		if (refcounted)
24378afdd99aSEric Dumazet 			sock_put(sk);
24382b5a9217SPaolo Abeni 		return ret;
2439c18450a5SFabian Frederick 	}
2440c18450a5SFabian Frederick 
2441db8dac20SDavid S. Miller 	if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
2442e3163493SPavel Emelyanov 		return __udp4_lib_mcast_deliver(net, skb, uh,
244336cbb245SRick Jones 						saddr, daddr, udptable, proto);
2444db8dac20SDavid S. Miller 
2445607c4aafSKOVACS Krisztian 	sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
24462b5a9217SPaolo Abeni 	if (sk)
24472b5a9217SPaolo Abeni 		return udp_unicast_rcv_skb(sk, skb, uh);
24489c02bec9SLorenz Bauer no_sk:
2449db8dac20SDavid S. Miller 	if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
2450db8dac20SDavid S. Miller 		goto drop;
2451895b5c9fSFlorian Westphal 	nf_reset_ct(skb);
2452db8dac20SDavid S. Miller 
2453db8dac20SDavid S. Miller 	/* No socket. Drop packet silently, if checksum is wrong */
2454db8dac20SDavid S. Miller 	if (udp_lib_checksum_complete(skb))
2455db8dac20SDavid S. Miller 		goto csum_error;
2456db8dac20SDavid S. Miller 
24571c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_NO_SOCKET;
245802c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
2459db8dac20SDavid S. Miller 	icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
2460db8dac20SDavid S. Miller 
2461db8dac20SDavid S. Miller 	/*
2462db8dac20SDavid S. Miller 	 * Hmm.  We got an UDP packet to a port to which we
2463db8dac20SDavid S. Miller 	 * don't wanna listen.  Ignore it.
2464db8dac20SDavid S. Miller 	 */
2465fc0cc924SYan Zhai 	sk_skb_reason_drop(sk, skb, drop_reason);
2466db8dac20SDavid S. Miller 	return 0;
2467db8dac20SDavid S. Miller 
2468db8dac20SDavid S. Miller short_packet:
24691c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_PKT_TOO_SMALL;
2470ba7a46f1SJoe Perches 	net_dbg_ratelimited("UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
2471afd46503SJoe Perches 			    proto == IPPROTO_UDPLITE ? "Lite" : "",
2472afd46503SJoe Perches 			    &saddr, ntohs(uh->source),
2473afd46503SJoe Perches 			    ulen, skb->len,
2474afd46503SJoe Perches 			    &daddr, ntohs(uh->dest));
2475db8dac20SDavid S. Miller 	goto drop;
2476db8dac20SDavid S. Miller 
2477db8dac20SDavid S. Miller csum_error:
2478db8dac20SDavid S. Miller 	/*
2479db8dac20SDavid S. Miller 	 * RFC1122: OK.  Discards the bad packet silently (as far as
2480db8dac20SDavid S. Miller 	 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
2481db8dac20SDavid S. Miller 	 */
24821c7fab70SMenglong Dong 	drop_reason = SKB_DROP_REASON_UDP_CSUM;
2483ba7a46f1SJoe Perches 	net_dbg_ratelimited("UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
2484afd46503SJoe Perches 			    proto == IPPROTO_UDPLITE ? "Lite" : "",
2485afd46503SJoe Perches 			    &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
2486db8dac20SDavid S. Miller 			    ulen);
248702c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
2488db8dac20SDavid S. Miller drop:
248902c22347SEric Dumazet 	__UDP_INC_STATS(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
2490fc0cc924SYan Zhai 	sk_skb_reason_drop(sk, skb, drop_reason);
2491db8dac20SDavid S. Miller 	return 0;
2492db8dac20SDavid S. Miller }
2493db8dac20SDavid S. Miller 
2494421b3885SShawn Bohrer /* We can only early demux multicast if there is a single matching socket.
2495421b3885SShawn Bohrer  * If more than one socket found returns NULL
2496421b3885SShawn Bohrer  */
__udp4_lib_mcast_demux_lookup(struct net * net,__be16 loc_port,__be32 loc_addr,__be16 rmt_port,__be32 rmt_addr,int dif,int sdif)2497421b3885SShawn Bohrer static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net,
2498421b3885SShawn Bohrer 						  __be16 loc_port, __be32 loc_addr,
2499421b3885SShawn Bohrer 						  __be16 rmt_port, __be32 rmt_addr,
2500fb74c277SDavid Ahern 						  int dif, int sdif)
2501421b3885SShawn Bohrer {
2502ba6aac15SKuniyuki Iwashima 	struct udp_table *udptable = net->ipv4.udp_table;
2503421b3885SShawn Bohrer 	unsigned short hnum = ntohs(loc_port);
2504919dfa0bSKuniyuki Iwashima 	struct sock *sk, *result;
2505919dfa0bSKuniyuki Iwashima 	struct udp_hslot *hslot;
2506919dfa0bSKuniyuki Iwashima 	unsigned int slot;
2507919dfa0bSKuniyuki Iwashima 
2508ba6aac15SKuniyuki Iwashima 	slot = udp_hashfn(net, hnum, udptable->mask);
2509ba6aac15SKuniyuki Iwashima 	hslot = &udptable->hash[slot];
2510421b3885SShawn Bohrer 
251163c6f81cSEric Dumazet 	/* Do not bother scanning a too big list */
251263c6f81cSEric Dumazet 	if (hslot->count > 10)
251363c6f81cSEric Dumazet 		return NULL;
251463c6f81cSEric Dumazet 
2515421b3885SShawn Bohrer 	result = NULL;
2516ca065d0cSEric Dumazet 	sk_for_each_rcu(sk, &hslot->head) {
2517ca065d0cSEric Dumazet 		if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr,
2518fb74c277SDavid Ahern 					rmt_port, rmt_addr, dif, sdif, hnum)) {
2519ca065d0cSEric Dumazet 			if (result)
2520ca065d0cSEric Dumazet 				return NULL;
2521421b3885SShawn Bohrer 			result = sk;
2522421b3885SShawn Bohrer 		}
2523421b3885SShawn Bohrer 	}
2524421b3885SShawn Bohrer 
2525421b3885SShawn Bohrer 	return result;
2526421b3885SShawn Bohrer }
2527421b3885SShawn Bohrer 
2528421b3885SShawn Bohrer /* For unicast we should only early demux connected sockets or we can
2529421b3885SShawn Bohrer  * break forwarding setups.  The chains here can be long so only check
2530421b3885SShawn Bohrer  * if the first socket is an exact match and if not move on.
2531421b3885SShawn Bohrer  */
__udp4_lib_demux_lookup(struct net * net,__be16 loc_port,__be32 loc_addr,__be16 rmt_port,__be32 rmt_addr,int dif,int sdif)2532421b3885SShawn Bohrer static struct sock *__udp4_lib_demux_lookup(struct net *net,
2533421b3885SShawn Bohrer 					    __be16 loc_port, __be32 loc_addr,
2534421b3885SShawn Bohrer 					    __be16 rmt_port, __be32 rmt_addr,
25353fa6f616SDavid Ahern 					    int dif, int sdif)
2536421b3885SShawn Bohrer {
2537ba6aac15SKuniyuki Iwashima 	struct udp_table *udptable = net->ipv4.udp_table;
2538c7228317SJoe Perches 	INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr);
2539919dfa0bSKuniyuki Iwashima 	unsigned short hnum = ntohs(loc_port);
2540919dfa0bSKuniyuki Iwashima 	unsigned int hash2, slot2;
2541919dfa0bSKuniyuki Iwashima 	struct udp_hslot *hslot2;
2542919dfa0bSKuniyuki Iwashima 	__portpair ports;
2543ca065d0cSEric Dumazet 	struct sock *sk;
2544421b3885SShawn Bohrer 
2545919dfa0bSKuniyuki Iwashima 	hash2 = ipv4_portaddr_hash(net, loc_addr, hnum);
2546ba6aac15SKuniyuki Iwashima 	slot2 = hash2 & udptable->mask;
2547ba6aac15SKuniyuki Iwashima 	hslot2 = &udptable->hash2[slot2];
2548919dfa0bSKuniyuki Iwashima 	ports = INET_COMBINED_PORTS(rmt_port, hnum);
2549919dfa0bSKuniyuki Iwashima 
2550ca065d0cSEric Dumazet 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
2551eda090c3SEric Dumazet 		if (inet_match(net, sk, acookie, ports, dif, sdif))
2552ca065d0cSEric Dumazet 			return sk;
2553421b3885SShawn Bohrer 		/* Only check first socket in chain */
2554421b3885SShawn Bohrer 		break;
2555421b3885SShawn Bohrer 	}
2556ca065d0cSEric Dumazet 	return NULL;
2557421b3885SShawn Bohrer }
2558421b3885SShawn Bohrer 
udp_v4_early_demux(struct sk_buff * skb)25597487449cSPaolo Abeni int udp_v4_early_demux(struct sk_buff *skb)
2560421b3885SShawn Bohrer {
2561610438b7SEric Dumazet 	struct net *net = dev_net(skb->dev);
2562bc044e8dSPaolo Abeni 	struct in_device *in_dev = NULL;
2563610438b7SEric Dumazet 	const struct iphdr *iph;
2564610438b7SEric Dumazet 	const struct udphdr *uh;
2565ca065d0cSEric Dumazet 	struct sock *sk = NULL;
2566421b3885SShawn Bohrer 	struct dst_entry *dst;
2567421b3885SShawn Bohrer 	int dif = skb->dev->ifindex;
2568fb74c277SDavid Ahern 	int sdif = inet_sdif(skb);
25696e540309SShawn Bohrer 	int ours;
2570421b3885SShawn Bohrer 
2571421b3885SShawn Bohrer 	/* validate the packet */
2572421b3885SShawn Bohrer 	if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)))
25737487449cSPaolo Abeni 		return 0;
2574421b3885SShawn Bohrer 
2575610438b7SEric Dumazet 	iph = ip_hdr(skb);
2576610438b7SEric Dumazet 	uh = udp_hdr(skb);
2577610438b7SEric Dumazet 
2578996b44fcSPaolo Abeni 	if (skb->pkt_type == PACKET_MULTICAST) {
2579bc044e8dSPaolo Abeni 		in_dev = __in_dev_get_rcu(skb->dev);
25806e540309SShawn Bohrer 
25816e540309SShawn Bohrer 		if (!in_dev)
25827487449cSPaolo Abeni 			return 0;
25836e540309SShawn Bohrer 
25846e540309SShawn Bohrer 		ours = ip_check_mc_rcu(in_dev, iph->daddr, iph->saddr,
25856e540309SShawn Bohrer 				       iph->protocol);
25866e540309SShawn Bohrer 		if (!ours)
25877487449cSPaolo Abeni 			return 0;
2588ad0ea198SPaolo Abeni 
2589421b3885SShawn Bohrer 		sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr,
2590fb74c277SDavid Ahern 						   uh->source, iph->saddr,
2591fb74c277SDavid Ahern 						   dif, sdif);
25926e540309SShawn Bohrer 	} else if (skb->pkt_type == PACKET_HOST) {
2593421b3885SShawn Bohrer 		sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr,
25943fa6f616SDavid Ahern 					     uh->source, iph->saddr, dif, sdif);
25956e540309SShawn Bohrer 	}
2596421b3885SShawn Bohrer 
259708842c43SEric Dumazet 	if (!sk)
25987487449cSPaolo Abeni 		return 0;
2599421b3885SShawn Bohrer 
2600421b3885SShawn Bohrer 	skb->sk = sk;
260108842c43SEric Dumazet 	DEBUG_NET_WARN_ON_ONCE(sk_is_refcounted(sk));
260208842c43SEric Dumazet 	skb->destructor = sock_pfree;
26038f905c0eSEric Dumazet 	dst = rcu_dereference(sk->sk_rx_dst);
2604421b3885SShawn Bohrer 
2605421b3885SShawn Bohrer 	if (dst)
2606421b3885SShawn Bohrer 		dst = dst_check(dst, 0);
260710e2eb87SEric Dumazet 	if (dst) {
2608bc044e8dSPaolo Abeni 		u32 itag = 0;
2609bc044e8dSPaolo Abeni 
2610d24406c8SWei Wang 		/* set noref for now.
2611d24406c8SWei Wang 		 * any place which wants to hold dst has to call
2612d24406c8SWei Wang 		 * dst_hold_safe()
2613d24406c8SWei Wang 		 */
2614421b3885SShawn Bohrer 		skb_dst_set_noref(skb, dst);
2615bc044e8dSPaolo Abeni 
2616bc044e8dSPaolo Abeni 		/* for unconnected multicast sockets we need to validate
2617bc044e8dSPaolo Abeni 		 * the source on each packet
2618bc044e8dSPaolo Abeni 		 */
2619bc044e8dSPaolo Abeni 		if (!inet_sk(sk)->inet_daddr && in_dev)
2620bc044e8dSPaolo Abeni 			return ip_mc_validate_source(skb, iph->daddr,
26218d2b51b0SGuillaume Nault 						     iph->saddr,
2622*b6791ac5SIdo Schimmel 						     iph->tos & INET_DSCP_MASK,
2623bc044e8dSPaolo Abeni 						     skb->dev, in_dev, &itag);
2624421b3885SShawn Bohrer 	}
26257487449cSPaolo Abeni 	return 0;
262610e2eb87SEric Dumazet }
2627421b3885SShawn Bohrer 
udp_rcv(struct sk_buff * skb)2628db8dac20SDavid S. Miller int udp_rcv(struct sk_buff *skb)
2629db8dac20SDavid S. Miller {
2630ba6aac15SKuniyuki Iwashima 	return __udp4_lib_rcv(skb, dev_net(skb->dev)->ipv4.udp_table, IPPROTO_UDP);
2631db8dac20SDavid S. Miller }
2632db8dac20SDavid S. Miller 
udp_destroy_sock(struct sock * sk)26337d06b2e0SBrian Haley void udp_destroy_sock(struct sock *sk)
2634db8dac20SDavid S. Miller {
263544046a59STom Parkin 	struct udp_sock *up = udp_sk(sk);
26368a74ad60SEric Dumazet 	bool slow = lock_sock_fast(sk);
2637a8b897c7SPaolo Abeni 
2638a8b897c7SPaolo Abeni 	/* protects from races with udp_abort() */
2639a8b897c7SPaolo Abeni 	sock_set_flag(sk, SOCK_DEAD);
2640db8dac20SDavid S. Miller 	udp_flush_pending_frames(sk);
26418a74ad60SEric Dumazet 	unlock_sock_fast(sk, slow);
264260fb9567SPaolo Abeni 	if (static_branch_unlikely(&udp_encap_needed_key)) {
264360fb9567SPaolo Abeni 		if (up->encap_type) {
264444046a59STom Parkin 			void (*encap_destroy)(struct sock *sk);
26456aa7de05SMark Rutland 			encap_destroy = READ_ONCE(up->encap_destroy);
264644046a59STom Parkin 			if (encap_destroy)
264744046a59STom Parkin 				encap_destroy(sk);
264844046a59STom Parkin 		}
2649ac9a7f4cSEric Dumazet 		if (udp_test_bit(ENCAP_ENABLED, sk))
26509c480601SPaolo Abeni 			static_branch_dec(&udp_encap_needed_key);
265160fb9567SPaolo Abeni 	}
2652db8dac20SDavid S. Miller }
2653db8dac20SDavid S. Miller 
set_xfrm_gro_udp_encap_rcv(__u16 encap_type,unsigned short family,struct sock * sk)2654172bf009SSteffen Klassert static void set_xfrm_gro_udp_encap_rcv(__u16 encap_type, unsigned short family,
2655172bf009SSteffen Klassert 				       struct sock *sk)
2656172bf009SSteffen Klassert {
2657172bf009SSteffen Klassert #ifdef CONFIG_XFRM
2658172bf009SSteffen Klassert 	if (udp_test_bit(GRO_ENABLED, sk) && encap_type == UDP_ENCAP_ESPINUDP) {
2659172bf009SSteffen Klassert 		if (family == AF_INET)
2660172bf009SSteffen Klassert 			WRITE_ONCE(udp_sk(sk)->gro_receive, xfrm4_gro_udp_encap_rcv);
2661221ddb72SSteffen Klassert 		else if (IS_ENABLED(CONFIG_IPV6) && family == AF_INET6)
2662221ddb72SSteffen Klassert 			WRITE_ONCE(udp_sk(sk)->gro_receive, ipv6_stub->xfrm6_gro_udp_encap_rcv);
2663172bf009SSteffen Klassert 	}
2664172bf009SSteffen Klassert #endif
2665172bf009SSteffen Klassert }
2666172bf009SSteffen Klassert 
26671da177e4SLinus Torvalds /*
26681da177e4SLinus Torvalds  *	Socket option code for UDP
26691da177e4SLinus Torvalds  */
udp_lib_setsockopt(struct sock * sk,int level,int optname,sockptr_t optval,unsigned int optlen,int (* push_pending_frames)(struct sock *))26704c0a6cb0SGerrit Renker int udp_lib_setsockopt(struct sock *sk, int level, int optname,
267191ac1ccaSChristoph Hellwig 		       sockptr_t optval, unsigned int optlen,
26724c0a6cb0SGerrit Renker 		       int (*push_pending_frames)(struct sock *))
26731da177e4SLinus Torvalds {
26741da177e4SLinus Torvalds 	struct udp_sock *up = udp_sk(sk);
26751c19448cSTom Herbert 	int val, valbool;
26761da177e4SLinus Torvalds 	int err = 0;
2677b2bf1e26SWang Chen 	int is_udplite = IS_UDPLITE(sk);
26781da177e4SLinus Torvalds 
26798a3854c7SPaolo Abeni 	if (level == SOL_SOCKET) {
26808a3854c7SPaolo Abeni 		err = sk_setsockopt(sk, level, optname, optval, optlen);
26818a3854c7SPaolo Abeni 
26828a3854c7SPaolo Abeni 		if (optname == SO_RCVBUF || optname == SO_RCVBUFFORCE) {
26838a3854c7SPaolo Abeni 			sockopt_lock_sock(sk);
26848a3854c7SPaolo Abeni 			/* paired with READ_ONCE in udp_rmem_release() */
26858a3854c7SPaolo Abeni 			WRITE_ONCE(up->forward_threshold, sk->sk_rcvbuf >> 2);
26868a3854c7SPaolo Abeni 			sockopt_release_sock(sk);
26878a3854c7SPaolo Abeni 		}
26888a3854c7SPaolo Abeni 		return err;
26898a3854c7SPaolo Abeni 	}
26908a3854c7SPaolo Abeni 
26911da177e4SLinus Torvalds 	if (optlen < sizeof(int))
26921da177e4SLinus Torvalds 		return -EINVAL;
26931da177e4SLinus Torvalds 
269491ac1ccaSChristoph Hellwig 	if (copy_from_sockptr(&val, optval, sizeof(val)))
26951da177e4SLinus Torvalds 		return -EFAULT;
26961da177e4SLinus Torvalds 
26971c19448cSTom Herbert 	valbool = val ? 1 : 0;
26981c19448cSTom Herbert 
26991da177e4SLinus Torvalds 	switch (optname) {
27001da177e4SLinus Torvalds 	case UDP_CORK:
27011da177e4SLinus Torvalds 		if (val != 0) {
270281b36803SEric Dumazet 			udp_set_bit(CORK, sk);
27031da177e4SLinus Torvalds 		} else {
270481b36803SEric Dumazet 			udp_clear_bit(CORK, sk);
27051da177e4SLinus Torvalds 			lock_sock(sk);
27064243cdc2SJoe Perches 			push_pending_frames(sk);
27071da177e4SLinus Torvalds 			release_sock(sk);
27081da177e4SLinus Torvalds 		}
27091da177e4SLinus Torvalds 		break;
27101da177e4SLinus Torvalds 
27111da177e4SLinus Torvalds 	case UDP_ENCAP:
27121da177e4SLinus Torvalds 		switch (val) {
27131da177e4SLinus Torvalds 		case 0:
2714fd1ac07fSAlexey Dobriyan #ifdef CONFIG_XFRM
27151da177e4SLinus Torvalds 		case UDP_ENCAP_ESPINUDP:
2716172bf009SSteffen Klassert 			set_xfrm_gro_udp_encap_rcv(val, sk->sk_family, sk);
27170146dca7SSabrina Dubroca #if IS_ENABLED(CONFIG_IPV6)
27180146dca7SSabrina Dubroca 			if (sk->sk_family == AF_INET6)
27196d5a12ebSEric Dumazet 				WRITE_ONCE(up->encap_rcv,
27206d5a12ebSEric Dumazet 					   ipv6_stub->xfrm6_udp_encap_rcv);
27210146dca7SSabrina Dubroca 			else
27220146dca7SSabrina Dubroca #endif
27236d5a12ebSEric Dumazet 				WRITE_ONCE(up->encap_rcv,
27246d5a12ebSEric Dumazet 					   xfrm4_udp_encap_rcv);
2725fd1ac07fSAlexey Dobriyan #endif
2726a8eceea8SJoe Perches 			fallthrough;
2727342f0234SJames Chapman 		case UDP_ENCAP_L2TPINUDP:
272870a36f57SEric Dumazet 			WRITE_ONCE(up->encap_type, val);
2729ac9a7f4cSEric Dumazet 			udp_tunnel_encap_enable(sk);
27301da177e4SLinus Torvalds 			break;
27311da177e4SLinus Torvalds 		default:
27321da177e4SLinus Torvalds 			err = -ENOPROTOOPT;
27331da177e4SLinus Torvalds 			break;
27341da177e4SLinus Torvalds 		}
27351da177e4SLinus Torvalds 		break;
27361da177e4SLinus Torvalds 
27371c19448cSTom Herbert 	case UDP_NO_CHECK6_TX:
2738a0002127SEric Dumazet 		udp_set_no_check6_tx(sk, valbool);
27391c19448cSTom Herbert 		break;
27401c19448cSTom Herbert 
27411c19448cSTom Herbert 	case UDP_NO_CHECK6_RX:
2742bcbc1b1dSEric Dumazet 		udp_set_no_check6_rx(sk, valbool);
27431c19448cSTom Herbert 		break;
27441c19448cSTom Herbert 
2745bec1f6f6SWillem de Bruijn 	case UDP_SEGMENT:
2746bec1f6f6SWillem de Bruijn 		if (val < 0 || val > USHRT_MAX)
2747bec1f6f6SWillem de Bruijn 			return -EINVAL;
274818a419baSEric Dumazet 		WRITE_ONCE(up->gso_size, val);
2749bec1f6f6SWillem de Bruijn 		break;
2750bec1f6f6SWillem de Bruijn 
2751e20cf8d3SPaolo Abeni 	case UDP_GRO:
275278352f73SPaolo Abeni 
275378352f73SPaolo Abeni 		/* when enabling GRO, accept the related GSO packet type */
2754e20cf8d3SPaolo Abeni 		if (valbool)
2755ac9a7f4cSEric Dumazet 			udp_tunnel_encap_enable(sk);
2756e1dc0615SEric Dumazet 		udp_assign_bit(GRO_ENABLED, sk, valbool);
2757f5f52f08SEric Dumazet 		udp_assign_bit(ACCEPT_L4, sk, valbool);
2758172bf009SSteffen Klassert 		set_xfrm_gro_udp_encap_rcv(up->encap_type, sk->sk_family, sk);
2759e20cf8d3SPaolo Abeni 		break;
2760e20cf8d3SPaolo Abeni 
2761ba4e58ecSGerrit Renker 	/*
2762ba4e58ecSGerrit Renker 	 * 	UDP-Lite's partial checksum coverage (RFC 3828).
2763ba4e58ecSGerrit Renker 	 */
2764ba4e58ecSGerrit Renker 	/* The sender sets actual checksum coverage length via this option.
2765ba4e58ecSGerrit Renker 	 * The case coverage > packet length is handled by send module. */
2766ba4e58ecSGerrit Renker 	case UDPLITE_SEND_CSCOV:
2767b2bf1e26SWang Chen 		if (!is_udplite)         /* Disable the option on UDP sockets */
2768ba4e58ecSGerrit Renker 			return -ENOPROTOOPT;
2769ba4e58ecSGerrit Renker 		if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
2770ba4e58ecSGerrit Renker 			val = 8;
27714be929beSAlexey Dobriyan 		else if (val > USHRT_MAX)
27724be929beSAlexey Dobriyan 			val = USHRT_MAX;
2773882af43aSEric Dumazet 		WRITE_ONCE(up->pcslen, val);
2774882af43aSEric Dumazet 		udp_set_bit(UDPLITE_SEND_CC, sk);
2775ba4e58ecSGerrit Renker 		break;
2776ba4e58ecSGerrit Renker 
2777ba4e58ecSGerrit Renker 	/* The receiver specifies a minimum checksum coverage value. To make
2778ba4e58ecSGerrit Renker 	 * sense, this should be set to at least 8 (as done below). If zero is
2779ba4e58ecSGerrit Renker 	 * used, this again means full checksum coverage.                     */
2780ba4e58ecSGerrit Renker 	case UDPLITE_RECV_CSCOV:
2781b2bf1e26SWang Chen 		if (!is_udplite)         /* Disable the option on UDP sockets */
2782ba4e58ecSGerrit Renker 			return -ENOPROTOOPT;
2783ba4e58ecSGerrit Renker 		if (val != 0 && val < 8) /* Avoid silly minimal values.       */
2784ba4e58ecSGerrit Renker 			val = 8;
27854be929beSAlexey Dobriyan 		else if (val > USHRT_MAX)
27864be929beSAlexey Dobriyan 			val = USHRT_MAX;
2787882af43aSEric Dumazet 		WRITE_ONCE(up->pcrlen, val);
2788882af43aSEric Dumazet 		udp_set_bit(UDPLITE_RECV_CC, sk);
2789ba4e58ecSGerrit Renker 		break;
2790ba4e58ecSGerrit Renker 
27911da177e4SLinus Torvalds 	default:
27921da177e4SLinus Torvalds 		err = -ENOPROTOOPT;
27931da177e4SLinus Torvalds 		break;
27946516c655SStephen Hemminger 	}
27951da177e4SLinus Torvalds 
27961da177e4SLinus Torvalds 	return err;
27971da177e4SLinus Torvalds }
2798c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_setsockopt);
27991da177e4SLinus Torvalds 
udp_setsockopt(struct sock * sk,int level,int optname,sockptr_t optval,unsigned int optlen)2800a7b75c5aSChristoph Hellwig int udp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
2801a7b75c5aSChristoph Hellwig 		   unsigned int optlen)
2802db8dac20SDavid S. Miller {
28038a3854c7SPaolo Abeni 	if (level == SOL_UDP  ||  level == SOL_UDPLITE || level == SOL_SOCKET)
280491ac1ccaSChristoph Hellwig 		return udp_lib_setsockopt(sk, level, optname,
2805a7b75c5aSChristoph Hellwig 					  optval, optlen,
2806db8dac20SDavid S. Miller 					  udp_push_pending_frames);
2807db8dac20SDavid S. Miller 	return ip_setsockopt(sk, level, optname, optval, optlen);
2808db8dac20SDavid S. Miller }
2809db8dac20SDavid S. Miller 
udp_lib_getsockopt(struct sock * sk,int level,int optname,char __user * optval,int __user * optlen)28104c0a6cb0SGerrit Renker int udp_lib_getsockopt(struct sock *sk, int level, int optname,
28111da177e4SLinus Torvalds 		       char __user *optval, int __user *optlen)
28121da177e4SLinus Torvalds {
28131da177e4SLinus Torvalds 	struct udp_sock *up = udp_sk(sk);
28141da177e4SLinus Torvalds 	int val, len;
28151da177e4SLinus Torvalds 
28161da177e4SLinus Torvalds 	if (get_user(len, optlen))
28171da177e4SLinus Torvalds 		return -EFAULT;
28181da177e4SLinus Torvalds 
28191da177e4SLinus Torvalds 	if (len < 0)
28201da177e4SLinus Torvalds 		return -EINVAL;
28211da177e4SLinus Torvalds 
28224bb3ba7bSGavrilov Ilia 	len = min_t(unsigned int, len, sizeof(int));
28234bb3ba7bSGavrilov Ilia 
28241da177e4SLinus Torvalds 	switch (optname) {
28251da177e4SLinus Torvalds 	case UDP_CORK:
282681b36803SEric Dumazet 		val = udp_test_bit(CORK, sk);
28271da177e4SLinus Torvalds 		break;
28281da177e4SLinus Torvalds 
28291da177e4SLinus Torvalds 	case UDP_ENCAP:
283070a36f57SEric Dumazet 		val = READ_ONCE(up->encap_type);
28311da177e4SLinus Torvalds 		break;
28321da177e4SLinus Torvalds 
28331c19448cSTom Herbert 	case UDP_NO_CHECK6_TX:
2834a0002127SEric Dumazet 		val = udp_get_no_check6_tx(sk);
28351c19448cSTom Herbert 		break;
28361c19448cSTom Herbert 
28371c19448cSTom Herbert 	case UDP_NO_CHECK6_RX:
2838bcbc1b1dSEric Dumazet 		val = udp_get_no_check6_rx(sk);
28391c19448cSTom Herbert 		break;
28401c19448cSTom Herbert 
2841bec1f6f6SWillem de Bruijn 	case UDP_SEGMENT:
284218a419baSEric Dumazet 		val = READ_ONCE(up->gso_size);
2843bec1f6f6SWillem de Bruijn 		break;
2844bec1f6f6SWillem de Bruijn 
284598184612SNorman Maurer 	case UDP_GRO:
2846e1dc0615SEric Dumazet 		val = udp_test_bit(GRO_ENABLED, sk);
284798184612SNorman Maurer 		break;
284898184612SNorman Maurer 
2849ba4e58ecSGerrit Renker 	/* The following two cannot be changed on UDP sockets, the return is
2850ba4e58ecSGerrit Renker 	 * always 0 (which corresponds to the full checksum coverage of UDP). */
2851ba4e58ecSGerrit Renker 	case UDPLITE_SEND_CSCOV:
2852882af43aSEric Dumazet 		val = READ_ONCE(up->pcslen);
2853ba4e58ecSGerrit Renker 		break;
2854ba4e58ecSGerrit Renker 
2855ba4e58ecSGerrit Renker 	case UDPLITE_RECV_CSCOV:
2856882af43aSEric Dumazet 		val = READ_ONCE(up->pcrlen);
2857ba4e58ecSGerrit Renker 		break;
2858ba4e58ecSGerrit Renker 
28591da177e4SLinus Torvalds 	default:
28601da177e4SLinus Torvalds 		return -ENOPROTOOPT;
28616516c655SStephen Hemminger 	}
28621da177e4SLinus Torvalds 
28631da177e4SLinus Torvalds 	if (put_user(len, optlen))
28641da177e4SLinus Torvalds 		return -EFAULT;
28651da177e4SLinus Torvalds 	if (copy_to_user(optval, &val, len))
28661da177e4SLinus Torvalds 		return -EFAULT;
28671da177e4SLinus Torvalds 	return 0;
28681da177e4SLinus Torvalds }
2869c482c568SEric Dumazet EXPORT_SYMBOL(udp_lib_getsockopt);
28701da177e4SLinus Torvalds 
udp_getsockopt(struct sock * sk,int level,int optname,char __user * optval,int __user * optlen)2871db8dac20SDavid S. Miller int udp_getsockopt(struct sock *sk, int level, int optname,
2872db8dac20SDavid S. Miller 		   char __user *optval, int __user *optlen)
2873db8dac20SDavid S. Miller {
2874db8dac20SDavid S. Miller 	if (level == SOL_UDP  ||  level == SOL_UDPLITE)
2875db8dac20SDavid S. Miller 		return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2876db8dac20SDavid S. Miller 	return ip_getsockopt(sk, level, optname, optval, optlen);
2877db8dac20SDavid S. Miller }
2878db8dac20SDavid S. Miller 
28791da177e4SLinus Torvalds /**
28801da177e4SLinus Torvalds  * 	udp_poll - wait for a UDP event.
28813628e3cbSAndrew Lunn  *	@file: - file struct
28823628e3cbSAndrew Lunn  *	@sock: - socket
28833628e3cbSAndrew Lunn  *	@wait: - poll table
28841da177e4SLinus Torvalds  *
28851da177e4SLinus Torvalds  *	This is same as datagram poll, except for the special case of
28861da177e4SLinus Torvalds  *	blocking sockets. If application is using a blocking fd
28871da177e4SLinus Torvalds  *	and a packet with checksum error is in the queue;
28881da177e4SLinus Torvalds  *	then it could get return from select indicating data available
28891da177e4SLinus Torvalds  *	but then block when reading it. Add special case code
28901da177e4SLinus Torvalds  *	to work around these arguably broken applications.
28911da177e4SLinus Torvalds  */
udp_poll(struct file * file,struct socket * sock,poll_table * wait)2892a11e1d43SLinus Torvalds __poll_t udp_poll(struct file *file, struct socket *sock, poll_table *wait)
28931da177e4SLinus Torvalds {
2894a11e1d43SLinus Torvalds 	__poll_t mask = datagram_poll(file, sock, wait);
28951da177e4SLinus Torvalds 	struct sock *sk = sock->sk;
28961da177e4SLinus Torvalds 
28973ef7cf57SEric Dumazet 	if (!skb_queue_empty_lockless(&udp_sk(sk)->reader_queue))
2898a9a08845SLinus Torvalds 		mask |= EPOLLIN | EPOLLRDNORM;
28992276f58aSPaolo Abeni 
29001da177e4SLinus Torvalds 	/* Check for false positives due to checksum errors */
2901a11e1d43SLinus Torvalds 	if ((mask & EPOLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
2902e83c6744SEric Dumazet 	    !(sk->sk_shutdown & RCV_SHUTDOWN) && first_packet_length(sk) == -1)
2903a9a08845SLinus Torvalds 		mask &= ~(EPOLLIN | EPOLLRDNORM);
29041da177e4SLinus Torvalds 
2905af493388SCong Wang 	/* psock ingress_msg queue should not contain any bad checksum frames */
2906af493388SCong Wang 	if (sk_is_readable(sk))
2907af493388SCong Wang 		mask |= EPOLLIN | EPOLLRDNORM;
29081da177e4SLinus Torvalds 	return mask;
29091da177e4SLinus Torvalds 
29101da177e4SLinus Torvalds }
2911a11e1d43SLinus Torvalds EXPORT_SYMBOL(udp_poll);
29121da177e4SLinus Torvalds 
udp_abort(struct sock * sk,int err)29135d77dca8SDavid Ahern int udp_abort(struct sock *sk, int err)
29145d77dca8SDavid Ahern {
29154ddbcb88SAditi Ghag 	if (!has_current_bpf_ctx())
29165d77dca8SDavid Ahern 		lock_sock(sk);
29175d77dca8SDavid Ahern 
2918a8b897c7SPaolo Abeni 	/* udp{v6}_destroy_sock() sets it under the sk lock, avoid racing
2919a8b897c7SPaolo Abeni 	 * with close()
2920a8b897c7SPaolo Abeni 	 */
2921a8b897c7SPaolo Abeni 	if (sock_flag(sk, SOCK_DEAD))
2922a8b897c7SPaolo Abeni 		goto out;
2923a8b897c7SPaolo Abeni 
29245d77dca8SDavid Ahern 	sk->sk_err = err;
2925e3ae2365SAlexander Aring 	sk_error_report(sk);
2926286c72deSEric Dumazet 	__udp_disconnect(sk, 0);
29275d77dca8SDavid Ahern 
2928a8b897c7SPaolo Abeni out:
29294ddbcb88SAditi Ghag 	if (!has_current_bpf_ctx())
29305d77dca8SDavid Ahern 		release_sock(sk);
29315d77dca8SDavid Ahern 
29325d77dca8SDavid Ahern 	return 0;
29335d77dca8SDavid Ahern }
29345d77dca8SDavid Ahern EXPORT_SYMBOL_GPL(udp_abort);
29355d77dca8SDavid Ahern 
2936db8dac20SDavid S. Miller struct proto udp_prot = {
2937db8dac20SDavid S. Miller 	.name			= "UDP",
2938db8dac20SDavid S. Miller 	.owner			= THIS_MODULE,
2939db8dac20SDavid S. Miller 	.close			= udp_lib_close,
2940d74bad4eSAndrey Ignatov 	.pre_connect		= udp_pre_connect,
2941db8dac20SDavid S. Miller 	.connect		= ip4_datagram_connect,
2942db8dac20SDavid S. Miller 	.disconnect		= udp_disconnect,
2943db8dac20SDavid S. Miller 	.ioctl			= udp_ioctl,
2944850cbaddSPaolo Abeni 	.init			= udp_init_sock,
2945db8dac20SDavid S. Miller 	.destroy		= udp_destroy_sock,
2946db8dac20SDavid S. Miller 	.setsockopt		= udp_setsockopt,
2947db8dac20SDavid S. Miller 	.getsockopt		= udp_getsockopt,
2948db8dac20SDavid S. Miller 	.sendmsg		= udp_sendmsg,
2949db8dac20SDavid S. Miller 	.recvmsg		= udp_recvmsg,
29501d7e4538SDavid Howells 	.splice_eof		= udp_splice_eof,
29518141ed9fSSteffen Klassert 	.release_cb		= ip4_datagram_release_cb,
2952db8dac20SDavid S. Miller 	.hash			= udp_lib_hash,
2953db8dac20SDavid S. Miller 	.unhash			= udp_lib_unhash,
2954719f8358SEric Dumazet 	.rehash			= udp_v4_rehash,
2955db8dac20SDavid S. Miller 	.get_port		= udp_v4_get_port,
295691a760b2SMenglong Dong 	.put_port		= udp_lib_unhash,
29578a59f9d1SCong Wang #ifdef CONFIG_BPF_SYSCALL
29588a59f9d1SCong Wang 	.psock_update_sk_prot	= udp_bpf_update_proto,
29598a59f9d1SCong Wang #endif
2960db8dac20SDavid S. Miller 	.memory_allocated	= &udp_memory_allocated,
29610defbb0aSEric Dumazet 	.per_cpu_fw_alloc	= &udp_memory_per_cpu_fw_alloc,
29620defbb0aSEric Dumazet 
2963db8dac20SDavid S. Miller 	.sysctl_mem		= sysctl_udp_mem,
29641e802951STonghao Zhang 	.sysctl_wmem_offset	= offsetof(struct net, ipv4.sysctl_udp_wmem_min),
29651e802951STonghao Zhang 	.sysctl_rmem_offset	= offsetof(struct net, ipv4.sysctl_udp_rmem_min),
2966db8dac20SDavid S. Miller 	.obj_size		= sizeof(struct udp_sock),
296767fb4330SKuniyuki Iwashima 	.h.udp_table		= NULL,
29685d77dca8SDavid Ahern 	.diag_destroy		= udp_abort,
2969db8dac20SDavid S. Miller };
2970c482c568SEric Dumazet EXPORT_SYMBOL(udp_prot);
29711da177e4SLinus Torvalds 
29721da177e4SLinus Torvalds /* ------------------------------------------------------------------------ */
29731da177e4SLinus Torvalds #ifdef CONFIG_PROC_FS
29741da177e4SLinus Torvalds 
2975f44b1c51SAditi Ghag static unsigned short seq_file_family(const struct seq_file *seq);
seq_sk_match(struct seq_file * seq,const struct sock * sk)2976f44b1c51SAditi Ghag static bool seq_sk_match(struct seq_file *seq, const struct sock *sk)
2977f44b1c51SAditi Ghag {
2978f44b1c51SAditi Ghag 	unsigned short family = seq_file_family(seq);
2979f44b1c51SAditi Ghag 
2980f44b1c51SAditi Ghag 	/* AF_UNSPEC is used as a match all */
2981f44b1c51SAditi Ghag 	return ((family == AF_UNSPEC || family == sk->sk_family) &&
2982f44b1c51SAditi Ghag 		net_eq(sock_net(sk), seq_file_net(seq)));
2983f44b1c51SAditi Ghag }
2984f44b1c51SAditi Ghag 
2985e4fe1bf1SAditi Ghag #ifdef CONFIG_BPF_SYSCALL
2986e4fe1bf1SAditi Ghag static const struct seq_operations bpf_iter_udp_seq_ops;
2987e4fe1bf1SAditi Ghag #endif
udp_get_table_seq(struct seq_file * seq,struct net * net)29887625d2e9SAditi Ghag static struct udp_table *udp_get_table_seq(struct seq_file *seq,
2989478aee5dSKuniyuki Iwashima 					   struct net *net)
2990478aee5dSKuniyuki Iwashima {
29917625d2e9SAditi Ghag 	const struct udp_seq_afinfo *afinfo;
29927625d2e9SAditi Ghag 
2993e4fe1bf1SAditi Ghag #ifdef CONFIG_BPF_SYSCALL
2994e4fe1bf1SAditi Ghag 	if (seq->op == &bpf_iter_udp_seq_ops)
29957625d2e9SAditi Ghag 		return net->ipv4.udp_table;
2996e4fe1bf1SAditi Ghag #endif
29977625d2e9SAditi Ghag 
29987625d2e9SAditi Ghag 	afinfo = pde_data(file_inode(seq->file));
2999478aee5dSKuniyuki Iwashima 	return afinfo->udp_table ? : net->ipv4.udp_table;
3000478aee5dSKuniyuki Iwashima }
3001478aee5dSKuniyuki Iwashima 
udp_get_first(struct seq_file * seq,int start)3002645ca708SEric Dumazet static struct sock *udp_get_first(struct seq_file *seq, int start)
30031da177e4SLinus Torvalds {
30041da177e4SLinus Torvalds 	struct udp_iter_state *state = seq->private;
30056f191efeSDenis V. Lunev 	struct net *net = seq_file_net(seq);
3006478aee5dSKuniyuki Iwashima 	struct udp_table *udptable;
3007919dfa0bSKuniyuki Iwashima 	struct sock *sk;
30081da177e4SLinus Torvalds 
30097625d2e9SAditi Ghag 	udptable = udp_get_table_seq(seq, net);
3010478aee5dSKuniyuki Iwashima 
3011478aee5dSKuniyuki Iwashima 	for (state->bucket = start; state->bucket <= udptable->mask;
3012f86dcc5aSEric Dumazet 	     ++state->bucket) {
3013478aee5dSKuniyuki Iwashima 		struct udp_hslot *hslot = &udptable->hash[state->bucket];
3014f86dcc5aSEric Dumazet 
3015ca065d0cSEric Dumazet 		if (hlist_empty(&hslot->head))
3016f86dcc5aSEric Dumazet 			continue;
3017f86dcc5aSEric Dumazet 
3018645ca708SEric Dumazet 		spin_lock_bh(&hslot->lock);
3019ca065d0cSEric Dumazet 		sk_for_each(sk, &hslot->head) {
3020f44b1c51SAditi Ghag 			if (seq_sk_match(seq, sk))
30211da177e4SLinus Torvalds 				goto found;
30221da177e4SLinus Torvalds 		}
3023645ca708SEric Dumazet 		spin_unlock_bh(&hslot->lock);
30241da177e4SLinus Torvalds 	}
30251da177e4SLinus Torvalds 	sk = NULL;
30261da177e4SLinus Torvalds found:
30271da177e4SLinus Torvalds 	return sk;
30281da177e4SLinus Torvalds }
30291da177e4SLinus Torvalds 
udp_get_next(struct seq_file * seq,struct sock * sk)30301da177e4SLinus Torvalds static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
30311da177e4SLinus Torvalds {
30321da177e4SLinus Torvalds 	struct udp_iter_state *state = seq->private;
30336f191efeSDenis V. Lunev 	struct net *net = seq_file_net(seq);
3034478aee5dSKuniyuki Iwashima 	struct udp_table *udptable;
30351da177e4SLinus Torvalds 
30361da177e4SLinus Torvalds 	do {
3037ca065d0cSEric Dumazet 		sk = sk_next(sk);
3038f44b1c51SAditi Ghag 	} while (sk && !seq_sk_match(seq, sk));
30391da177e4SLinus Torvalds 
3040645ca708SEric Dumazet 	if (!sk) {
30417625d2e9SAditi Ghag 		udptable = udp_get_table_seq(seq, net);
3042478aee5dSKuniyuki Iwashima 
3043478aee5dSKuniyuki Iwashima 		if (state->bucket <= udptable->mask)
3044478aee5dSKuniyuki Iwashima 			spin_unlock_bh(&udptable->hash[state->bucket].lock);
3045478aee5dSKuniyuki Iwashima 
3046645ca708SEric Dumazet 		return udp_get_first(seq, state->bucket + 1);
30471da177e4SLinus Torvalds 	}
30481da177e4SLinus Torvalds 	return sk;
30491da177e4SLinus Torvalds }
30501da177e4SLinus Torvalds 
udp_get_idx(struct seq_file * seq,loff_t pos)30511da177e4SLinus Torvalds static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
30521da177e4SLinus Torvalds {
3053645ca708SEric Dumazet 	struct sock *sk = udp_get_first(seq, 0);
30541da177e4SLinus Torvalds 
30551da177e4SLinus Torvalds 	if (sk)
30561da177e4SLinus Torvalds 		while (pos && (sk = udp_get_next(seq, sk)) != NULL)
30571da177e4SLinus Torvalds 			--pos;
30581da177e4SLinus Torvalds 	return pos ? NULL : sk;
30591da177e4SLinus Torvalds }
30601da177e4SLinus Torvalds 
udp_seq_start(struct seq_file * seq,loff_t * pos)3061a3d2599bSChristoph Hellwig void *udp_seq_start(struct seq_file *seq, loff_t *pos)
30621da177e4SLinus Torvalds {
306330842f29SVitaly Mayatskikh 	struct udp_iter_state *state = seq->private;
3064f86dcc5aSEric Dumazet 	state->bucket = MAX_UDP_PORTS;
306530842f29SVitaly Mayatskikh 
3066b50660f1SYOSHIFUJI Hideaki 	return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
30671da177e4SLinus Torvalds }
3068a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_start);
30691da177e4SLinus Torvalds 
udp_seq_next(struct seq_file * seq,void * v,loff_t * pos)3070a3d2599bSChristoph Hellwig void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
30711da177e4SLinus Torvalds {
30721da177e4SLinus Torvalds 	struct sock *sk;
30731da177e4SLinus Torvalds 
3074b50660f1SYOSHIFUJI Hideaki 	if (v == SEQ_START_TOKEN)
30751da177e4SLinus Torvalds 		sk = udp_get_idx(seq, 0);
30761da177e4SLinus Torvalds 	else
30771da177e4SLinus Torvalds 		sk = udp_get_next(seq, v);
30781da177e4SLinus Torvalds 
30791da177e4SLinus Torvalds 	++*pos;
30801da177e4SLinus Torvalds 	return sk;
30811da177e4SLinus Torvalds }
3082a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_next);
30831da177e4SLinus Torvalds 
udp_seq_stop(struct seq_file * seq,void * v)3084a3d2599bSChristoph Hellwig void udp_seq_stop(struct seq_file *seq, void *v)
30851da177e4SLinus Torvalds {
3086645ca708SEric Dumazet 	struct udp_iter_state *state = seq->private;
3087478aee5dSKuniyuki Iwashima 	struct udp_table *udptable;
3088645ca708SEric Dumazet 
30897625d2e9SAditi Ghag 	udptable = udp_get_table_seq(seq, seq_file_net(seq));
3090478aee5dSKuniyuki Iwashima 
3091478aee5dSKuniyuki Iwashima 	if (state->bucket <= udptable->mask)
3092478aee5dSKuniyuki Iwashima 		spin_unlock_bh(&udptable->hash[state->bucket].lock);
30931da177e4SLinus Torvalds }
3094a3d2599bSChristoph Hellwig EXPORT_SYMBOL(udp_seq_stop);
3095db8dac20SDavid S. Miller 
3096db8dac20SDavid S. Miller /* ------------------------------------------------------------------------ */
udp4_format_sock(struct sock * sp,struct seq_file * f,int bucket)30975e659e4cSPavel Emelyanov static void udp4_format_sock(struct sock *sp, struct seq_file *f,
3098652586dfSTetsuo Handa 		int bucket)
3099db8dac20SDavid S. Miller {
3100db8dac20SDavid S. Miller 	struct inet_sock *inet = inet_sk(sp);
3101c720c7e8SEric Dumazet 	__be32 dest = inet->inet_daddr;
3102c720c7e8SEric Dumazet 	__be32 src  = inet->inet_rcv_saddr;
3103c720c7e8SEric Dumazet 	__u16 destp	  = ntohs(inet->inet_dport);
3104c720c7e8SEric Dumazet 	__u16 srcp	  = ntohs(inet->inet_sport);
3105db8dac20SDavid S. Miller 
3106f86dcc5aSEric Dumazet 	seq_printf(f, "%5d: %08X:%04X %08X:%04X"
3107ea9a0379SPatrick Talbert 		" %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %u",
3108db8dac20SDavid S. Miller 		bucket, src, srcp, dest, destp, sp->sk_state,
310931e6d363SEric Dumazet 		sk_wmem_alloc_get(sp),
31106c206b20SPaolo Abeni 		udp_rqueue_get(sp),
3111a7cb5a49SEric W. Biederman 		0, 0L, 0,
3112a7cb5a49SEric W. Biederman 		from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
3113a7cb5a49SEric W. Biederman 		0, sock_i_ino(sp),
311441c6d650SReshetova, Elena 		refcount_read(&sp->sk_refcnt), sp,
3115652586dfSTetsuo Handa 		atomic_read(&sp->sk_drops));
3116db8dac20SDavid S. Miller }
3117db8dac20SDavid S. Miller 
udp4_seq_show(struct seq_file * seq,void * v)3118db8dac20SDavid S. Miller int udp4_seq_show(struct seq_file *seq, void *v)
3119db8dac20SDavid S. Miller {
3120652586dfSTetsuo Handa 	seq_setwidth(seq, 127);
3121db8dac20SDavid S. Miller 	if (v == SEQ_START_TOKEN)
3122652586dfSTetsuo Handa 		seq_puts(seq, "   sl  local_address rem_address   st tx_queue "
3123db8dac20SDavid S. Miller 			   "rx_queue tr tm->when retrnsmt   uid  timeout "
3124cb61cb9bSEric Dumazet 			   "inode ref pointer drops");
3125db8dac20SDavid S. Miller 	else {
3126db8dac20SDavid S. Miller 		struct udp_iter_state *state = seq->private;
3127db8dac20SDavid S. Miller 
3128652586dfSTetsuo Handa 		udp4_format_sock(v, seq, state->bucket);
3129db8dac20SDavid S. Miller 	}
3130652586dfSTetsuo Handa 	seq_pad(seq, '\n');
3131db8dac20SDavid S. Miller 	return 0;
3132db8dac20SDavid S. Miller }
3133db8dac20SDavid S. Miller 
31345788b3a0SYonghong Song #ifdef CONFIG_BPF_SYSCALL
31355788b3a0SYonghong Song struct bpf_iter__udp {
31365788b3a0SYonghong Song 	__bpf_md_ptr(struct bpf_iter_meta *, meta);
31375788b3a0SYonghong Song 	__bpf_md_ptr(struct udp_sock *, udp_sk);
31385788b3a0SYonghong Song 	uid_t uid __aligned(8);
31395788b3a0SYonghong Song 	int bucket __aligned(8);
31405788b3a0SYonghong Song };
31415788b3a0SYonghong Song 
3142c96dac8dSAditi Ghag struct bpf_udp_iter_state {
3143c96dac8dSAditi Ghag 	struct udp_iter_state state;
3144c96dac8dSAditi Ghag 	unsigned int cur_sk;
3145c96dac8dSAditi Ghag 	unsigned int end_sk;
3146c96dac8dSAditi Ghag 	unsigned int max_sk;
3147c96dac8dSAditi Ghag 	int offset;
3148c96dac8dSAditi Ghag 	struct sock **batch;
3149c96dac8dSAditi Ghag 	bool st_bucket_done;
3150c96dac8dSAditi Ghag };
3151c96dac8dSAditi Ghag 
3152c96dac8dSAditi Ghag static int bpf_iter_udp_realloc_batch(struct bpf_udp_iter_state *iter,
3153c96dac8dSAditi Ghag 				      unsigned int new_batch_sz);
bpf_iter_udp_batch(struct seq_file * seq)3154c96dac8dSAditi Ghag static struct sock *bpf_iter_udp_batch(struct seq_file *seq)
3155c96dac8dSAditi Ghag {
3156c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = seq->private;
3157c96dac8dSAditi Ghag 	struct udp_iter_state *state = &iter->state;
3158c96dac8dSAditi Ghag 	struct net *net = seq_file_net(seq);
31592242fd53SMartin KaFai Lau 	int resume_bucket, resume_offset;
3160c96dac8dSAditi Ghag 	struct udp_table *udptable;
3161c96dac8dSAditi Ghag 	unsigned int batch_sks = 0;
3162c96dac8dSAditi Ghag 	bool resized = false;
3163c96dac8dSAditi Ghag 	struct sock *sk;
3164c96dac8dSAditi Ghag 
31652242fd53SMartin KaFai Lau 	resume_bucket = state->bucket;
31662242fd53SMartin KaFai Lau 	resume_offset = iter->offset;
31672242fd53SMartin KaFai Lau 
3168c96dac8dSAditi Ghag 	/* The current batch is done, so advance the bucket. */
31692242fd53SMartin KaFai Lau 	if (iter->st_bucket_done)
3170c96dac8dSAditi Ghag 		state->bucket++;
3171c96dac8dSAditi Ghag 
3172c96dac8dSAditi Ghag 	udptable = udp_get_table_seq(seq, net);
3173c96dac8dSAditi Ghag 
3174c96dac8dSAditi Ghag again:
3175c96dac8dSAditi Ghag 	/* New batch for the next bucket.
3176c96dac8dSAditi Ghag 	 * Iterate over the hash table to find a bucket with sockets matching
3177c96dac8dSAditi Ghag 	 * the iterator attributes, and return the first matching socket from
3178c96dac8dSAditi Ghag 	 * the bucket. The remaining matched sockets from the bucket are batched
3179c96dac8dSAditi Ghag 	 * before releasing the bucket lock. This allows BPF programs that are
3180c96dac8dSAditi Ghag 	 * called in seq_show to acquire the bucket lock if needed.
3181c96dac8dSAditi Ghag 	 */
3182c96dac8dSAditi Ghag 	iter->cur_sk = 0;
3183c96dac8dSAditi Ghag 	iter->end_sk = 0;
3184c96dac8dSAditi Ghag 	iter->st_bucket_done = false;
3185c96dac8dSAditi Ghag 	batch_sks = 0;
3186c96dac8dSAditi Ghag 
3187c96dac8dSAditi Ghag 	for (; state->bucket <= udptable->mask; state->bucket++) {
3188c96dac8dSAditi Ghag 		struct udp_hslot *hslot2 = &udptable->hash2[state->bucket];
3189c96dac8dSAditi Ghag 
31902242fd53SMartin KaFai Lau 		if (hlist_empty(&hslot2->head))
3191c96dac8dSAditi Ghag 			continue;
3192c96dac8dSAditi Ghag 
31932242fd53SMartin KaFai Lau 		iter->offset = 0;
3194c96dac8dSAditi Ghag 		spin_lock_bh(&hslot2->lock);
3195c96dac8dSAditi Ghag 		udp_portaddr_for_each_entry(sk, &hslot2->head) {
3196c96dac8dSAditi Ghag 			if (seq_sk_match(seq, sk)) {
3197c96dac8dSAditi Ghag 				/* Resume from the last iterated socket at the
3198c96dac8dSAditi Ghag 				 * offset in the bucket before iterator was stopped.
3199c96dac8dSAditi Ghag 				 */
32002242fd53SMartin KaFai Lau 				if (state->bucket == resume_bucket &&
32012242fd53SMartin KaFai Lau 				    iter->offset < resume_offset) {
32022242fd53SMartin KaFai Lau 					++iter->offset;
3203c96dac8dSAditi Ghag 					continue;
3204c96dac8dSAditi Ghag 				}
3205c96dac8dSAditi Ghag 				if (iter->end_sk < iter->max_sk) {
3206c96dac8dSAditi Ghag 					sock_hold(sk);
3207c96dac8dSAditi Ghag 					iter->batch[iter->end_sk++] = sk;
3208c96dac8dSAditi Ghag 				}
3209c96dac8dSAditi Ghag 				batch_sks++;
3210c96dac8dSAditi Ghag 			}
3211c96dac8dSAditi Ghag 		}
3212c96dac8dSAditi Ghag 		spin_unlock_bh(&hslot2->lock);
3213c96dac8dSAditi Ghag 
3214c96dac8dSAditi Ghag 		if (iter->end_sk)
3215c96dac8dSAditi Ghag 			break;
3216c96dac8dSAditi Ghag 	}
3217c96dac8dSAditi Ghag 
3218c96dac8dSAditi Ghag 	/* All done: no batch made. */
3219c96dac8dSAditi Ghag 	if (!iter->end_sk)
3220c96dac8dSAditi Ghag 		return NULL;
3221c96dac8dSAditi Ghag 
3222c96dac8dSAditi Ghag 	if (iter->end_sk == batch_sks) {
3223c96dac8dSAditi Ghag 		/* Batching is done for the current bucket; return the first
3224c96dac8dSAditi Ghag 		 * socket to be iterated from the batch.
3225c96dac8dSAditi Ghag 		 */
3226c96dac8dSAditi Ghag 		iter->st_bucket_done = true;
3227c96dac8dSAditi Ghag 		goto done;
3228c96dac8dSAditi Ghag 	}
3229c96dac8dSAditi Ghag 	if (!resized && !bpf_iter_udp_realloc_batch(iter, batch_sks * 3 / 2)) {
3230c96dac8dSAditi Ghag 		resized = true;
3231c96dac8dSAditi Ghag 		/* After allocating a larger batch, retry one more time to grab
3232c96dac8dSAditi Ghag 		 * the whole bucket.
3233c96dac8dSAditi Ghag 		 */
3234c96dac8dSAditi Ghag 		goto again;
3235c96dac8dSAditi Ghag 	}
3236c96dac8dSAditi Ghag done:
3237c96dac8dSAditi Ghag 	return iter->batch[0];
3238c96dac8dSAditi Ghag }
3239c96dac8dSAditi Ghag 
bpf_iter_udp_seq_next(struct seq_file * seq,void * v,loff_t * pos)3240c96dac8dSAditi Ghag static void *bpf_iter_udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3241c96dac8dSAditi Ghag {
3242c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = seq->private;
3243c96dac8dSAditi Ghag 	struct sock *sk;
3244c96dac8dSAditi Ghag 
3245c96dac8dSAditi Ghag 	/* Whenever seq_next() is called, the iter->cur_sk is
3246c96dac8dSAditi Ghag 	 * done with seq_show(), so unref the iter->cur_sk.
3247c96dac8dSAditi Ghag 	 */
3248c96dac8dSAditi Ghag 	if (iter->cur_sk < iter->end_sk) {
3249c96dac8dSAditi Ghag 		sock_put(iter->batch[iter->cur_sk++]);
3250c96dac8dSAditi Ghag 		++iter->offset;
3251c96dac8dSAditi Ghag 	}
3252c96dac8dSAditi Ghag 
3253c96dac8dSAditi Ghag 	/* After updating iter->cur_sk, check if there are more sockets
3254c96dac8dSAditi Ghag 	 * available in the current bucket batch.
3255c96dac8dSAditi Ghag 	 */
3256c96dac8dSAditi Ghag 	if (iter->cur_sk < iter->end_sk)
3257c96dac8dSAditi Ghag 		sk = iter->batch[iter->cur_sk];
3258c96dac8dSAditi Ghag 	else
3259c96dac8dSAditi Ghag 		/* Prepare a new batch. */
3260c96dac8dSAditi Ghag 		sk = bpf_iter_udp_batch(seq);
3261c96dac8dSAditi Ghag 
3262c96dac8dSAditi Ghag 	++*pos;
3263c96dac8dSAditi Ghag 	return sk;
3264c96dac8dSAditi Ghag }
3265c96dac8dSAditi Ghag 
bpf_iter_udp_seq_start(struct seq_file * seq,loff_t * pos)3266c96dac8dSAditi Ghag static void *bpf_iter_udp_seq_start(struct seq_file *seq, loff_t *pos)
3267c96dac8dSAditi Ghag {
3268c96dac8dSAditi Ghag 	/* bpf iter does not support lseek, so it always
3269c96dac8dSAditi Ghag 	 * continue from where it was stop()-ped.
3270c96dac8dSAditi Ghag 	 */
3271c96dac8dSAditi Ghag 	if (*pos)
3272c96dac8dSAditi Ghag 		return bpf_iter_udp_batch(seq);
3273c96dac8dSAditi Ghag 
3274c96dac8dSAditi Ghag 	return SEQ_START_TOKEN;
3275c96dac8dSAditi Ghag }
3276c96dac8dSAditi Ghag 
udp_prog_seq_show(struct bpf_prog * prog,struct bpf_iter_meta * meta,struct udp_sock * udp_sk,uid_t uid,int bucket)32775788b3a0SYonghong Song static int udp_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
32785788b3a0SYonghong Song 			     struct udp_sock *udp_sk, uid_t uid, int bucket)
32795788b3a0SYonghong Song {
32805788b3a0SYonghong Song 	struct bpf_iter__udp ctx;
32815788b3a0SYonghong Song 
32825788b3a0SYonghong Song 	meta->seq_num--;  /* skip SEQ_START_TOKEN */
32835788b3a0SYonghong Song 	ctx.meta = meta;
32845788b3a0SYonghong Song 	ctx.udp_sk = udp_sk;
32855788b3a0SYonghong Song 	ctx.uid = uid;
32865788b3a0SYonghong Song 	ctx.bucket = bucket;
32875788b3a0SYonghong Song 	return bpf_iter_run_prog(prog, &ctx);
32885788b3a0SYonghong Song }
32895788b3a0SYonghong Song 
bpf_iter_udp_seq_show(struct seq_file * seq,void * v)32905788b3a0SYonghong Song static int bpf_iter_udp_seq_show(struct seq_file *seq, void *v)
32915788b3a0SYonghong Song {
32925788b3a0SYonghong Song 	struct udp_iter_state *state = seq->private;
32935788b3a0SYonghong Song 	struct bpf_iter_meta meta;
32945788b3a0SYonghong Song 	struct bpf_prog *prog;
32955788b3a0SYonghong Song 	struct sock *sk = v;
32965788b3a0SYonghong Song 	uid_t uid;
3297c96dac8dSAditi Ghag 	int ret;
32985788b3a0SYonghong Song 
32995788b3a0SYonghong Song 	if (v == SEQ_START_TOKEN)
33005788b3a0SYonghong Song 		return 0;
33015788b3a0SYonghong Song 
3302c96dac8dSAditi Ghag 	lock_sock(sk);
3303c96dac8dSAditi Ghag 
3304c96dac8dSAditi Ghag 	if (unlikely(sk_unhashed(sk))) {
3305c96dac8dSAditi Ghag 		ret = SEQ_SKIP;
3306c96dac8dSAditi Ghag 		goto unlock;
3307c96dac8dSAditi Ghag 	}
3308c96dac8dSAditi Ghag 
33095788b3a0SYonghong Song 	uid = from_kuid_munged(seq_user_ns(seq), sock_i_uid(sk));
33105788b3a0SYonghong Song 	meta.seq = seq;
33115788b3a0SYonghong Song 	prog = bpf_iter_get_info(&meta, false);
3312c96dac8dSAditi Ghag 	ret = udp_prog_seq_show(prog, &meta, v, uid, state->bucket);
3313c96dac8dSAditi Ghag 
3314c96dac8dSAditi Ghag unlock:
3315c96dac8dSAditi Ghag 	release_sock(sk);
3316c96dac8dSAditi Ghag 	return ret;
3317c96dac8dSAditi Ghag }
3318c96dac8dSAditi Ghag 
bpf_iter_udp_put_batch(struct bpf_udp_iter_state * iter)3319c96dac8dSAditi Ghag static void bpf_iter_udp_put_batch(struct bpf_udp_iter_state *iter)
3320c96dac8dSAditi Ghag {
3321c96dac8dSAditi Ghag 	while (iter->cur_sk < iter->end_sk)
3322c96dac8dSAditi Ghag 		sock_put(iter->batch[iter->cur_sk++]);
33235788b3a0SYonghong Song }
33245788b3a0SYonghong Song 
bpf_iter_udp_seq_stop(struct seq_file * seq,void * v)33255788b3a0SYonghong Song static void bpf_iter_udp_seq_stop(struct seq_file *seq, void *v)
33265788b3a0SYonghong Song {
3327c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = seq->private;
33285788b3a0SYonghong Song 	struct bpf_iter_meta meta;
33295788b3a0SYonghong Song 	struct bpf_prog *prog;
33305788b3a0SYonghong Song 
33315788b3a0SYonghong Song 	if (!v) {
33325788b3a0SYonghong Song 		meta.seq = seq;
33335788b3a0SYonghong Song 		prog = bpf_iter_get_info(&meta, true);
33345788b3a0SYonghong Song 		if (prog)
33355788b3a0SYonghong Song 			(void)udp_prog_seq_show(prog, &meta, v, 0, 0);
33365788b3a0SYonghong Song 	}
33375788b3a0SYonghong Song 
3338c96dac8dSAditi Ghag 	if (iter->cur_sk < iter->end_sk) {
3339c96dac8dSAditi Ghag 		bpf_iter_udp_put_batch(iter);
3340c96dac8dSAditi Ghag 		iter->st_bucket_done = false;
3341c96dac8dSAditi Ghag 	}
33425788b3a0SYonghong Song }
33435788b3a0SYonghong Song 
33445788b3a0SYonghong Song static const struct seq_operations bpf_iter_udp_seq_ops = {
3345c96dac8dSAditi Ghag 	.start		= bpf_iter_udp_seq_start,
3346c96dac8dSAditi Ghag 	.next		= bpf_iter_udp_seq_next,
33475788b3a0SYonghong Song 	.stop		= bpf_iter_udp_seq_stop,
33485788b3a0SYonghong Song 	.show		= bpf_iter_udp_seq_show,
33495788b3a0SYonghong Song };
33505788b3a0SYonghong Song #endif
33515788b3a0SYonghong Song 
seq_file_family(const struct seq_file * seq)3352f44b1c51SAditi Ghag static unsigned short seq_file_family(const struct seq_file *seq)
3353f44b1c51SAditi Ghag {
3354f44b1c51SAditi Ghag 	const struct udp_seq_afinfo *afinfo;
3355f44b1c51SAditi Ghag 
3356f44b1c51SAditi Ghag #ifdef CONFIG_BPF_SYSCALL
3357f44b1c51SAditi Ghag 	/* BPF iterator: bpf programs to filter sockets. */
3358f44b1c51SAditi Ghag 	if (seq->op == &bpf_iter_udp_seq_ops)
3359f44b1c51SAditi Ghag 		return AF_UNSPEC;
3360f44b1c51SAditi Ghag #endif
3361f44b1c51SAditi Ghag 
3362f44b1c51SAditi Ghag 	/* Proc fs iterator */
3363f44b1c51SAditi Ghag 	afinfo = pde_data(file_inode(seq->file));
3364f44b1c51SAditi Ghag 	return afinfo->family;
3365f44b1c51SAditi Ghag }
3366f44b1c51SAditi Ghag 
3367c3506372SChristoph Hellwig const struct seq_operations udp_seq_ops = {
3368a3d2599bSChristoph Hellwig 	.start		= udp_seq_start,
3369a3d2599bSChristoph Hellwig 	.next		= udp_seq_next,
3370a3d2599bSChristoph Hellwig 	.stop		= udp_seq_stop,
3371a3d2599bSChristoph Hellwig 	.show		= udp4_seq_show,
3372a3d2599bSChristoph Hellwig };
3373c3506372SChristoph Hellwig EXPORT_SYMBOL(udp_seq_ops);
337473cb88ecSArjan van de Ven 
3375db8dac20SDavid S. Miller static struct udp_seq_afinfo udp4_seq_afinfo = {
3376db8dac20SDavid S. Miller 	.family		= AF_INET,
3377478aee5dSKuniyuki Iwashima 	.udp_table	= NULL,
3378db8dac20SDavid S. Miller };
3379db8dac20SDavid S. Miller 
udp4_proc_init_net(struct net * net)33802c8c1e72SAlexey Dobriyan static int __net_init udp4_proc_init_net(struct net *net)
338115439febSPavel Emelyanov {
3382c3506372SChristoph Hellwig 	if (!proc_create_net_data("udp", 0444, net->proc_net, &udp_seq_ops,
3383c3506372SChristoph Hellwig 			sizeof(struct udp_iter_state), &udp4_seq_afinfo))
3384a3d2599bSChristoph Hellwig 		return -ENOMEM;
3385a3d2599bSChristoph Hellwig 	return 0;
338615439febSPavel Emelyanov }
338715439febSPavel Emelyanov 
udp4_proc_exit_net(struct net * net)33882c8c1e72SAlexey Dobriyan static void __net_exit udp4_proc_exit_net(struct net *net)
338915439febSPavel Emelyanov {
3390a3d2599bSChristoph Hellwig 	remove_proc_entry("udp", net->proc_net);
339115439febSPavel Emelyanov }
339215439febSPavel Emelyanov 
339315439febSPavel Emelyanov static struct pernet_operations udp4_net_ops = {
339415439febSPavel Emelyanov 	.init = udp4_proc_init_net,
339515439febSPavel Emelyanov 	.exit = udp4_proc_exit_net,
339615439febSPavel Emelyanov };
339715439febSPavel Emelyanov 
udp4_proc_init(void)3398db8dac20SDavid S. Miller int __init udp4_proc_init(void)
3399db8dac20SDavid S. Miller {
340015439febSPavel Emelyanov 	return register_pernet_subsys(&udp4_net_ops);
3401db8dac20SDavid S. Miller }
3402db8dac20SDavid S. Miller 
udp4_proc_exit(void)3403db8dac20SDavid S. Miller void udp4_proc_exit(void)
3404db8dac20SDavid S. Miller {
340515439febSPavel Emelyanov 	unregister_pernet_subsys(&udp4_net_ops);
3406db8dac20SDavid S. Miller }
34071da177e4SLinus Torvalds #endif /* CONFIG_PROC_FS */
34081da177e4SLinus Torvalds 
3409f86dcc5aSEric Dumazet static __initdata unsigned long uhash_entries;
set_uhash_entries(char * str)3410f86dcc5aSEric Dumazet static int __init set_uhash_entries(char *str)
3411645ca708SEric Dumazet {
3412413c27d8SEldad Zack 	ssize_t ret;
3413413c27d8SEldad Zack 
3414f86dcc5aSEric Dumazet 	if (!str)
3415f86dcc5aSEric Dumazet 		return 0;
3416413c27d8SEldad Zack 
3417413c27d8SEldad Zack 	ret = kstrtoul(str, 0, &uhash_entries);
3418413c27d8SEldad Zack 	if (ret)
3419413c27d8SEldad Zack 		return 0;
3420413c27d8SEldad Zack 
3421f86dcc5aSEric Dumazet 	if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
3422f86dcc5aSEric Dumazet 		uhash_entries = UDP_HTABLE_SIZE_MIN;
3423f86dcc5aSEric Dumazet 	return 1;
3424f86dcc5aSEric Dumazet }
3425f86dcc5aSEric Dumazet __setup("uhash_entries=", set_uhash_entries);
3426645ca708SEric Dumazet 
udp_table_init(struct udp_table * table,const char * name)3427f86dcc5aSEric Dumazet void __init udp_table_init(struct udp_table *table, const char *name)
3428f86dcc5aSEric Dumazet {
3429f86dcc5aSEric Dumazet 	unsigned int i;
3430f86dcc5aSEric Dumazet 
3431f86dcc5aSEric Dumazet 	table->hash = alloc_large_system_hash(name,
3432512615b6SEric Dumazet 					      2 * sizeof(struct udp_hslot),
3433f86dcc5aSEric Dumazet 					      uhash_entries,
3434f86dcc5aSEric Dumazet 					      21, /* one slot per 2 MB */
3435f86dcc5aSEric Dumazet 					      0,
3436f86dcc5aSEric Dumazet 					      &table->log,
3437f86dcc5aSEric Dumazet 					      &table->mask,
343831fe62b9STim Bird 					      UDP_HTABLE_SIZE_MIN,
34399804985bSKuniyuki Iwashima 					      UDP_HTABLE_SIZE_MAX);
344031fe62b9STim Bird 
3441512615b6SEric Dumazet 	table->hash2 = table->hash + (table->mask + 1);
3442f86dcc5aSEric Dumazet 	for (i = 0; i <= table->mask; i++) {
3443ca065d0cSEric Dumazet 		INIT_HLIST_HEAD(&table->hash[i].head);
3444fdcc8aa9SEric Dumazet 		table->hash[i].count = 0;
3445645ca708SEric Dumazet 		spin_lock_init(&table->hash[i].lock);
3446645ca708SEric Dumazet 	}
3447512615b6SEric Dumazet 	for (i = 0; i <= table->mask; i++) {
3448ca065d0cSEric Dumazet 		INIT_HLIST_HEAD(&table->hash2[i].head);
3449512615b6SEric Dumazet 		table->hash2[i].count = 0;
3450512615b6SEric Dumazet 		spin_lock_init(&table->hash2[i].lock);
3451512615b6SEric Dumazet 	}
3452645ca708SEric Dumazet }
3453645ca708SEric Dumazet 
udp_flow_hashrnd(void)3454723b8e46STom Herbert u32 udp_flow_hashrnd(void)
3455723b8e46STom Herbert {
3456723b8e46STom Herbert 	static u32 hashrnd __read_mostly;
3457723b8e46STom Herbert 
3458723b8e46STom Herbert 	net_get_random_once(&hashrnd, sizeof(hashrnd));
3459723b8e46STom Herbert 
3460723b8e46STom Herbert 	return hashrnd;
3461723b8e46STom Herbert }
3462723b8e46STom Herbert EXPORT_SYMBOL(udp_flow_hashrnd);
3463723b8e46STom Herbert 
udp_sysctl_init(struct net * net)34649804985bSKuniyuki Iwashima static void __net_init udp_sysctl_init(struct net *net)
34651e802951STonghao Zhang {
3466100fdd1fSEric Dumazet 	net->ipv4.sysctl_udp_rmem_min = PAGE_SIZE;
3467100fdd1fSEric Dumazet 	net->ipv4.sysctl_udp_wmem_min = PAGE_SIZE;
34681e802951STonghao Zhang 
34691e802951STonghao Zhang #ifdef CONFIG_NET_L3_MASTER_DEV
34701e802951STonghao Zhang 	net->ipv4.sysctl_udp_l3mdev_accept = 0;
34711e802951STonghao Zhang #endif
34729804985bSKuniyuki Iwashima }
34739804985bSKuniyuki Iwashima 
udp_pernet_table_alloc(unsigned int hash_entries)34749804985bSKuniyuki Iwashima static struct udp_table __net_init *udp_pernet_table_alloc(unsigned int hash_entries)
34759804985bSKuniyuki Iwashima {
34769804985bSKuniyuki Iwashima 	struct udp_table *udptable;
34779804985bSKuniyuki Iwashima 	int i;
34789804985bSKuniyuki Iwashima 
34799804985bSKuniyuki Iwashima 	udptable = kmalloc(sizeof(*udptable), GFP_KERNEL);
34809804985bSKuniyuki Iwashima 	if (!udptable)
34819804985bSKuniyuki Iwashima 		goto out;
34829804985bSKuniyuki Iwashima 
34839804985bSKuniyuki Iwashima 	udptable->hash = vmalloc_huge(hash_entries * 2 * sizeof(struct udp_hslot),
34849804985bSKuniyuki Iwashima 				      GFP_KERNEL_ACCOUNT);
34859804985bSKuniyuki Iwashima 	if (!udptable->hash)
34869804985bSKuniyuki Iwashima 		goto free_table;
34879804985bSKuniyuki Iwashima 
34889804985bSKuniyuki Iwashima 	udptable->hash2 = udptable->hash + hash_entries;
34899804985bSKuniyuki Iwashima 	udptable->mask = hash_entries - 1;
34909804985bSKuniyuki Iwashima 	udptable->log = ilog2(hash_entries);
34919804985bSKuniyuki Iwashima 
34929804985bSKuniyuki Iwashima 	for (i = 0; i < hash_entries; i++) {
34939804985bSKuniyuki Iwashima 		INIT_HLIST_HEAD(&udptable->hash[i].head);
34949804985bSKuniyuki Iwashima 		udptable->hash[i].count = 0;
34959804985bSKuniyuki Iwashima 		spin_lock_init(&udptable->hash[i].lock);
34969804985bSKuniyuki Iwashima 
34979804985bSKuniyuki Iwashima 		INIT_HLIST_HEAD(&udptable->hash2[i].head);
34989804985bSKuniyuki Iwashima 		udptable->hash2[i].count = 0;
34999804985bSKuniyuki Iwashima 		spin_lock_init(&udptable->hash2[i].lock);
35009804985bSKuniyuki Iwashima 	}
35019804985bSKuniyuki Iwashima 
35029804985bSKuniyuki Iwashima 	return udptable;
35039804985bSKuniyuki Iwashima 
35049804985bSKuniyuki Iwashima free_table:
35059804985bSKuniyuki Iwashima 	kfree(udptable);
35069804985bSKuniyuki Iwashima out:
35079804985bSKuniyuki Iwashima 	return NULL;
35089804985bSKuniyuki Iwashima }
35099804985bSKuniyuki Iwashima 
udp_pernet_table_free(struct net * net)35109804985bSKuniyuki Iwashima static void __net_exit udp_pernet_table_free(struct net *net)
35119804985bSKuniyuki Iwashima {
35129804985bSKuniyuki Iwashima 	struct udp_table *udptable = net->ipv4.udp_table;
35139804985bSKuniyuki Iwashima 
35149804985bSKuniyuki Iwashima 	if (udptable == &udp_table)
35159804985bSKuniyuki Iwashima 		return;
35169804985bSKuniyuki Iwashima 
35179804985bSKuniyuki Iwashima 	kvfree(udptable->hash);
35189804985bSKuniyuki Iwashima 	kfree(udptable);
35199804985bSKuniyuki Iwashima }
35209804985bSKuniyuki Iwashima 
udp_set_table(struct net * net)35219804985bSKuniyuki Iwashima static void __net_init udp_set_table(struct net *net)
35229804985bSKuniyuki Iwashima {
35239804985bSKuniyuki Iwashima 	struct udp_table *udptable;
35249804985bSKuniyuki Iwashima 	unsigned int hash_entries;
35259804985bSKuniyuki Iwashima 	struct net *old_net;
35269804985bSKuniyuki Iwashima 
35279804985bSKuniyuki Iwashima 	if (net_eq(net, &init_net))
35289804985bSKuniyuki Iwashima 		goto fallback;
35299804985bSKuniyuki Iwashima 
35309804985bSKuniyuki Iwashima 	old_net = current->nsproxy->net_ns;
35319804985bSKuniyuki Iwashima 	hash_entries = READ_ONCE(old_net->ipv4.sysctl_udp_child_hash_entries);
35329804985bSKuniyuki Iwashima 	if (!hash_entries)
35339804985bSKuniyuki Iwashima 		goto fallback;
35349804985bSKuniyuki Iwashima 
35359804985bSKuniyuki Iwashima 	/* Set min to keep the bitmap on stack in udp_lib_get_port() */
35369804985bSKuniyuki Iwashima 	if (hash_entries < UDP_HTABLE_SIZE_MIN_PERNET)
35379804985bSKuniyuki Iwashima 		hash_entries = UDP_HTABLE_SIZE_MIN_PERNET;
35389804985bSKuniyuki Iwashima 	else
35399804985bSKuniyuki Iwashima 		hash_entries = roundup_pow_of_two(hash_entries);
35409804985bSKuniyuki Iwashima 
35419804985bSKuniyuki Iwashima 	udptable = udp_pernet_table_alloc(hash_entries);
35429804985bSKuniyuki Iwashima 	if (udptable) {
35439804985bSKuniyuki Iwashima 		net->ipv4.udp_table = udptable;
35449804985bSKuniyuki Iwashima 	} else {
35459804985bSKuniyuki Iwashima 		pr_warn("Failed to allocate UDP hash table (entries: %u) "
35469804985bSKuniyuki Iwashima 			"for a netns, fallback to the global one\n",
35479804985bSKuniyuki Iwashima 			hash_entries);
35489804985bSKuniyuki Iwashima fallback:
35499804985bSKuniyuki Iwashima 		net->ipv4.udp_table = &udp_table;
35509804985bSKuniyuki Iwashima 	}
35519804985bSKuniyuki Iwashima }
35529804985bSKuniyuki Iwashima 
udp_pernet_init(struct net * net)35539804985bSKuniyuki Iwashima static int __net_init udp_pernet_init(struct net *net)
35549804985bSKuniyuki Iwashima {
35559804985bSKuniyuki Iwashima 	udp_sysctl_init(net);
35569804985bSKuniyuki Iwashima 	udp_set_table(net);
35571e802951STonghao Zhang 
35581e802951STonghao Zhang 	return 0;
35591e802951STonghao Zhang }
35601e802951STonghao Zhang 
udp_pernet_exit(struct net * net)35619804985bSKuniyuki Iwashima static void __net_exit udp_pernet_exit(struct net *net)
35629804985bSKuniyuki Iwashima {
35639804985bSKuniyuki Iwashima 	udp_pernet_table_free(net);
35649804985bSKuniyuki Iwashima }
35659804985bSKuniyuki Iwashima 
35661e802951STonghao Zhang static struct pernet_operations __net_initdata udp_sysctl_ops = {
35679804985bSKuniyuki Iwashima 	.init	= udp_pernet_init,
35689804985bSKuniyuki Iwashima 	.exit	= udp_pernet_exit,
35691e802951STonghao Zhang };
35701e802951STonghao Zhang 
35715788b3a0SYonghong Song #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
DEFINE_BPF_ITER_FUNC(udp,struct bpf_iter_meta * meta,struct udp_sock * udp_sk,uid_t uid,int bucket)35725788b3a0SYonghong Song DEFINE_BPF_ITER_FUNC(udp, struct bpf_iter_meta *meta,
35735788b3a0SYonghong Song 		     struct udp_sock *udp_sk, uid_t uid, int bucket)
35745788b3a0SYonghong Song 
3575c96dac8dSAditi Ghag static int bpf_iter_udp_realloc_batch(struct bpf_udp_iter_state *iter,
3576c96dac8dSAditi Ghag 				      unsigned int new_batch_sz)
35775788b3a0SYonghong Song {
3578c96dac8dSAditi Ghag 	struct sock **new_batch;
35795788b3a0SYonghong Song 
3580c96dac8dSAditi Ghag 	new_batch = kvmalloc_array(new_batch_sz, sizeof(*new_batch),
3581c96dac8dSAditi Ghag 				   GFP_USER | __GFP_NOWARN);
3582c96dac8dSAditi Ghag 	if (!new_batch)
35835788b3a0SYonghong Song 		return -ENOMEM;
35845788b3a0SYonghong Song 
3585c96dac8dSAditi Ghag 	bpf_iter_udp_put_batch(iter);
3586c96dac8dSAditi Ghag 	kvfree(iter->batch);
3587c96dac8dSAditi Ghag 	iter->batch = new_batch;
3588c96dac8dSAditi Ghag 	iter->max_sk = new_batch_sz;
3589c96dac8dSAditi Ghag 
3590c96dac8dSAditi Ghag 	return 0;
3591c96dac8dSAditi Ghag }
3592c96dac8dSAditi Ghag 
3593c96dac8dSAditi Ghag #define INIT_BATCH_SZ 16
3594c96dac8dSAditi Ghag 
bpf_iter_init_udp(void * priv_data,struct bpf_iter_aux_info * aux)35955788b3a0SYonghong Song static int bpf_iter_init_udp(void *priv_data, struct bpf_iter_aux_info *aux)
35965788b3a0SYonghong Song {
3597c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = priv_data;
3598c96dac8dSAditi Ghag 	int ret;
3599c96dac8dSAditi Ghag 
3600f9c79272SYonghong Song 	ret = bpf_iter_init_seq_net(priv_data, aux);
36015788b3a0SYonghong Song 	if (ret)
3602c96dac8dSAditi Ghag 		return ret;
3603c96dac8dSAditi Ghag 
3604c96dac8dSAditi Ghag 	ret = bpf_iter_udp_realloc_batch(iter, INIT_BATCH_SZ);
3605c96dac8dSAditi Ghag 	if (ret)
3606c96dac8dSAditi Ghag 		bpf_iter_fini_seq_net(priv_data);
3607c96dac8dSAditi Ghag 
36085788b3a0SYonghong Song 	return ret;
36095788b3a0SYonghong Song }
36105788b3a0SYonghong Song 
bpf_iter_fini_udp(void * priv_data)36115788b3a0SYonghong Song static void bpf_iter_fini_udp(void *priv_data)
36125788b3a0SYonghong Song {
3613c96dac8dSAditi Ghag 	struct bpf_udp_iter_state *iter = priv_data;
36145788b3a0SYonghong Song 
36155788b3a0SYonghong Song 	bpf_iter_fini_seq_net(priv_data);
3616c96dac8dSAditi Ghag 	kvfree(iter->batch);
36175788b3a0SYonghong Song }
36185788b3a0SYonghong Song 
361914fc6bd6SYonghong Song static const struct bpf_iter_seq_info udp_seq_info = {
36205788b3a0SYonghong Song 	.seq_ops		= &bpf_iter_udp_seq_ops,
36215788b3a0SYonghong Song 	.init_seq_private	= bpf_iter_init_udp,
36225788b3a0SYonghong Song 	.fini_seq_private	= bpf_iter_fini_udp,
3623c96dac8dSAditi Ghag 	.seq_priv_size		= sizeof(struct bpf_udp_iter_state),
362414fc6bd6SYonghong Song };
362514fc6bd6SYonghong Song 
362614fc6bd6SYonghong Song static struct bpf_iter_reg udp_reg_info = {
362714fc6bd6SYonghong Song 	.target			= "udp",
36285788b3a0SYonghong Song 	.ctx_arg_info_size	= 1,
36295788b3a0SYonghong Song 	.ctx_arg_info		= {
36305788b3a0SYonghong Song 		{ offsetof(struct bpf_iter__udp, udp_sk),
36314ddbcb88SAditi Ghag 		  PTR_TO_BTF_ID_OR_NULL | PTR_TRUSTED },
36325788b3a0SYonghong Song 	},
363314fc6bd6SYonghong Song 	.seq_info		= &udp_seq_info,
36345788b3a0SYonghong Song };
36355788b3a0SYonghong Song 
bpf_iter_register(void)36365788b3a0SYonghong Song static void __init bpf_iter_register(void)
36375788b3a0SYonghong Song {
3638951cf368SYonghong Song 	udp_reg_info.ctx_arg_info[0].btf_id = btf_sock_ids[BTF_SOCK_TYPE_UDP];
36395788b3a0SYonghong Song 	if (bpf_iter_reg_target(&udp_reg_info))
36405788b3a0SYonghong Song 		pr_warn("Warning: could not register bpf iterator udp\n");
36415788b3a0SYonghong Song }
36425788b3a0SYonghong Song #endif
36435788b3a0SYonghong Song 
udp_init(void)364495766fffSHideo Aoki void __init udp_init(void)
364595766fffSHideo Aoki {
3646f03d78dbSEric Dumazet 	unsigned long limit;
36474b272750SEric Dumazet 	unsigned int i;
364895766fffSHideo Aoki 
3649f86dcc5aSEric Dumazet 	udp_table_init(&udp_table, "UDP");
3650f03d78dbSEric Dumazet 	limit = nr_free_buffer_pages() / 8;
365195766fffSHideo Aoki 	limit = max(limit, 128UL);
365295766fffSHideo Aoki 	sysctl_udp_mem[0] = limit / 4 * 3;
365395766fffSHideo Aoki 	sysctl_udp_mem[1] = limit;
365495766fffSHideo Aoki 	sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
365595766fffSHideo Aoki 
36564b272750SEric Dumazet 	/* 16 spinlocks per cpu */
36574b272750SEric Dumazet 	udp_busylocks_log = ilog2(nr_cpu_ids) + 4;
36584b272750SEric Dumazet 	udp_busylocks = kmalloc(sizeof(spinlock_t) << udp_busylocks_log,
36594b272750SEric Dumazet 				GFP_KERNEL);
36604b272750SEric Dumazet 	if (!udp_busylocks)
36614b272750SEric Dumazet 		panic("UDP: failed to alloc udp_busylocks\n");
36624b272750SEric Dumazet 	for (i = 0; i < (1U << udp_busylocks_log); i++)
36634b272750SEric Dumazet 		spin_lock_init(udp_busylocks + i);
36641e802951STonghao Zhang 
36651e802951STonghao Zhang 	if (register_pernet_subsys(&udp_sysctl_ops))
36661e802951STonghao Zhang 		panic("UDP: failed to init sysctl parameters.\n");
36675788b3a0SYonghong Song 
36685788b3a0SYonghong Song #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
36695788b3a0SYonghong Song 	bpf_iter_register();
36705788b3a0SYonghong Song #endif
367195766fffSHideo Aoki }
3672