• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * INET		An implementation of the TCP/IP protocol suite for the LINUX
4  *		operating system.  INET is implemented using the  BSD Socket
5  *		interface as the means of communication with the user level.
6  *
7  *		The User Datagram Protocol (UDP).
8  *
9  * Authors:	Ross Biro
10  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
11  *		Arnt Gulbrandsen, <agulbra@nvg.unit.no>
12  *		Alan Cox, <alan@lxorguk.ukuu.org.uk>
13  *		Hirokazu Takahashi, <taka@valinux.co.jp>
14  *
15  * Fixes:
16  *		Alan Cox	:	verify_area() calls
17  *		Alan Cox	: 	stopped close while in use off icmp
18  *					messages. Not a fix but a botch that
19  *					for udp at least is 'valid'.
20  *		Alan Cox	:	Fixed icmp handling properly
21  *		Alan Cox	: 	Correct error for oversized datagrams
22  *		Alan Cox	:	Tidied select() semantics.
23  *		Alan Cox	:	udp_err() fixed properly, also now
24  *					select and read wake correctly on errors
25  *		Alan Cox	:	udp_send verify_area moved to avoid mem leak
26  *		Alan Cox	:	UDP can count its memory
27  *		Alan Cox	:	send to an unknown connection causes
28  *					an ECONNREFUSED off the icmp, but
29  *					does NOT close.
30  *		Alan Cox	:	Switched to new sk_buff handlers. No more backlog!
31  *		Alan Cox	:	Using generic datagram code. Even smaller and the PEEK
32  *					bug no longer crashes it.
33  *		Fred Van Kempen	: 	Net2e support for sk->broadcast.
34  *		Alan Cox	:	Uses skb_free_datagram
35  *		Alan Cox	:	Added get/set sockopt support.
36  *		Alan Cox	:	Broadcasting without option set returns EACCES.
37  *		Alan Cox	:	No wakeup calls. Instead we now use the callbacks.
38  *		Alan Cox	:	Use ip_tos and ip_ttl
39  *		Alan Cox	:	SNMP Mibs
40  *		Alan Cox	:	MSG_DONTROUTE, and 0.0.0.0 support.
41  *		Matt Dillon	:	UDP length checks.
42  *		Alan Cox	:	Smarter af_inet used properly.
43  *		Alan Cox	:	Use new kernel side addressing.
44  *		Alan Cox	:	Incorrect return on truncated datagram receive.
45  *	Arnt Gulbrandsen 	:	New udp_send and stuff
46  *		Alan Cox	:	Cache last socket
47  *		Alan Cox	:	Route cache
48  *		Jon Peatfield	:	Minor efficiency fix to sendto().
49  *		Mike Shaver	:	RFC1122 checks.
50  *		Alan Cox	:	Nonblocking error fix.
51  *	Willy Konynenberg	:	Transparent proxying support.
52  *		Mike McLagan	:	Routing by source
53  *		David S. Miller	:	New socket lookup architecture.
54  *					Last socket cache retained as it
55  *					does have a high hit rate.
56  *		Olaf Kirch	:	Don't linearise iovec on sendmsg.
57  *		Andi Kleen	:	Some cleanups, cache destination entry
58  *					for connect.
59  *	Vitaly E. Lavrov	:	Transparent proxy revived after year coma.
60  *		Melvin Smith	:	Check msg_name not msg_namelen in sendto(),
61  *					return ENOTCONN for unconnected sockets (POSIX)
62  *		Janos Farkas	:	don't deliver multi/broadcasts to a different
63  *					bound-to-device socket
64  *	Hirokazu Takahashi	:	HW checksumming for outgoing UDP
65  *					datagrams.
66  *	Hirokazu Takahashi	:	sendfile() on UDP works now.
67  *		Arnaldo C. Melo :	convert /proc/net/udp to seq_file
68  *	YOSHIFUJI Hideaki @USAGI and:	Support IPV6_V6ONLY socket option, which
69  *	Alexey Kuznetsov:		allow both IPv4 and IPv6 sockets to bind
70  *					a single port at the same time.
71  *	Derek Atkins <derek@ihtfp.com>: Add Encapulation Support
72  *	James Chapman		:	Add L2TP encapsulation type.
73  */
74 
75 #define pr_fmt(fmt) "UDP: " fmt
76 
77 #include <linux/bpf-cgroup.h>
78 #include <linux/uaccess.h>
79 #include <asm/ioctls.h>
80 #include <linux/memblock.h>
81 #include <linux/highmem.h>
82 #include <linux/types.h>
83 #include <linux/fcntl.h>
84 #include <linux/module.h>
85 #include <linux/socket.h>
86 #include <linux/sockios.h>
87 #include <linux/igmp.h>
88 #include <linux/inetdevice.h>
89 #include <linux/in.h>
90 #include <linux/errno.h>
91 #include <linux/timer.h>
92 #include <linux/mm.h>
93 #include <linux/inet.h>
94 #include <linux/netdevice.h>
95 #include <linux/slab.h>
96 #include <net/tcp_states.h>
97 #include <linux/skbuff.h>
98 #include <linux/proc_fs.h>
99 #include <linux/seq_file.h>
100 #include <net/net_namespace.h>
101 #include <net/icmp.h>
102 #include <net/inet_hashtables.h>
103 #include <net/ip_tunnels.h>
104 #include <net/route.h>
105 #include <net/checksum.h>
106 #include <net/gso.h>
107 #include <net/xfrm.h>
108 #include <trace/events/udp.h>
109 #include <linux/static_key.h>
110 #include <linux/btf_ids.h>
111 #include <trace/events/skb.h>
112 #include <net/busy_poll.h>
113 #include "udp_impl.h"
114 #include <net/sock_reuseport.h>
115 #include <net/addrconf.h>
116 #include <net/udp_tunnel.h>
117 #include <net/gro.h>
118 #if IS_ENABLED(CONFIG_IPV6)
119 #include <net/ipv6_stubs.h>
120 #endif
121 
122 struct udp_table udp_table __read_mostly;
123 EXPORT_SYMBOL(udp_table);
124 
125 long sysctl_udp_mem[3] __read_mostly;
126 EXPORT_SYMBOL(sysctl_udp_mem);
127 
128 atomic_long_t udp_memory_allocated ____cacheline_aligned_in_smp;
129 EXPORT_SYMBOL(udp_memory_allocated);
130 DEFINE_PER_CPU(int, udp_memory_per_cpu_fw_alloc);
131 EXPORT_PER_CPU_SYMBOL_GPL(udp_memory_per_cpu_fw_alloc);
132 
133 #define MAX_UDP_PORTS 65536
134 #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN_PERNET)
135 
udp_get_table_prot(struct sock * sk)136 static struct udp_table *udp_get_table_prot(struct sock *sk)
137 {
138 	return sk->sk_prot->h.udp_table ? : sock_net(sk)->ipv4.udp_table;
139 }
140 
udp_lib_lport_inuse(struct net * net,__u16 num,const struct udp_hslot * hslot,unsigned long * bitmap,struct sock * sk,unsigned int log)141 static int udp_lib_lport_inuse(struct net *net, __u16 num,
142 			       const struct udp_hslot *hslot,
143 			       unsigned long *bitmap,
144 			       struct sock *sk, unsigned int log)
145 {
146 	struct sock *sk2;
147 	kuid_t uid = sock_i_uid(sk);
148 
149 	sk_for_each(sk2, &hslot->head) {
150 		if (net_eq(sock_net(sk2), net) &&
151 		    sk2 != sk &&
152 		    (bitmap || udp_sk(sk2)->udp_port_hash == num) &&
153 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
154 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
155 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
156 		    inet_rcv_saddr_equal(sk, sk2, true)) {
157 			if (sk2->sk_reuseport && sk->sk_reuseport &&
158 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
159 			    uid_eq(uid, sock_i_uid(sk2))) {
160 				if (!bitmap)
161 					return 0;
162 			} else {
163 				if (!bitmap)
164 					return 1;
165 				__set_bit(udp_sk(sk2)->udp_port_hash >> log,
166 					  bitmap);
167 			}
168 		}
169 	}
170 	return 0;
171 }
172 
173 /*
174  * Note: we still hold spinlock of primary hash chain, so no other writer
175  * can insert/delete a socket with local_port == num
176  */
udp_lib_lport_inuse2(struct net * net,__u16 num,struct udp_hslot * hslot2,struct sock * sk)177 static int udp_lib_lport_inuse2(struct net *net, __u16 num,
178 				struct udp_hslot *hslot2,
179 				struct sock *sk)
180 {
181 	struct sock *sk2;
182 	kuid_t uid = sock_i_uid(sk);
183 	int res = 0;
184 
185 	spin_lock(&hslot2->lock);
186 	udp_portaddr_for_each_entry(sk2, &hslot2->head) {
187 		if (net_eq(sock_net(sk2), net) &&
188 		    sk2 != sk &&
189 		    (udp_sk(sk2)->udp_port_hash == num) &&
190 		    (!sk2->sk_reuse || !sk->sk_reuse) &&
191 		    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
192 		     sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
193 		    inet_rcv_saddr_equal(sk, sk2, true)) {
194 			if (sk2->sk_reuseport && sk->sk_reuseport &&
195 			    !rcu_access_pointer(sk->sk_reuseport_cb) &&
196 			    uid_eq(uid, sock_i_uid(sk2))) {
197 				res = 0;
198 			} else {
199 				res = 1;
200 			}
201 			break;
202 		}
203 	}
204 	spin_unlock(&hslot2->lock);
205 	return res;
206 }
207 
udp_reuseport_add_sock(struct sock * sk,struct udp_hslot * hslot)208 static int udp_reuseport_add_sock(struct sock *sk, struct udp_hslot *hslot)
209 {
210 	struct net *net = sock_net(sk);
211 	kuid_t uid = sock_i_uid(sk);
212 	struct sock *sk2;
213 
214 	sk_for_each(sk2, &hslot->head) {
215 		if (net_eq(sock_net(sk2), net) &&
216 		    sk2 != sk &&
217 		    sk2->sk_family == sk->sk_family &&
218 		    ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
219 		    (udp_sk(sk2)->udp_port_hash == udp_sk(sk)->udp_port_hash) &&
220 		    (sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
221 		    sk2->sk_reuseport && uid_eq(uid, sock_i_uid(sk2)) &&
222 		    inet_rcv_saddr_equal(sk, sk2, false)) {
223 			return reuseport_add_sock(sk, sk2,
224 						  inet_rcv_saddr_any(sk));
225 		}
226 	}
227 
228 	return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
229 }
230 
231 /**
232  *  udp_lib_get_port  -  UDP/-Lite port lookup for IPv4 and IPv6
233  *
234  *  @sk:          socket struct in question
235  *  @snum:        port number to look up
236  *  @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
237  *                   with NULL address
238  */
udp_lib_get_port(struct sock * sk,unsigned short snum,unsigned int hash2_nulladdr)239 int udp_lib_get_port(struct sock *sk, unsigned short snum,
240 		     unsigned int hash2_nulladdr)
241 {
242 	struct udp_table *udptable = udp_get_table_prot(sk);
243 	struct udp_hslot *hslot, *hslot2;
244 	struct net *net = sock_net(sk);
245 	int error = -EADDRINUSE;
246 
247 	if (!snum) {
248 		DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
249 		unsigned short first, last;
250 		int low, high, remaining;
251 		unsigned int rand;
252 
253 		inet_sk_get_local_port_range(sk, &low, &high);
254 		remaining = (high - low) + 1;
255 
256 		rand = get_random_u32();
257 		first = reciprocal_scale(rand, remaining) + low;
258 		/*
259 		 * force rand to be an odd multiple of UDP_HTABLE_SIZE
260 		 */
261 		rand = (rand | 1) * (udptable->mask + 1);
262 		last = first + udptable->mask + 1;
263 		do {
264 			hslot = udp_hashslot(udptable, net, first);
265 			bitmap_zero(bitmap, PORTS_PER_CHAIN);
266 			spin_lock_bh(&hslot->lock);
267 			udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
268 					    udptable->log);
269 
270 			snum = first;
271 			/*
272 			 * Iterate on all possible values of snum for this hash.
273 			 * Using steps of an odd multiple of UDP_HTABLE_SIZE
274 			 * give us randomization and full range coverage.
275 			 */
276 			do {
277 				if (low <= snum && snum <= high &&
278 				    !test_bit(snum >> udptable->log, bitmap) &&
279 				    !inet_is_local_reserved_port(net, snum))
280 					goto found;
281 				snum += rand;
282 			} while (snum != first);
283 			spin_unlock_bh(&hslot->lock);
284 			cond_resched();
285 		} while (++first != last);
286 		goto fail;
287 	} else {
288 		hslot = udp_hashslot(udptable, net, snum);
289 		spin_lock_bh(&hslot->lock);
290 		if (hslot->count > 10) {
291 			int exist;
292 			unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
293 
294 			slot2          &= udptable->mask;
295 			hash2_nulladdr &= udptable->mask;
296 
297 			hslot2 = udp_hashslot2(udptable, slot2);
298 			if (hslot->count < hslot2->count)
299 				goto scan_primary_hash;
300 
301 			exist = udp_lib_lport_inuse2(net, snum, hslot2, sk);
302 			if (!exist && (hash2_nulladdr != slot2)) {
303 				hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
304 				exist = udp_lib_lport_inuse2(net, snum, hslot2,
305 							     sk);
306 			}
307 			if (exist)
308 				goto fail_unlock;
309 			else
310 				goto found;
311 		}
312 scan_primary_hash:
313 		if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, 0))
314 			goto fail_unlock;
315 	}
316 found:
317 	inet_sk(sk)->inet_num = snum;
318 	udp_sk(sk)->udp_port_hash = snum;
319 	udp_sk(sk)->udp_portaddr_hash ^= snum;
320 	if (sk_unhashed(sk)) {
321 		if (sk->sk_reuseport &&
322 		    udp_reuseport_add_sock(sk, hslot)) {
323 			inet_sk(sk)->inet_num = 0;
324 			udp_sk(sk)->udp_port_hash = 0;
325 			udp_sk(sk)->udp_portaddr_hash ^= snum;
326 			goto fail_unlock;
327 		}
328 
329 		sock_set_flag(sk, SOCK_RCU_FREE);
330 
331 		sk_add_node_rcu(sk, &hslot->head);
332 		hslot->count++;
333 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
334 
335 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
336 		spin_lock(&hslot2->lock);
337 		if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
338 		    sk->sk_family == AF_INET6)
339 			hlist_add_tail_rcu(&udp_sk(sk)->udp_portaddr_node,
340 					   &hslot2->head);
341 		else
342 			hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
343 					   &hslot2->head);
344 		hslot2->count++;
345 		spin_unlock(&hslot2->lock);
346 	}
347 
348 	error = 0;
349 fail_unlock:
350 	spin_unlock_bh(&hslot->lock);
351 fail:
352 	return error;
353 }
354 EXPORT_SYMBOL(udp_lib_get_port);
355 
udp_v4_get_port(struct sock * sk,unsigned short snum)356 int udp_v4_get_port(struct sock *sk, unsigned short snum)
357 {
358 	unsigned int hash2_nulladdr =
359 		ipv4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
360 	unsigned int hash2_partial =
361 		ipv4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
362 
363 	/* precompute partial secondary hash */
364 	udp_sk(sk)->udp_portaddr_hash = hash2_partial;
365 	return udp_lib_get_port(sk, snum, hash2_nulladdr);
366 }
367 
compute_score(struct sock * sk,struct net * net,__be32 saddr,__be16 sport,__be32 daddr,unsigned short hnum,int dif,int sdif)368 static int compute_score(struct sock *sk, struct net *net,
369 			 __be32 saddr, __be16 sport,
370 			 __be32 daddr, unsigned short hnum,
371 			 int dif, int sdif)
372 {
373 	int score;
374 	struct inet_sock *inet;
375 	bool dev_match;
376 
377 	if (!net_eq(sock_net(sk), net) ||
378 	    udp_sk(sk)->udp_port_hash != hnum ||
379 	    ipv6_only_sock(sk))
380 		return -1;
381 
382 	if (sk->sk_rcv_saddr != daddr)
383 		return -1;
384 
385 	score = (sk->sk_family == PF_INET) ? 2 : 1;
386 
387 	inet = inet_sk(sk);
388 	if (inet->inet_daddr) {
389 		if (inet->inet_daddr != saddr)
390 			return -1;
391 		score += 4;
392 	}
393 
394 	if (inet->inet_dport) {
395 		if (inet->inet_dport != sport)
396 			return -1;
397 		score += 4;
398 	}
399 
400 	dev_match = udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if,
401 					dif, sdif);
402 	if (!dev_match)
403 		return -1;
404 	if (sk->sk_bound_dev_if)
405 		score += 4;
406 
407 	if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
408 		score++;
409 	return score;
410 }
411 
412 INDIRECT_CALLABLE_SCOPE
udp_ehashfn(const struct net * net,const __be32 laddr,const __u16 lport,const __be32 faddr,const __be16 fport)413 u32 udp_ehashfn(const struct net *net, const __be32 laddr, const __u16 lport,
414 		const __be32 faddr, const __be16 fport)
415 {
416 	static u32 udp_ehash_secret __read_mostly;
417 
418 	net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret));
419 
420 	return __inet_ehashfn(laddr, lport, faddr, fport,
421 			      udp_ehash_secret + net_hash_mix(net));
422 }
423 
424 /**
425  * udp4_lib_lookup1() - Simplified lookup using primary hash (destination port)
426  * @net:	Network namespace
427  * @saddr:	Source address, network order
428  * @sport:	Source port, network order
429  * @daddr:	Destination address, network order
430  * @hnum:	Destination port, host order
431  * @dif:	Destination interface index
432  * @sdif:	Destination bridge port index, if relevant
433  * @udptable:	Set of UDP hash tables
434  *
435  * Simplified lookup to be used as fallback if no sockets are found due to a
436  * potential race between (receive) address change, and lookup happening before
437  * the rehash operation. This function ignores SO_REUSEPORT groups while scoring
438  * result sockets, because if we have one, we don't need the fallback at all.
439  *
440  * Called under rcu_read_lock().
441  *
442  * Return: socket with highest matching score if any, NULL if none
443  */
udp4_lib_lookup1(const struct net * net,__be32 saddr,__be16 sport,__be32 daddr,unsigned int hnum,int dif,int sdif,const struct udp_table * udptable)444 static struct sock *udp4_lib_lookup1(const struct net *net,
445 				     __be32 saddr, __be16 sport,
446 				     __be32 daddr, unsigned int hnum,
447 				     int dif, int sdif,
448 				     const struct udp_table *udptable)
449 {
450 	unsigned int slot = udp_hashfn(net, hnum, udptable->mask);
451 	struct udp_hslot *hslot = &udptable->hash[slot];
452 	struct sock *sk, *result = NULL;
453 	int score, badness = 0;
454 
455 	sk_for_each_rcu(sk, &hslot->head) {
456 		score = compute_score(sk, (struct net *)net,
457 				      saddr, sport, daddr, hnum, dif, sdif);
458 		if (score > badness) {
459 			result = sk;
460 			badness = score;
461 		}
462 	}
463 
464 	return result;
465 }
466 
467 /* called with rcu_read_lock() */
udp4_lib_lookup2(struct net * net,__be32 saddr,__be16 sport,__be32 daddr,unsigned int hnum,int dif,int sdif,struct udp_hslot * hslot2,struct sk_buff * skb)468 static struct sock *udp4_lib_lookup2(struct net *net,
469 				     __be32 saddr, __be16 sport,
470 				     __be32 daddr, unsigned int hnum,
471 				     int dif, int sdif,
472 				     struct udp_hslot *hslot2,
473 				     struct sk_buff *skb)
474 {
475 	struct sock *sk, *result;
476 	int score, badness;
477 	bool need_rescore;
478 
479 	result = NULL;
480 	badness = 0;
481 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
482 		need_rescore = false;
483 rescore:
484 		score = compute_score(need_rescore ? result : sk, net, saddr,
485 				      sport, daddr, hnum, dif, sdif);
486 		if (score > badness) {
487 			badness = score;
488 
489 			if (need_rescore)
490 				continue;
491 
492 			if (sk->sk_state == TCP_ESTABLISHED) {
493 				result = sk;
494 				continue;
495 			}
496 
497 			result = inet_lookup_reuseport(net, sk, skb, sizeof(struct udphdr),
498 						       saddr, sport, daddr, hnum, udp_ehashfn);
499 			if (!result) {
500 				result = sk;
501 				continue;
502 			}
503 
504 			/* Fall back to scoring if group has connections */
505 			if (!reuseport_has_conns(sk))
506 				return result;
507 
508 			/* Reuseport logic returned an error, keep original score. */
509 			if (IS_ERR(result))
510 				continue;
511 
512 			/* compute_score is too long of a function to be
513 			 * inlined, and calling it again here yields
514 			 * measureable overhead for some
515 			 * workloads. Work around it by jumping
516 			 * backwards to rescore 'result'.
517 			 */
518 			need_rescore = true;
519 			goto rescore;
520 		}
521 	}
522 	return result;
523 }
524 
525 /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
526  * harder than this. -DaveM
527  */
__udp4_lib_lookup(struct net * net,__be32 saddr,__be16 sport,__be32 daddr,__be16 dport,int dif,int sdif,struct udp_table * udptable,struct sk_buff * skb)528 struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
529 		__be16 sport, __be32 daddr, __be16 dport, int dif,
530 		int sdif, struct udp_table *udptable, struct sk_buff *skb)
531 {
532 	unsigned short hnum = ntohs(dport);
533 	unsigned int hash2, slot2;
534 	struct udp_hslot *hslot2;
535 	struct sock *result, *sk;
536 
537 	hash2 = ipv4_portaddr_hash(net, daddr, hnum);
538 	slot2 = hash2 & udptable->mask;
539 	hslot2 = &udptable->hash2[slot2];
540 
541 	/* Lookup connected or non-wildcard socket */
542 	result = udp4_lib_lookup2(net, saddr, sport,
543 				  daddr, hnum, dif, sdif,
544 				  hslot2, skb);
545 	if (!IS_ERR_OR_NULL(result) && result->sk_state == TCP_ESTABLISHED)
546 		goto done;
547 
548 	/* Lookup redirect from BPF */
549 	if (static_branch_unlikely(&bpf_sk_lookup_enabled) &&
550 	    udptable == net->ipv4.udp_table) {
551 		sk = inet_lookup_run_sk_lookup(net, IPPROTO_UDP, skb, sizeof(struct udphdr),
552 					       saddr, sport, daddr, hnum, dif,
553 					       udp_ehashfn);
554 		if (sk) {
555 			result = sk;
556 			goto done;
557 		}
558 	}
559 
560 	/* Got non-wildcard socket or error on first lookup */
561 	if (result)
562 		goto done;
563 
564 	/* Lookup wildcard sockets */
565 	hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
566 	slot2 = hash2 & udptable->mask;
567 	hslot2 = &udptable->hash2[slot2];
568 
569 	result = udp4_lib_lookup2(net, saddr, sport,
570 				  htonl(INADDR_ANY), hnum, dif, sdif,
571 				  hslot2, skb);
572 	if (!IS_ERR_OR_NULL(result))
573 		goto done;
574 
575 	/* Primary hash (destination port) lookup as fallback for this race:
576 	 *   1. __ip4_datagram_connect() sets sk_rcv_saddr
577 	 *   2. lookup (this function): new sk_rcv_saddr, hashes not updated yet
578 	 *   3. rehash operation updating _secondary and four-tuple_ hashes
579 	 * The primary hash doesn't need an update after 1., so, thanks to this
580 	 * further step, 1. and 3. don't need to be atomic against the lookup.
581 	 */
582 	result = udp4_lib_lookup1(net, saddr, sport, daddr, hnum, dif, sdif,
583 				  udptable);
584 
585 done:
586 	if (IS_ERR(result))
587 		return NULL;
588 	return result;
589 }
590 EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
591 
__udp4_lib_lookup_skb(struct sk_buff * skb,__be16 sport,__be16 dport,struct udp_table * udptable)592 static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
593 						 __be16 sport, __be16 dport,
594 						 struct udp_table *udptable)
595 {
596 	const struct iphdr *iph = ip_hdr(skb);
597 
598 	return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
599 				 iph->daddr, dport, inet_iif(skb),
600 				 inet_sdif(skb), udptable, skb);
601 }
602 
udp4_lib_lookup_skb(const struct sk_buff * skb,__be16 sport,__be16 dport)603 struct sock *udp4_lib_lookup_skb(const struct sk_buff *skb,
604 				 __be16 sport, __be16 dport)
605 {
606 	const u16 offset = NAPI_GRO_CB(skb)->network_offsets[skb->encapsulation];
607 	const struct iphdr *iph = (struct iphdr *)(skb->data + offset);
608 	struct net *net = dev_net(skb->dev);
609 	int iif, sdif;
610 
611 	inet_get_iif_sdif(skb, &iif, &sdif);
612 
613 	return __udp4_lib_lookup(net, iph->saddr, sport,
614 				 iph->daddr, dport, iif,
615 				 sdif, net->ipv4.udp_table, NULL);
616 }
617 
618 /* Must be called under rcu_read_lock().
619  * Does increment socket refcount.
620  */
621 #if IS_ENABLED(CONFIG_NF_TPROXY_IPV4) || IS_ENABLED(CONFIG_NF_SOCKET_IPV4)
udp4_lib_lookup(struct net * net,__be32 saddr,__be16 sport,__be32 daddr,__be16 dport,int dif)622 struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
623 			     __be32 daddr, __be16 dport, int dif)
624 {
625 	struct sock *sk;
626 
627 	sk = __udp4_lib_lookup(net, saddr, sport, daddr, dport,
628 			       dif, 0, net->ipv4.udp_table, NULL);
629 	if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
630 		sk = NULL;
631 	return sk;
632 }
633 EXPORT_SYMBOL_GPL(udp4_lib_lookup);
634 #endif
635 
__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)636 static inline bool __udp_is_mcast_sock(struct net *net, const struct sock *sk,
637 				       __be16 loc_port, __be32 loc_addr,
638 				       __be16 rmt_port, __be32 rmt_addr,
639 				       int dif, int sdif, unsigned short hnum)
640 {
641 	const struct inet_sock *inet = inet_sk(sk);
642 
643 	if (!net_eq(sock_net(sk), net) ||
644 	    udp_sk(sk)->udp_port_hash != hnum ||
645 	    (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
646 	    (inet->inet_dport != rmt_port && inet->inet_dport) ||
647 	    (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) ||
648 	    ipv6_only_sock(sk) ||
649 	    !udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif))
650 		return false;
651 	if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif, sdif))
652 		return false;
653 	return true;
654 }
655 
656 DEFINE_STATIC_KEY_FALSE(udp_encap_needed_key);
657 EXPORT_SYMBOL(udp_encap_needed_key);
658 
659 #if IS_ENABLED(CONFIG_IPV6)
660 DEFINE_STATIC_KEY_FALSE(udpv6_encap_needed_key);
661 EXPORT_SYMBOL(udpv6_encap_needed_key);
662 #endif
663 
udp_encap_enable(void)664 void udp_encap_enable(void)
665 {
666 	static_branch_inc(&udp_encap_needed_key);
667 }
668 EXPORT_SYMBOL(udp_encap_enable);
669 
udp_encap_disable(void)670 void udp_encap_disable(void)
671 {
672 	static_branch_dec(&udp_encap_needed_key);
673 }
674 EXPORT_SYMBOL(udp_encap_disable);
675 
676 /* Handler for tunnels with arbitrary destination ports: no socket lookup, go
677  * through error handlers in encapsulations looking for a match.
678  */
__udp4_lib_err_encap_no_sk(struct sk_buff * skb,u32 info)679 static int __udp4_lib_err_encap_no_sk(struct sk_buff *skb, u32 info)
680 {
681 	int i;
682 
683 	for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) {
684 		int (*handler)(struct sk_buff *skb, u32 info);
685 		const struct ip_tunnel_encap_ops *encap;
686 
687 		encap = rcu_dereference(iptun_encaps[i]);
688 		if (!encap)
689 			continue;
690 		handler = encap->err_handler;
691 		if (handler && !handler(skb, info))
692 			return 0;
693 	}
694 
695 	return -ENOENT;
696 }
697 
698 /* Try to match ICMP errors to UDP tunnels by looking up a socket without
699  * reversing source and destination port: this will match tunnels that force the
700  * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that
701  * lwtunnels might actually break this assumption by being configured with
702  * different destination ports on endpoints, in this case we won't be able to
703  * trace ICMP messages back to them.
704  *
705  * If this doesn't match any socket, probe tunnels with arbitrary destination
706  * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port
707  * we've sent packets to won't necessarily match the local destination port.
708  *
709  * Then ask the tunnel implementation to match the error against a valid
710  * association.
711  *
712  * Return an error if we can't find a match, the socket if we need further
713  * processing, zero otherwise.
714  */
__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)715 static struct sock *__udp4_lib_err_encap(struct net *net,
716 					 const struct iphdr *iph,
717 					 struct udphdr *uh,
718 					 struct udp_table *udptable,
719 					 struct sock *sk,
720 					 struct sk_buff *skb, u32 info)
721 {
722 	int (*lookup)(struct sock *sk, struct sk_buff *skb);
723 	int network_offset, transport_offset;
724 	struct udp_sock *up;
725 
726 	network_offset = skb_network_offset(skb);
727 	transport_offset = skb_transport_offset(skb);
728 
729 	/* Network header needs to point to the outer IPv4 header inside ICMP */
730 	skb_reset_network_header(skb);
731 
732 	/* Transport header needs to point to the UDP header */
733 	skb_set_transport_header(skb, iph->ihl << 2);
734 
735 	if (sk) {
736 		up = udp_sk(sk);
737 
738 		lookup = READ_ONCE(up->encap_err_lookup);
739 		if (lookup && lookup(sk, skb))
740 			sk = NULL;
741 
742 		goto out;
743 	}
744 
745 	sk = __udp4_lib_lookup(net, iph->daddr, uh->source,
746 			       iph->saddr, uh->dest, skb->dev->ifindex, 0,
747 			       udptable, NULL);
748 	if (sk) {
749 		up = udp_sk(sk);
750 
751 		lookup = READ_ONCE(up->encap_err_lookup);
752 		if (!lookup || lookup(sk, skb))
753 			sk = NULL;
754 	}
755 
756 out:
757 	if (!sk)
758 		sk = ERR_PTR(__udp4_lib_err_encap_no_sk(skb, info));
759 
760 	skb_set_transport_header(skb, transport_offset);
761 	skb_set_network_header(skb, network_offset);
762 
763 	return sk;
764 }
765 
766 /*
767  * This routine is called by the ICMP module when it gets some
768  * sort of error condition.  If err < 0 then the socket should
769  * be closed and the error returned to the user.  If err > 0
770  * it's just the icmp type << 8 | icmp code.
771  * Header points to the ip header of the error packet. We move
772  * on past this. Then (as it used to claim before adjustment)
773  * header points to the first 8 bytes of the udp header.  We need
774  * to find the appropriate port.
775  */
776 
__udp4_lib_err(struct sk_buff * skb,u32 info,struct udp_table * udptable)777 int __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
778 {
779 	struct inet_sock *inet;
780 	const struct iphdr *iph = (const struct iphdr *)skb->data;
781 	struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
782 	const int type = icmp_hdr(skb)->type;
783 	const int code = icmp_hdr(skb)->code;
784 	bool tunnel = false;
785 	struct sock *sk;
786 	int harderr;
787 	int err;
788 	struct net *net = dev_net(skb->dev);
789 
790 	sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
791 			       iph->saddr, uh->source, skb->dev->ifindex,
792 			       inet_sdif(skb), udptable, NULL);
793 
794 	if (!sk || READ_ONCE(udp_sk(sk)->encap_type)) {
795 		/* No socket for error: try tunnels before discarding */
796 		if (static_branch_unlikely(&udp_encap_needed_key)) {
797 			sk = __udp4_lib_err_encap(net, iph, uh, udptable, sk, skb,
798 						  info);
799 			if (!sk)
800 				return 0;
801 		} else
802 			sk = ERR_PTR(-ENOENT);
803 
804 		if (IS_ERR(sk)) {
805 			__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
806 			return PTR_ERR(sk);
807 		}
808 
809 		tunnel = true;
810 	}
811 
812 	err = 0;
813 	harderr = 0;
814 	inet = inet_sk(sk);
815 
816 	switch (type) {
817 	default:
818 	case ICMP_TIME_EXCEEDED:
819 		err = EHOSTUNREACH;
820 		break;
821 	case ICMP_SOURCE_QUENCH:
822 		goto out;
823 	case ICMP_PARAMETERPROB:
824 		err = EPROTO;
825 		harderr = 1;
826 		break;
827 	case ICMP_DEST_UNREACH:
828 		if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
829 			ipv4_sk_update_pmtu(skb, sk, info);
830 			if (inet->pmtudisc != IP_PMTUDISC_DONT) {
831 				err = EMSGSIZE;
832 				harderr = 1;
833 				break;
834 			}
835 			goto out;
836 		}
837 		err = EHOSTUNREACH;
838 		if (code <= NR_ICMP_UNREACH) {
839 			harderr = icmp_err_convert[code].fatal;
840 			err = icmp_err_convert[code].errno;
841 		}
842 		break;
843 	case ICMP_REDIRECT:
844 		ipv4_sk_redirect(skb, sk);
845 		goto out;
846 	}
847 
848 	/*
849 	 *      RFC1122: OK.  Passes ICMP errors back to application, as per
850 	 *	4.1.3.3.
851 	 */
852 	if (tunnel) {
853 		/* ...not for tunnels though: we don't have a sending socket */
854 		if (udp_sk(sk)->encap_err_rcv)
855 			udp_sk(sk)->encap_err_rcv(sk, skb, err, uh->dest, info,
856 						  (u8 *)(uh+1));
857 		goto out;
858 	}
859 	if (!inet_test_bit(RECVERR, sk)) {
860 		if (!harderr || sk->sk_state != TCP_ESTABLISHED)
861 			goto out;
862 	} else
863 		ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
864 
865 	sk->sk_err = err;
866 	sk_error_report(sk);
867 out:
868 	return 0;
869 }
870 
udp_err(struct sk_buff * skb,u32 info)871 int udp_err(struct sk_buff *skb, u32 info)
872 {
873 	return __udp4_lib_err(skb, info, dev_net(skb->dev)->ipv4.udp_table);
874 }
875 
876 /*
877  * Throw away all pending data and cancel the corking. Socket is locked.
878  */
udp_flush_pending_frames(struct sock * sk)879 void udp_flush_pending_frames(struct sock *sk)
880 {
881 	struct udp_sock *up = udp_sk(sk);
882 
883 	if (up->pending) {
884 		up->len = 0;
885 		WRITE_ONCE(up->pending, 0);
886 		ip_flush_pending_frames(sk);
887 	}
888 }
889 EXPORT_SYMBOL(udp_flush_pending_frames);
890 
891 /**
892  * 	udp4_hwcsum  -  handle outgoing HW checksumming
893  * 	@skb: 	sk_buff containing the filled-in UDP header
894  * 	        (checksum field must be zeroed out)
895  *	@src:	source IP address
896  *	@dst:	destination IP address
897  */
udp4_hwcsum(struct sk_buff * skb,__be32 src,__be32 dst)898 void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
899 {
900 	struct udphdr *uh = udp_hdr(skb);
901 	int offset = skb_transport_offset(skb);
902 	int len = skb->len - offset;
903 	int hlen = len;
904 	__wsum csum = 0;
905 
906 	if (!skb_has_frag_list(skb)) {
907 		/*
908 		 * Only one fragment on the socket.
909 		 */
910 		skb->csum_start = skb_transport_header(skb) - skb->head;
911 		skb->csum_offset = offsetof(struct udphdr, check);
912 		uh->check = ~csum_tcpudp_magic(src, dst, len,
913 					       IPPROTO_UDP, 0);
914 	} else {
915 		struct sk_buff *frags;
916 
917 		/*
918 		 * HW-checksum won't work as there are two or more
919 		 * fragments on the socket so that all csums of sk_buffs
920 		 * should be together
921 		 */
922 		skb_walk_frags(skb, frags) {
923 			csum = csum_add(csum, frags->csum);
924 			hlen -= frags->len;
925 		}
926 
927 		csum = skb_checksum(skb, offset, hlen, csum);
928 		skb->ip_summed = CHECKSUM_NONE;
929 
930 		uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
931 		if (uh->check == 0)
932 			uh->check = CSUM_MANGLED_0;
933 	}
934 }
935 EXPORT_SYMBOL_GPL(udp4_hwcsum);
936 
937 /* Function to set UDP checksum for an IPv4 UDP packet. This is intended
938  * for the simple case like when setting the checksum for a UDP tunnel.
939  */
udp_set_csum(bool nocheck,struct sk_buff * skb,__be32 saddr,__be32 daddr,int len)940 void udp_set_csum(bool nocheck, struct sk_buff *skb,
941 		  __be32 saddr, __be32 daddr, int len)
942 {
943 	struct udphdr *uh = udp_hdr(skb);
944 
945 	if (nocheck) {
946 		uh->check = 0;
947 	} else if (skb_is_gso(skb)) {
948 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
949 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) {
950 		uh->check = 0;
951 		uh->check = udp_v4_check(len, saddr, daddr, lco_csum(skb));
952 		if (uh->check == 0)
953 			uh->check = CSUM_MANGLED_0;
954 	} else {
955 		skb->ip_summed = CHECKSUM_PARTIAL;
956 		skb->csum_start = skb_transport_header(skb) - skb->head;
957 		skb->csum_offset = offsetof(struct udphdr, check);
958 		uh->check = ~udp_v4_check(len, saddr, daddr, 0);
959 	}
960 }
961 EXPORT_SYMBOL(udp_set_csum);
962 
udp_send_skb(struct sk_buff * skb,struct flowi4 * fl4,struct inet_cork * cork)963 static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4,
964 			struct inet_cork *cork)
965 {
966 	struct sock *sk = skb->sk;
967 	struct inet_sock *inet = inet_sk(sk);
968 	struct udphdr *uh;
969 	int err;
970 	int is_udplite = IS_UDPLITE(sk);
971 	int offset = skb_transport_offset(skb);
972 	int len = skb->len - offset;
973 	int datalen = len - sizeof(*uh);
974 	__wsum csum = 0;
975 
976 	/*
977 	 * Create a UDP header
978 	 */
979 	uh = udp_hdr(skb);
980 	uh->source = inet->inet_sport;
981 	uh->dest = fl4->fl4_dport;
982 	uh->len = htons(len);
983 	uh->check = 0;
984 
985 	if (cork->gso_size) {
986 		const int hlen = skb_network_header_len(skb) +
987 				 sizeof(struct udphdr);
988 
989 		if (hlen + min(datalen, cork->gso_size) > cork->fragsize) {
990 			kfree_skb(skb);
991 			return -EMSGSIZE;
992 		}
993 		if (datalen > cork->gso_size * UDP_MAX_SEGMENTS) {
994 			kfree_skb(skb);
995 			return -EINVAL;
996 		}
997 		if (sk->sk_no_check_tx) {
998 			kfree_skb(skb);
999 			return -EINVAL;
1000 		}
1001 		if (skb->ip_summed != CHECKSUM_PARTIAL || is_udplite ||
1002 		    dst_xfrm(skb_dst(skb))) {
1003 			kfree_skb(skb);
1004 			return -EIO;
1005 		}
1006 
1007 		if (datalen > cork->gso_size) {
1008 			skb_shinfo(skb)->gso_size = cork->gso_size;
1009 			skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4;
1010 			skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(datalen,
1011 								 cork->gso_size);
1012 		}
1013 		goto csum_partial;
1014 	}
1015 
1016 	if (is_udplite)  				 /*     UDP-Lite      */
1017 		csum = udplite_csum(skb);
1018 
1019 	else if (sk->sk_no_check_tx) {			 /* UDP csum off */
1020 
1021 		skb->ip_summed = CHECKSUM_NONE;
1022 		goto send;
1023 
1024 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
1025 csum_partial:
1026 
1027 		udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
1028 		goto send;
1029 
1030 	} else
1031 		csum = udp_csum(skb);
1032 
1033 	/* add protocol-dependent pseudo-header */
1034 	uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
1035 				      sk->sk_protocol, csum);
1036 	if (uh->check == 0)
1037 		uh->check = CSUM_MANGLED_0;
1038 
1039 send:
1040 	err = ip_send_skb(sock_net(sk), skb);
1041 	if (err) {
1042 		if (err == -ENOBUFS &&
1043 		    !inet_test_bit(RECVERR, sk)) {
1044 			UDP_INC_STATS(sock_net(sk),
1045 				      UDP_MIB_SNDBUFERRORS, is_udplite);
1046 			err = 0;
1047 		}
1048 	} else
1049 		UDP_INC_STATS(sock_net(sk),
1050 			      UDP_MIB_OUTDATAGRAMS, is_udplite);
1051 	return err;
1052 }
1053 
1054 /*
1055  * Push out all pending data as one UDP datagram. Socket is locked.
1056  */
udp_push_pending_frames(struct sock * sk)1057 int udp_push_pending_frames(struct sock *sk)
1058 {
1059 	struct udp_sock  *up = udp_sk(sk);
1060 	struct inet_sock *inet = inet_sk(sk);
1061 	struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
1062 	struct sk_buff *skb;
1063 	int err = 0;
1064 
1065 	skb = ip_finish_skb(sk, fl4);
1066 	if (!skb)
1067 		goto out;
1068 
1069 	err = udp_send_skb(skb, fl4, &inet->cork.base);
1070 
1071 out:
1072 	up->len = 0;
1073 	WRITE_ONCE(up->pending, 0);
1074 	return err;
1075 }
1076 EXPORT_SYMBOL(udp_push_pending_frames);
1077 
__udp_cmsg_send(struct cmsghdr * cmsg,u16 * gso_size)1078 static int __udp_cmsg_send(struct cmsghdr *cmsg, u16 *gso_size)
1079 {
1080 	switch (cmsg->cmsg_type) {
1081 	case UDP_SEGMENT:
1082 		if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u16)))
1083 			return -EINVAL;
1084 		*gso_size = *(__u16 *)CMSG_DATA(cmsg);
1085 		return 0;
1086 	default:
1087 		return -EINVAL;
1088 	}
1089 }
1090 
udp_cmsg_send(struct sock * sk,struct msghdr * msg,u16 * gso_size)1091 int udp_cmsg_send(struct sock *sk, struct msghdr *msg, u16 *gso_size)
1092 {
1093 	struct cmsghdr *cmsg;
1094 	bool need_ip = false;
1095 	int err;
1096 
1097 	for_each_cmsghdr(cmsg, msg) {
1098 		if (!CMSG_OK(msg, cmsg))
1099 			return -EINVAL;
1100 
1101 		if (cmsg->cmsg_level != SOL_UDP) {
1102 			need_ip = true;
1103 			continue;
1104 		}
1105 
1106 		err = __udp_cmsg_send(cmsg, gso_size);
1107 		if (err)
1108 			return err;
1109 	}
1110 
1111 	return need_ip;
1112 }
1113 EXPORT_SYMBOL_GPL(udp_cmsg_send);
1114 
udp_sendmsg(struct sock * sk,struct msghdr * msg,size_t len)1115 int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1116 {
1117 	struct inet_sock *inet = inet_sk(sk);
1118 	struct udp_sock *up = udp_sk(sk);
1119 	DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
1120 	struct flowi4 fl4_stack;
1121 	struct flowi4 *fl4;
1122 	int ulen = len;
1123 	struct ipcm_cookie ipc;
1124 	struct rtable *rt = NULL;
1125 	int free = 0;
1126 	int connected = 0;
1127 	__be32 daddr, faddr, saddr;
1128 	u8 tos, scope;
1129 	__be16 dport;
1130 	int err, is_udplite = IS_UDPLITE(sk);
1131 	int corkreq = udp_test_bit(CORK, sk) || msg->msg_flags & MSG_MORE;
1132 	int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
1133 	struct sk_buff *skb;
1134 	struct ip_options_data opt_copy;
1135 
1136 	if (len > 0xFFFF)
1137 		return -EMSGSIZE;
1138 
1139 	/*
1140 	 *	Check the flags.
1141 	 */
1142 
1143 	if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
1144 		return -EOPNOTSUPP;
1145 
1146 	getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
1147 
1148 	fl4 = &inet->cork.fl.u.ip4;
1149 	if (READ_ONCE(up->pending)) {
1150 		/*
1151 		 * There are pending frames.
1152 		 * The socket lock must be held while it's corked.
1153 		 */
1154 		lock_sock(sk);
1155 		if (likely(up->pending)) {
1156 			if (unlikely(up->pending != AF_INET)) {
1157 				release_sock(sk);
1158 				return -EINVAL;
1159 			}
1160 			goto do_append_data;
1161 		}
1162 		release_sock(sk);
1163 	}
1164 	ulen += sizeof(struct udphdr);
1165 
1166 	/*
1167 	 *	Get and verify the address.
1168 	 */
1169 	if (usin) {
1170 		if (msg->msg_namelen < sizeof(*usin))
1171 			return -EINVAL;
1172 		if (usin->sin_family != AF_INET) {
1173 			if (usin->sin_family != AF_UNSPEC)
1174 				return -EAFNOSUPPORT;
1175 		}
1176 
1177 		daddr = usin->sin_addr.s_addr;
1178 		dport = usin->sin_port;
1179 		if (dport == 0)
1180 			return -EINVAL;
1181 	} else {
1182 		if (sk->sk_state != TCP_ESTABLISHED)
1183 			return -EDESTADDRREQ;
1184 		daddr = inet->inet_daddr;
1185 		dport = inet->inet_dport;
1186 		/* Open fast path for connected socket.
1187 		   Route will not be used, if at least one option is set.
1188 		 */
1189 		connected = 1;
1190 	}
1191 
1192 	ipcm_init_sk(&ipc, inet);
1193 	ipc.gso_size = READ_ONCE(up->gso_size);
1194 
1195 	if (msg->msg_controllen) {
1196 		err = udp_cmsg_send(sk, msg, &ipc.gso_size);
1197 		if (err > 0) {
1198 			err = ip_cmsg_send(sk, msg, &ipc,
1199 					   sk->sk_family == AF_INET6);
1200 			connected = 0;
1201 		}
1202 		if (unlikely(err < 0)) {
1203 			kfree(ipc.opt);
1204 			return err;
1205 		}
1206 		if (ipc.opt)
1207 			free = 1;
1208 	}
1209 	if (!ipc.opt) {
1210 		struct ip_options_rcu *inet_opt;
1211 
1212 		rcu_read_lock();
1213 		inet_opt = rcu_dereference(inet->inet_opt);
1214 		if (inet_opt) {
1215 			memcpy(&opt_copy, inet_opt,
1216 			       sizeof(*inet_opt) + inet_opt->opt.optlen);
1217 			ipc.opt = &opt_copy.opt;
1218 		}
1219 		rcu_read_unlock();
1220 	}
1221 
1222 	if (cgroup_bpf_enabled(CGROUP_UDP4_SENDMSG) && !connected) {
1223 		err = BPF_CGROUP_RUN_PROG_UDP4_SENDMSG_LOCK(sk,
1224 					    (struct sockaddr *)usin,
1225 					    &msg->msg_namelen,
1226 					    &ipc.addr);
1227 		if (err)
1228 			goto out_free;
1229 		if (usin) {
1230 			if (usin->sin_port == 0) {
1231 				/* BPF program set invalid port. Reject it. */
1232 				err = -EINVAL;
1233 				goto out_free;
1234 			}
1235 			daddr = usin->sin_addr.s_addr;
1236 			dport = usin->sin_port;
1237 		}
1238 	}
1239 
1240 	saddr = ipc.addr;
1241 	ipc.addr = faddr = daddr;
1242 
1243 	if (ipc.opt && ipc.opt->opt.srr) {
1244 		if (!daddr) {
1245 			err = -EINVAL;
1246 			goto out_free;
1247 		}
1248 		faddr = ipc.opt->opt.faddr;
1249 		connected = 0;
1250 	}
1251 	tos = get_rttos(&ipc, inet);
1252 	scope = ip_sendmsg_scope(inet, &ipc, msg);
1253 	if (scope == RT_SCOPE_LINK)
1254 		connected = 0;
1255 
1256 	if (ipv4_is_multicast(daddr)) {
1257 		if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif))
1258 			ipc.oif = inet->mc_index;
1259 		if (!saddr)
1260 			saddr = inet->mc_addr;
1261 		connected = 0;
1262 	} else if (!ipc.oif) {
1263 		ipc.oif = inet->uc_index;
1264 	} else if (ipv4_is_lbcast(daddr) && inet->uc_index) {
1265 		/* oif is set, packet is to local broadcast and
1266 		 * uc_index is set. oif is most likely set
1267 		 * by sk_bound_dev_if. If uc_index != oif check if the
1268 		 * oif is an L3 master and uc_index is an L3 slave.
1269 		 * If so, we want to allow the send using the uc_index.
1270 		 */
1271 		if (ipc.oif != inet->uc_index &&
1272 		    ipc.oif == l3mdev_master_ifindex_by_index(sock_net(sk),
1273 							      inet->uc_index)) {
1274 			ipc.oif = inet->uc_index;
1275 		}
1276 	}
1277 
1278 	if (connected)
1279 		rt = (struct rtable *)sk_dst_check(sk, 0);
1280 
1281 	if (!rt) {
1282 		struct net *net = sock_net(sk);
1283 		__u8 flow_flags = inet_sk_flowi_flags(sk);
1284 
1285 		fl4 = &fl4_stack;
1286 
1287 		flowi4_init_output(fl4, ipc.oif, ipc.sockc.mark, tos, scope,
1288 				   sk->sk_protocol, flow_flags, faddr, saddr,
1289 				   dport, inet->inet_sport, sk->sk_uid);
1290 
1291 		security_sk_classify_flow(sk, flowi4_to_flowi_common(fl4));
1292 		rt = ip_route_output_flow(net, fl4, sk);
1293 		if (IS_ERR(rt)) {
1294 			err = PTR_ERR(rt);
1295 			rt = NULL;
1296 			if (err == -ENETUNREACH)
1297 				IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
1298 			goto out;
1299 		}
1300 
1301 		err = -EACCES;
1302 		if ((rt->rt_flags & RTCF_BROADCAST) &&
1303 		    !sock_flag(sk, SOCK_BROADCAST))
1304 			goto out;
1305 		if (connected)
1306 			sk_dst_set(sk, dst_clone(&rt->dst));
1307 	}
1308 
1309 	if (msg->msg_flags&MSG_CONFIRM)
1310 		goto do_confirm;
1311 back_from_confirm:
1312 
1313 	saddr = fl4->saddr;
1314 	if (!ipc.addr)
1315 		daddr = ipc.addr = fl4->daddr;
1316 
1317 	/* Lockless fast path for the non-corking case. */
1318 	if (!corkreq) {
1319 		struct inet_cork cork;
1320 
1321 		skb = ip_make_skb(sk, fl4, getfrag, msg, ulen,
1322 				  sizeof(struct udphdr), &ipc, &rt,
1323 				  &cork, msg->msg_flags);
1324 		err = PTR_ERR(skb);
1325 		if (!IS_ERR_OR_NULL(skb))
1326 			err = udp_send_skb(skb, fl4, &cork);
1327 		goto out;
1328 	}
1329 
1330 	lock_sock(sk);
1331 	if (unlikely(up->pending)) {
1332 		/* The socket is already corked while preparing it. */
1333 		/* ... which is an evident application bug. --ANK */
1334 		release_sock(sk);
1335 
1336 		net_dbg_ratelimited("socket already corked\n");
1337 		err = -EINVAL;
1338 		goto out;
1339 	}
1340 	/*
1341 	 *	Now cork the socket to pend data.
1342 	 */
1343 	fl4 = &inet->cork.fl.u.ip4;
1344 	fl4->daddr = daddr;
1345 	fl4->saddr = saddr;
1346 	fl4->fl4_dport = dport;
1347 	fl4->fl4_sport = inet->inet_sport;
1348 	WRITE_ONCE(up->pending, AF_INET);
1349 
1350 do_append_data:
1351 	up->len += ulen;
1352 	err = ip_append_data(sk, fl4, getfrag, msg, ulen,
1353 			     sizeof(struct udphdr), &ipc, &rt,
1354 			     corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
1355 	if (err)
1356 		udp_flush_pending_frames(sk);
1357 	else if (!corkreq)
1358 		err = udp_push_pending_frames(sk);
1359 	else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
1360 		WRITE_ONCE(up->pending, 0);
1361 	release_sock(sk);
1362 
1363 out:
1364 	ip_rt_put(rt);
1365 out_free:
1366 	if (free)
1367 		kfree(ipc.opt);
1368 	if (!err)
1369 		return len;
1370 	/*
1371 	 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space.  Reporting
1372 	 * ENOBUFS might not be good (it's not tunable per se), but otherwise
1373 	 * we don't have a good statistic (IpOutDiscards but it can be too many
1374 	 * things).  We could add another new stat but at least for now that
1375 	 * seems like overkill.
1376 	 */
1377 	if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
1378 		UDP_INC_STATS(sock_net(sk),
1379 			      UDP_MIB_SNDBUFERRORS, is_udplite);
1380 	}
1381 	return err;
1382 
1383 do_confirm:
1384 	if (msg->msg_flags & MSG_PROBE)
1385 		dst_confirm_neigh(&rt->dst, &fl4->daddr);
1386 	if (!(msg->msg_flags&MSG_PROBE) || len)
1387 		goto back_from_confirm;
1388 	err = 0;
1389 	goto out;
1390 }
1391 EXPORT_SYMBOL(udp_sendmsg);
1392 
udp_splice_eof(struct socket * sock)1393 void udp_splice_eof(struct socket *sock)
1394 {
1395 	struct sock *sk = sock->sk;
1396 	struct udp_sock *up = udp_sk(sk);
1397 
1398 	if (!READ_ONCE(up->pending) || udp_test_bit(CORK, sk))
1399 		return;
1400 
1401 	lock_sock(sk);
1402 	if (up->pending && !udp_test_bit(CORK, sk))
1403 		udp_push_pending_frames(sk);
1404 	release_sock(sk);
1405 }
1406 EXPORT_SYMBOL_GPL(udp_splice_eof);
1407 
1408 #define UDP_SKB_IS_STATELESS 0x80000000
1409 
1410 /* all head states (dst, sk, nf conntrack) except skb extensions are
1411  * cleared by udp_rcv().
1412  *
1413  * We need to preserve secpath, if present, to eventually process
1414  * IP_CMSG_PASSSEC at recvmsg() time.
1415  *
1416  * Other extensions can be cleared.
1417  */
udp_try_make_stateless(struct sk_buff * skb)1418 static bool udp_try_make_stateless(struct sk_buff *skb)
1419 {
1420 	if (!skb_has_extensions(skb))
1421 		return true;
1422 
1423 	if (!secpath_exists(skb)) {
1424 		skb_ext_reset(skb);
1425 		return true;
1426 	}
1427 
1428 	return false;
1429 }
1430 
udp_set_dev_scratch(struct sk_buff * skb)1431 static void udp_set_dev_scratch(struct sk_buff *skb)
1432 {
1433 	struct udp_dev_scratch *scratch = udp_skb_scratch(skb);
1434 
1435 	BUILD_BUG_ON(sizeof(struct udp_dev_scratch) > sizeof(long));
1436 	scratch->_tsize_state = skb->truesize;
1437 #if BITS_PER_LONG == 64
1438 	scratch->len = skb->len;
1439 	scratch->csum_unnecessary = !!skb_csum_unnecessary(skb);
1440 	scratch->is_linear = !skb_is_nonlinear(skb);
1441 #endif
1442 	if (udp_try_make_stateless(skb))
1443 		scratch->_tsize_state |= UDP_SKB_IS_STATELESS;
1444 }
1445 
udp_skb_csum_unnecessary_set(struct sk_buff * skb)1446 static void udp_skb_csum_unnecessary_set(struct sk_buff *skb)
1447 {
1448 	/* We come here after udp_lib_checksum_complete() returned 0.
1449 	 * This means that __skb_checksum_complete() might have
1450 	 * set skb->csum_valid to 1.
1451 	 * On 64bit platforms, we can set csum_unnecessary
1452 	 * to true, but only if the skb is not shared.
1453 	 */
1454 #if BITS_PER_LONG == 64
1455 	if (!skb_shared(skb))
1456 		udp_skb_scratch(skb)->csum_unnecessary = true;
1457 #endif
1458 }
1459 
udp_skb_truesize(struct sk_buff * skb)1460 static int udp_skb_truesize(struct sk_buff *skb)
1461 {
1462 	return udp_skb_scratch(skb)->_tsize_state & ~UDP_SKB_IS_STATELESS;
1463 }
1464 
udp_skb_has_head_state(struct sk_buff * skb)1465 static bool udp_skb_has_head_state(struct sk_buff *skb)
1466 {
1467 	return !(udp_skb_scratch(skb)->_tsize_state & UDP_SKB_IS_STATELESS);
1468 }
1469 
1470 /* fully reclaim rmem/fwd memory allocated for skb */
udp_rmem_release(struct sock * sk,unsigned int size,int partial,bool rx_queue_lock_held)1471 static void udp_rmem_release(struct sock *sk, unsigned int size,
1472 			     int partial, bool rx_queue_lock_held)
1473 {
1474 	struct udp_sock *up = udp_sk(sk);
1475 	struct sk_buff_head *sk_queue;
1476 	unsigned int amt;
1477 
1478 	if (likely(partial)) {
1479 		up->forward_deficit += size;
1480 		size = up->forward_deficit;
1481 		if (size < READ_ONCE(up->forward_threshold) &&
1482 		    !skb_queue_empty(&up->reader_queue))
1483 			return;
1484 	} else {
1485 		size += up->forward_deficit;
1486 	}
1487 	up->forward_deficit = 0;
1488 
1489 	/* acquire the sk_receive_queue for fwd allocated memory scheduling,
1490 	 * if the called don't held it already
1491 	 */
1492 	sk_queue = &sk->sk_receive_queue;
1493 	if (!rx_queue_lock_held)
1494 		spin_lock(&sk_queue->lock);
1495 
1496 	amt = (size + sk->sk_forward_alloc - partial) & ~(PAGE_SIZE - 1);
1497 	sk_forward_alloc_add(sk, size - amt);
1498 
1499 	if (amt)
1500 		__sk_mem_reduce_allocated(sk, amt >> PAGE_SHIFT);
1501 
1502 	atomic_sub(size, &sk->sk_rmem_alloc);
1503 
1504 	/* this can save us from acquiring the rx queue lock on next receive */
1505 	skb_queue_splice_tail_init(sk_queue, &up->reader_queue);
1506 
1507 	if (!rx_queue_lock_held)
1508 		spin_unlock(&sk_queue->lock);
1509 }
1510 
1511 /* Note: called with reader_queue.lock held.
1512  * Instead of using skb->truesize here, find a copy of it in skb->dev_scratch
1513  * This avoids a cache line miss while receive_queue lock is held.
1514  * Look at __udp_enqueue_schedule_skb() to find where this copy is done.
1515  */
udp_skb_destructor(struct sock * sk,struct sk_buff * skb)1516 void udp_skb_destructor(struct sock *sk, struct sk_buff *skb)
1517 {
1518 	prefetch(&skb->data);
1519 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, false);
1520 }
1521 EXPORT_SYMBOL(udp_skb_destructor);
1522 
1523 /* as above, but the caller held the rx queue lock, too */
udp_skb_dtor_locked(struct sock * sk,struct sk_buff * skb)1524 static void udp_skb_dtor_locked(struct sock *sk, struct sk_buff *skb)
1525 {
1526 	prefetch(&skb->data);
1527 	udp_rmem_release(sk, udp_skb_truesize(skb), 1, true);
1528 }
1529 
1530 /* Idea of busylocks is to let producers grab an extra spinlock
1531  * to relieve pressure on the receive_queue spinlock shared by consumer.
1532  * Under flood, this means that only one producer can be in line
1533  * trying to acquire the receive_queue spinlock.
1534  * These busylock can be allocated on a per cpu manner, instead of a
1535  * per socket one (that would consume a cache line per socket)
1536  */
1537 static int udp_busylocks_log __read_mostly;
1538 static spinlock_t *udp_busylocks __read_mostly;
1539 
busylock_acquire(void * ptr)1540 static spinlock_t *busylock_acquire(void *ptr)
1541 {
1542 	spinlock_t *busy;
1543 
1544 	busy = udp_busylocks + hash_ptr(ptr, udp_busylocks_log);
1545 	spin_lock(busy);
1546 	return busy;
1547 }
1548 
busylock_release(spinlock_t * busy)1549 static void busylock_release(spinlock_t *busy)
1550 {
1551 	if (busy)
1552 		spin_unlock(busy);
1553 }
1554 
udp_rmem_schedule(struct sock * sk,int size)1555 static int udp_rmem_schedule(struct sock *sk, int size)
1556 {
1557 	int delta;
1558 
1559 	delta = size - sk->sk_forward_alloc;
1560 	if (delta > 0 && !__sk_mem_schedule(sk, delta, SK_MEM_RECV))
1561 		return -ENOBUFS;
1562 
1563 	return 0;
1564 }
1565 
__udp_enqueue_schedule_skb(struct sock * sk,struct sk_buff * skb)1566 int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb)
1567 {
1568 	struct sk_buff_head *list = &sk->sk_receive_queue;
1569 	int rmem, err = -ENOMEM;
1570 	spinlock_t *busy = NULL;
1571 	int size;
1572 
1573 	/* try to avoid the costly atomic add/sub pair when the receive
1574 	 * queue is full; always allow at least a packet
1575 	 */
1576 	rmem = atomic_read(&sk->sk_rmem_alloc);
1577 	if (rmem > sk->sk_rcvbuf)
1578 		goto drop;
1579 
1580 	/* Under mem pressure, it might be helpful to help udp_recvmsg()
1581 	 * having linear skbs :
1582 	 * - Reduce memory overhead and thus increase receive queue capacity
1583 	 * - Less cache line misses at copyout() time
1584 	 * - Less work at consume_skb() (less alien page frag freeing)
1585 	 */
1586 	if (rmem > (sk->sk_rcvbuf >> 1)) {
1587 		skb_condense(skb);
1588 
1589 		busy = busylock_acquire(sk);
1590 	}
1591 	size = skb->truesize;
1592 	udp_set_dev_scratch(skb);
1593 
1594 	/* we drop only if the receive buf is full and the receive
1595 	 * queue contains some other skb
1596 	 */
1597 	rmem = atomic_add_return(size, &sk->sk_rmem_alloc);
1598 	if (rmem > (size + (unsigned int)sk->sk_rcvbuf))
1599 		goto uncharge_drop;
1600 
1601 	spin_lock(&list->lock);
1602 	err = udp_rmem_schedule(sk, size);
1603 	if (err) {
1604 		spin_unlock(&list->lock);
1605 		goto uncharge_drop;
1606 	}
1607 
1608 	sk_forward_alloc_add(sk, -size);
1609 
1610 	/* no need to setup a destructor, we will explicitly release the
1611 	 * forward allocated memory on dequeue
1612 	 */
1613 	sock_skb_set_dropcount(sk, skb);
1614 
1615 	__skb_queue_tail(list, skb);
1616 	spin_unlock(&list->lock);
1617 
1618 	if (!sock_flag(sk, SOCK_DEAD))
1619 		INDIRECT_CALL_1(sk->sk_data_ready, sock_def_readable, sk);
1620 
1621 	busylock_release(busy);
1622 	return 0;
1623 
1624 uncharge_drop:
1625 	atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
1626 
1627 drop:
1628 	atomic_inc(&sk->sk_drops);
1629 	busylock_release(busy);
1630 	return err;
1631 }
1632 EXPORT_SYMBOL_GPL(__udp_enqueue_schedule_skb);
1633 
udp_destruct_common(struct sock * sk)1634 void udp_destruct_common(struct sock *sk)
1635 {
1636 	/* reclaim completely the forward allocated memory */
1637 	struct udp_sock *up = udp_sk(sk);
1638 	unsigned int total = 0;
1639 	struct sk_buff *skb;
1640 
1641 	skb_queue_splice_tail_init(&sk->sk_receive_queue, &up->reader_queue);
1642 	while ((skb = __skb_dequeue(&up->reader_queue)) != NULL) {
1643 		total += skb->truesize;
1644 		kfree_skb(skb);
1645 	}
1646 	udp_rmem_release(sk, total, 0, true);
1647 }
1648 EXPORT_SYMBOL_GPL(udp_destruct_common);
1649 
udp_destruct_sock(struct sock * sk)1650 static void udp_destruct_sock(struct sock *sk)
1651 {
1652 	udp_destruct_common(sk);
1653 	inet_sock_destruct(sk);
1654 }
1655 
udp_init_sock(struct sock * sk)1656 int udp_init_sock(struct sock *sk)
1657 {
1658 	udp_lib_init_sock(sk);
1659 	sk->sk_destruct = udp_destruct_sock;
1660 	set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
1661 	return 0;
1662 }
1663 
skb_consume_udp(struct sock * sk,struct sk_buff * skb,int len)1664 void skb_consume_udp(struct sock *sk, struct sk_buff *skb, int len)
1665 {
1666 	if (unlikely(READ_ONCE(sk->sk_peek_off) >= 0)) {
1667 		bool slow = lock_sock_fast(sk);
1668 
1669 		sk_peek_offset_bwd(sk, len);
1670 		unlock_sock_fast(sk, slow);
1671 	}
1672 
1673 	if (!skb_unref(skb))
1674 		return;
1675 
1676 	/* In the more common cases we cleared the head states previously,
1677 	 * see __udp_queue_rcv_skb().
1678 	 */
1679 	if (unlikely(udp_skb_has_head_state(skb)))
1680 		skb_release_head_state(skb);
1681 	__consume_stateless_skb(skb);
1682 }
1683 EXPORT_SYMBOL_GPL(skb_consume_udp);
1684 
__first_packet_length(struct sock * sk,struct sk_buff_head * rcvq,unsigned int * total)1685 static struct sk_buff *__first_packet_length(struct sock *sk,
1686 					     struct sk_buff_head *rcvq,
1687 					     unsigned int *total)
1688 {
1689 	struct sk_buff *skb;
1690 
1691 	while ((skb = skb_peek(rcvq)) != NULL) {
1692 		if (udp_lib_checksum_complete(skb)) {
1693 			__UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS,
1694 					IS_UDPLITE(sk));
1695 			__UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS,
1696 					IS_UDPLITE(sk));
1697 			atomic_inc(&sk->sk_drops);
1698 			__skb_unlink(skb, rcvq);
1699 			*total += skb->truesize;
1700 			kfree_skb(skb);
1701 		} else {
1702 			udp_skb_csum_unnecessary_set(skb);
1703 			break;
1704 		}
1705 	}
1706 	return skb;
1707 }
1708 
1709 /**
1710  *	first_packet_length	- return length of first packet in receive queue
1711  *	@sk: socket
1712  *
1713  *	Drops all bad checksum frames, until a valid one is found.
1714  *	Returns the length of found skb, or -1 if none is found.
1715  */
first_packet_length(struct sock * sk)1716 static int first_packet_length(struct sock *sk)
1717 {
1718 	struct sk_buff_head *rcvq = &udp_sk(sk)->reader_queue;
1719 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
1720 	unsigned int total = 0;
1721 	struct sk_buff *skb;
1722 	int res;
1723 
1724 	spin_lock_bh(&rcvq->lock);
1725 	skb = __first_packet_length(sk, rcvq, &total);
1726 	if (!skb && !skb_queue_empty_lockless(sk_queue)) {
1727 		spin_lock(&sk_queue->lock);
1728 		skb_queue_splice_tail_init(sk_queue, rcvq);
1729 		spin_unlock(&sk_queue->lock);
1730 
1731 		skb = __first_packet_length(sk, rcvq, &total);
1732 	}
1733 	res = skb ? skb->len : -1;
1734 	if (total)
1735 		udp_rmem_release(sk, total, 1, false);
1736 	spin_unlock_bh(&rcvq->lock);
1737 	return res;
1738 }
1739 
1740 /*
1741  *	IOCTL requests applicable to the UDP protocol
1742  */
1743 
udp_ioctl(struct sock * sk,int cmd,int * karg)1744 int udp_ioctl(struct sock *sk, int cmd, int *karg)
1745 {
1746 	switch (cmd) {
1747 	case SIOCOUTQ:
1748 	{
1749 		*karg = sk_wmem_alloc_get(sk);
1750 		return 0;
1751 	}
1752 
1753 	case SIOCINQ:
1754 	{
1755 		*karg = max_t(int, 0, first_packet_length(sk));
1756 		return 0;
1757 	}
1758 
1759 	default:
1760 		return -ENOIOCTLCMD;
1761 	}
1762 
1763 	return 0;
1764 }
1765 EXPORT_SYMBOL(udp_ioctl);
1766 
__skb_recv_udp(struct sock * sk,unsigned int flags,int * off,int * err)1767 struct sk_buff *__skb_recv_udp(struct sock *sk, unsigned int flags,
1768 			       int *off, int *err)
1769 {
1770 	struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
1771 	struct sk_buff_head *queue;
1772 	struct sk_buff *last;
1773 	long timeo;
1774 	int error;
1775 
1776 	queue = &udp_sk(sk)->reader_queue;
1777 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1778 	do {
1779 		struct sk_buff *skb;
1780 
1781 		error = sock_error(sk);
1782 		if (error)
1783 			break;
1784 
1785 		error = -EAGAIN;
1786 		do {
1787 			spin_lock_bh(&queue->lock);
1788 			skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1789 							err, &last);
1790 			if (skb) {
1791 				if (!(flags & MSG_PEEK))
1792 					udp_skb_destructor(sk, skb);
1793 				spin_unlock_bh(&queue->lock);
1794 				return skb;
1795 			}
1796 
1797 			if (skb_queue_empty_lockless(sk_queue)) {
1798 				spin_unlock_bh(&queue->lock);
1799 				goto busy_check;
1800 			}
1801 
1802 			/* refill the reader queue and walk it again
1803 			 * keep both queues locked to avoid re-acquiring
1804 			 * the sk_receive_queue lock if fwd memory scheduling
1805 			 * is needed.
1806 			 */
1807 			spin_lock(&sk_queue->lock);
1808 			skb_queue_splice_tail_init(sk_queue, queue);
1809 
1810 			skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1811 							err, &last);
1812 			if (skb && !(flags & MSG_PEEK))
1813 				udp_skb_dtor_locked(sk, skb);
1814 			spin_unlock(&sk_queue->lock);
1815 			spin_unlock_bh(&queue->lock);
1816 			if (skb)
1817 				return skb;
1818 
1819 busy_check:
1820 			if (!sk_can_busy_loop(sk))
1821 				break;
1822 
1823 			sk_busy_loop(sk, flags & MSG_DONTWAIT);
1824 		} while (!skb_queue_empty_lockless(sk_queue));
1825 
1826 		/* sk_queue is empty, reader_queue may contain peeked packets */
1827 	} while (timeo &&
1828 		 !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,
1829 					      &error, &timeo,
1830 					      (struct sk_buff *)sk_queue));
1831 
1832 	*err = error;
1833 	return NULL;
1834 }
1835 EXPORT_SYMBOL(__skb_recv_udp);
1836 
udp_read_skb(struct sock * sk,skb_read_actor_t recv_actor)1837 int udp_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
1838 {
1839 	struct sk_buff *skb;
1840 	int err;
1841 
1842 try_again:
1843 	skb = skb_recv_udp(sk, MSG_DONTWAIT, &err);
1844 	if (!skb)
1845 		return err;
1846 
1847 	if (udp_lib_checksum_complete(skb)) {
1848 		int is_udplite = IS_UDPLITE(sk);
1849 		struct net *net = sock_net(sk);
1850 
1851 		__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, is_udplite);
1852 		__UDP_INC_STATS(net, UDP_MIB_INERRORS, is_udplite);
1853 		atomic_inc(&sk->sk_drops);
1854 		kfree_skb(skb);
1855 		goto try_again;
1856 	}
1857 
1858 	WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk));
1859 	return recv_actor(sk, skb);
1860 }
1861 EXPORT_SYMBOL(udp_read_skb);
1862 
1863 /*
1864  * 	This should be easy, if there is something there we
1865  * 	return it, otherwise we block.
1866  */
1867 
udp_recvmsg(struct sock * sk,struct msghdr * msg,size_t len,int flags,int * addr_len)1868 int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags,
1869 		int *addr_len)
1870 {
1871 	struct inet_sock *inet = inet_sk(sk);
1872 	DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
1873 	struct sk_buff *skb;
1874 	unsigned int ulen, copied;
1875 	int off, err, peeking = flags & MSG_PEEK;
1876 	int is_udplite = IS_UDPLITE(sk);
1877 	bool checksum_valid = false;
1878 
1879 	if (flags & MSG_ERRQUEUE)
1880 		return ip_recv_error(sk, msg, len, addr_len);
1881 
1882 try_again:
1883 	off = sk_peek_offset(sk, flags);
1884 	skb = __skb_recv_udp(sk, flags, &off, &err);
1885 	if (!skb)
1886 		return err;
1887 
1888 	ulen = udp_skb_len(skb);
1889 	copied = len;
1890 	if (copied > ulen - off)
1891 		copied = ulen - off;
1892 	else if (copied < ulen)
1893 		msg->msg_flags |= MSG_TRUNC;
1894 
1895 	/*
1896 	 * If checksum is needed at all, try to do it while copying the
1897 	 * data.  If the data is truncated, or if we only want a partial
1898 	 * coverage checksum (UDP-Lite), do it before the copy.
1899 	 */
1900 
1901 	if (copied < ulen || peeking ||
1902 	    (is_udplite && UDP_SKB_CB(skb)->partial_cov)) {
1903 		checksum_valid = udp_skb_csum_unnecessary(skb) ||
1904 				!__udp_lib_checksum_complete(skb);
1905 		if (!checksum_valid)
1906 			goto csum_copy_err;
1907 	}
1908 
1909 	if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
1910 		if (udp_skb_is_linear(skb))
1911 			err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
1912 		else
1913 			err = skb_copy_datagram_msg(skb, off, msg, copied);
1914 	} else {
1915 		err = skb_copy_and_csum_datagram_msg(skb, off, msg);
1916 
1917 		if (err == -EINVAL)
1918 			goto csum_copy_err;
1919 	}
1920 
1921 	if (unlikely(err)) {
1922 		if (!peeking) {
1923 			atomic_inc(&sk->sk_drops);
1924 			UDP_INC_STATS(sock_net(sk),
1925 				      UDP_MIB_INERRORS, is_udplite);
1926 		}
1927 		kfree_skb(skb);
1928 		return err;
1929 	}
1930 
1931 	if (!peeking)
1932 		UDP_INC_STATS(sock_net(sk),
1933 			      UDP_MIB_INDATAGRAMS, is_udplite);
1934 
1935 	sock_recv_cmsgs(msg, sk, skb);
1936 
1937 	/* Copy the address. */
1938 	if (sin) {
1939 		sin->sin_family = AF_INET;
1940 		sin->sin_port = udp_hdr(skb)->source;
1941 		sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
1942 		memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
1943 		*addr_len = sizeof(*sin);
1944 
1945 		BPF_CGROUP_RUN_PROG_UDP4_RECVMSG_LOCK(sk,
1946 						      (struct sockaddr *)sin,
1947 						      addr_len);
1948 	}
1949 
1950 	if (udp_test_bit(GRO_ENABLED, sk))
1951 		udp_cmsg_recv(msg, sk, skb);
1952 
1953 	if (inet_cmsg_flags(inet))
1954 		ip_cmsg_recv_offset(msg, sk, skb, sizeof(struct udphdr), off);
1955 
1956 	err = copied;
1957 	if (flags & MSG_TRUNC)
1958 		err = ulen;
1959 
1960 	skb_consume_udp(sk, skb, peeking ? -err : err);
1961 	return err;
1962 
1963 csum_copy_err:
1964 	if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags,
1965 				 udp_skb_destructor)) {
1966 		UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
1967 		UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
1968 	}
1969 	kfree_skb(skb);
1970 
1971 	/* starting over for a new packet, but check if we need to yield */
1972 	cond_resched();
1973 	msg->msg_flags &= ~MSG_TRUNC;
1974 	goto try_again;
1975 }
1976 
udp_pre_connect(struct sock * sk,struct sockaddr * uaddr,int addr_len)1977 int udp_pre_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
1978 {
1979 	/* This check is replicated from __ip4_datagram_connect() and
1980 	 * intended to prevent BPF program called below from accessing bytes
1981 	 * that are out of the bound specified by user in addr_len.
1982 	 */
1983 	if (addr_len < sizeof(struct sockaddr_in))
1984 		return -EINVAL;
1985 
1986 	return BPF_CGROUP_RUN_PROG_INET4_CONNECT_LOCK(sk, uaddr, &addr_len);
1987 }
1988 EXPORT_SYMBOL(udp_pre_connect);
1989 
__udp_disconnect(struct sock * sk,int flags)1990 int __udp_disconnect(struct sock *sk, int flags)
1991 {
1992 	struct inet_sock *inet = inet_sk(sk);
1993 	/*
1994 	 *	1003.1g - break association.
1995 	 */
1996 
1997 	sk->sk_state = TCP_CLOSE;
1998 	inet->inet_daddr = 0;
1999 	inet->inet_dport = 0;
2000 	sock_rps_reset_rxhash(sk);
2001 	sk->sk_bound_dev_if = 0;
2002 	if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) {
2003 		inet_reset_saddr(sk);
2004 		if (sk->sk_prot->rehash &&
2005 		    (sk->sk_userlocks & SOCK_BINDPORT_LOCK))
2006 			sk->sk_prot->rehash(sk);
2007 	}
2008 
2009 	if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
2010 		sk->sk_prot->unhash(sk);
2011 		inet->inet_sport = 0;
2012 	}
2013 	sk_dst_reset(sk);
2014 	return 0;
2015 }
2016 EXPORT_SYMBOL(__udp_disconnect);
2017 
udp_disconnect(struct sock * sk,int flags)2018 int udp_disconnect(struct sock *sk, int flags)
2019 {
2020 	lock_sock(sk);
2021 	__udp_disconnect(sk, flags);
2022 	release_sock(sk);
2023 	return 0;
2024 }
2025 EXPORT_SYMBOL(udp_disconnect);
2026 
udp_lib_unhash(struct sock * sk)2027 void udp_lib_unhash(struct sock *sk)
2028 {
2029 	if (sk_hashed(sk)) {
2030 		struct udp_table *udptable = udp_get_table_prot(sk);
2031 		struct udp_hslot *hslot, *hslot2;
2032 
2033 		hslot  = udp_hashslot(udptable, sock_net(sk),
2034 				      udp_sk(sk)->udp_port_hash);
2035 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
2036 
2037 		spin_lock_bh(&hslot->lock);
2038 		if (rcu_access_pointer(sk->sk_reuseport_cb))
2039 			reuseport_detach_sock(sk);
2040 		if (sk_del_node_init_rcu(sk)) {
2041 			hslot->count--;
2042 			inet_sk(sk)->inet_num = 0;
2043 			sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
2044 
2045 			spin_lock(&hslot2->lock);
2046 			hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
2047 			hslot2->count--;
2048 			spin_unlock(&hslot2->lock);
2049 		}
2050 		spin_unlock_bh(&hslot->lock);
2051 	}
2052 }
2053 EXPORT_SYMBOL(udp_lib_unhash);
2054 
2055 /*
2056  * inet_rcv_saddr was changed, we must rehash secondary hash
2057  */
udp_lib_rehash(struct sock * sk,u16 newhash)2058 void udp_lib_rehash(struct sock *sk, u16 newhash)
2059 {
2060 	if (sk_hashed(sk)) {
2061 		struct udp_table *udptable = udp_get_table_prot(sk);
2062 		struct udp_hslot *hslot, *hslot2, *nhslot2;
2063 
2064 		hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
2065 		nhslot2 = udp_hashslot2(udptable, newhash);
2066 		udp_sk(sk)->udp_portaddr_hash = newhash;
2067 
2068 		if (hslot2 != nhslot2 ||
2069 		    rcu_access_pointer(sk->sk_reuseport_cb)) {
2070 			hslot = udp_hashslot(udptable, sock_net(sk),
2071 					     udp_sk(sk)->udp_port_hash);
2072 			/* we must lock primary chain too */
2073 			spin_lock_bh(&hslot->lock);
2074 			if (rcu_access_pointer(sk->sk_reuseport_cb))
2075 				reuseport_detach_sock(sk);
2076 
2077 			if (hslot2 != nhslot2) {
2078 				spin_lock(&hslot2->lock);
2079 				hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
2080 				hslot2->count--;
2081 				spin_unlock(&hslot2->lock);
2082 
2083 				spin_lock(&nhslot2->lock);
2084 				hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
2085 							 &nhslot2->head);
2086 				nhslot2->count++;
2087 				spin_unlock(&nhslot2->lock);
2088 			}
2089 
2090 			spin_unlock_bh(&hslot->lock);
2091 		}
2092 	}
2093 }
2094 EXPORT_SYMBOL(udp_lib_rehash);
2095 
udp_v4_rehash(struct sock * sk)2096 void udp_v4_rehash(struct sock *sk)
2097 {
2098 	u16 new_hash = ipv4_portaddr_hash(sock_net(sk),
2099 					  inet_sk(sk)->inet_rcv_saddr,
2100 					  inet_sk(sk)->inet_num);
2101 	udp_lib_rehash(sk, new_hash);
2102 }
2103 
__udp_queue_rcv_skb(struct sock * sk,struct sk_buff * skb)2104 static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2105 {
2106 	int rc;
2107 
2108 	if (inet_sk(sk)->inet_daddr) {
2109 		sock_rps_save_rxhash(sk, skb);
2110 		sk_mark_napi_id(sk, skb);
2111 		sk_incoming_cpu_update(sk);
2112 	} else {
2113 		sk_mark_napi_id_once(sk, skb);
2114 	}
2115 
2116 	rc = __udp_enqueue_schedule_skb(sk, skb);
2117 	if (rc < 0) {
2118 		int is_udplite = IS_UDPLITE(sk);
2119 		int drop_reason;
2120 
2121 		/* Note that an ENOMEM error is charged twice */
2122 		if (rc == -ENOMEM) {
2123 			UDP_INC_STATS(sock_net(sk), UDP_MIB_RCVBUFERRORS,
2124 					is_udplite);
2125 			drop_reason = SKB_DROP_REASON_SOCKET_RCVBUFF;
2126 		} else {
2127 			UDP_INC_STATS(sock_net(sk), UDP_MIB_MEMERRORS,
2128 				      is_udplite);
2129 			drop_reason = SKB_DROP_REASON_PROTO_MEM;
2130 		}
2131 		UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
2132 		kfree_skb_reason(skb, drop_reason);
2133 		trace_udp_fail_queue_rcv_skb(rc, sk);
2134 		return -1;
2135 	}
2136 
2137 	return 0;
2138 }
2139 
2140 /* returns:
2141  *  -1: error
2142  *   0: success
2143  *  >0: "udp encap" protocol resubmission
2144  *
2145  * Note that in the success and error cases, the skb is assumed to
2146  * have either been requeued or freed.
2147  */
udp_queue_rcv_one_skb(struct sock * sk,struct sk_buff * skb)2148 static int udp_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
2149 {
2150 	int drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2151 	struct udp_sock *up = udp_sk(sk);
2152 	int is_udplite = IS_UDPLITE(sk);
2153 
2154 	/*
2155 	 *	Charge it to the socket, dropping if the queue is full.
2156 	 */
2157 	if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
2158 		drop_reason = SKB_DROP_REASON_XFRM_POLICY;
2159 		goto drop;
2160 	}
2161 	nf_reset_ct(skb);
2162 
2163 	if (static_branch_unlikely(&udp_encap_needed_key) &&
2164 	    READ_ONCE(up->encap_type)) {
2165 		int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
2166 
2167 		/*
2168 		 * This is an encapsulation socket so pass the skb to
2169 		 * the socket's udp_encap_rcv() hook. Otherwise, just
2170 		 * fall through and pass this up the UDP socket.
2171 		 * up->encap_rcv() returns the following value:
2172 		 * =0 if skb was successfully passed to the encap
2173 		 *    handler or was discarded by it.
2174 		 * >0 if skb should be passed on to UDP.
2175 		 * <0 if skb should be resubmitted as proto -N
2176 		 */
2177 
2178 		/* if we're overly short, let UDP handle it */
2179 		encap_rcv = READ_ONCE(up->encap_rcv);
2180 		if (encap_rcv) {
2181 			int ret;
2182 
2183 			/* Verify checksum before giving to encap */
2184 			if (udp_lib_checksum_complete(skb))
2185 				goto csum_error;
2186 
2187 			ret = encap_rcv(sk, skb);
2188 			if (ret <= 0) {
2189 				__UDP_INC_STATS(sock_net(sk),
2190 						UDP_MIB_INDATAGRAMS,
2191 						is_udplite);
2192 				return -ret;
2193 			}
2194 		}
2195 
2196 		/* FALLTHROUGH -- it's a UDP Packet */
2197 	}
2198 
2199 	/*
2200 	 * 	UDP-Lite specific tests, ignored on UDP sockets
2201 	 */
2202 	if (udp_test_bit(UDPLITE_RECV_CC, sk) && UDP_SKB_CB(skb)->partial_cov) {
2203 		u16 pcrlen = READ_ONCE(up->pcrlen);
2204 
2205 		/*
2206 		 * MIB statistics other than incrementing the error count are
2207 		 * disabled for the following two types of errors: these depend
2208 		 * on the application settings, not on the functioning of the
2209 		 * protocol stack as such.
2210 		 *
2211 		 * RFC 3828 here recommends (sec 3.3): "There should also be a
2212 		 * way ... to ... at least let the receiving application block
2213 		 * delivery of packets with coverage values less than a value
2214 		 * provided by the application."
2215 		 */
2216 		if (pcrlen == 0) {          /* full coverage was set  */
2217 			net_dbg_ratelimited("UDPLite: partial coverage %d while full coverage %d requested\n",
2218 					    UDP_SKB_CB(skb)->cscov, skb->len);
2219 			goto drop;
2220 		}
2221 		/* The next case involves violating the min. coverage requested
2222 		 * by the receiver. This is subtle: if receiver wants x and x is
2223 		 * greater than the buffersize/MTU then receiver will complain
2224 		 * that it wants x while sender emits packets of smaller size y.
2225 		 * Therefore the above ...()->partial_cov statement is essential.
2226 		 */
2227 		if (UDP_SKB_CB(skb)->cscov < pcrlen) {
2228 			net_dbg_ratelimited("UDPLite: coverage %d too small, need min %d\n",
2229 					    UDP_SKB_CB(skb)->cscov, pcrlen);
2230 			goto drop;
2231 		}
2232 	}
2233 
2234 	prefetch(&sk->sk_rmem_alloc);
2235 	if (rcu_access_pointer(sk->sk_filter) &&
2236 	    udp_lib_checksum_complete(skb))
2237 			goto csum_error;
2238 
2239 	if (sk_filter_trim_cap(sk, skb, sizeof(struct udphdr))) {
2240 		drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
2241 		goto drop;
2242 	}
2243 
2244 	udp_csum_pull_header(skb);
2245 
2246 	ipv4_pktinfo_prepare(sk, skb, true);
2247 	return __udp_queue_rcv_skb(sk, skb);
2248 
2249 csum_error:
2250 	drop_reason = SKB_DROP_REASON_UDP_CSUM;
2251 	__UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
2252 drop:
2253 	__UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
2254 	atomic_inc(&sk->sk_drops);
2255 	kfree_skb_reason(skb, drop_reason);
2256 	return -1;
2257 }
2258 
udp_queue_rcv_skb(struct sock * sk,struct sk_buff * skb)2259 static int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2260 {
2261 	struct sk_buff *next, *segs;
2262 	int ret;
2263 
2264 	if (likely(!udp_unexpected_gso(sk, skb)))
2265 		return udp_queue_rcv_one_skb(sk, skb);
2266 
2267 	BUILD_BUG_ON(sizeof(struct udp_skb_cb) > SKB_GSO_CB_OFFSET);
2268 	__skb_push(skb, -skb_mac_offset(skb));
2269 	segs = udp_rcv_segment(sk, skb, true);
2270 	skb_list_walk_safe(segs, skb, next) {
2271 		__skb_pull(skb, skb_transport_offset(skb));
2272 
2273 		udp_post_segment_fix_csum(skb);
2274 		ret = udp_queue_rcv_one_skb(sk, skb);
2275 		if (ret > 0)
2276 			ip_protocol_deliver_rcu(dev_net(skb->dev), skb, ret);
2277 	}
2278 	return 0;
2279 }
2280 
2281 /* For TCP sockets, sk_rx_dst is protected by socket lock
2282  * For UDP, we use xchg() to guard against concurrent changes.
2283  */
udp_sk_rx_dst_set(struct sock * sk,struct dst_entry * dst)2284 bool udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
2285 {
2286 	struct dst_entry *old;
2287 
2288 	if (dst_hold_safe(dst)) {
2289 		old = unrcu_pointer(xchg(&sk->sk_rx_dst, RCU_INITIALIZER(dst)));
2290 		dst_release(old);
2291 		return old != dst;
2292 	}
2293 	return false;
2294 }
2295 EXPORT_SYMBOL(udp_sk_rx_dst_set);
2296 
2297 /*
2298  *	Multicasts and broadcasts go to each listener.
2299  *
2300  *	Note: called only from the BH handler context.
2301  */
__udp4_lib_mcast_deliver(struct net * net,struct sk_buff * skb,struct udphdr * uh,__be32 saddr,__be32 daddr,struct udp_table * udptable,int proto)2302 static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
2303 				    struct udphdr  *uh,
2304 				    __be32 saddr, __be32 daddr,
2305 				    struct udp_table *udptable,
2306 				    int proto)
2307 {
2308 	struct sock *sk, *first = NULL;
2309 	unsigned short hnum = ntohs(uh->dest);
2310 	struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum);
2311 	unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10);
2312 	unsigned int offset = offsetof(typeof(*sk), sk_node);
2313 	int dif = skb->dev->ifindex;
2314 	int sdif = inet_sdif(skb);
2315 	struct hlist_node *node;
2316 	struct sk_buff *nskb;
2317 
2318 	if (use_hash2) {
2319 		hash2_any = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum) &
2320 			    udptable->mask;
2321 		hash2 = ipv4_portaddr_hash(net, daddr, hnum) & udptable->mask;
2322 start_lookup:
2323 		hslot = &udptable->hash2[hash2];
2324 		offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
2325 	}
2326 
2327 	sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
2328 		if (!__udp_is_mcast_sock(net, sk, uh->dest, daddr,
2329 					 uh->source, saddr, dif, sdif, hnum))
2330 			continue;
2331 
2332 		if (!first) {
2333 			first = sk;
2334 			continue;
2335 		}
2336 		nskb = skb_clone(skb, GFP_ATOMIC);
2337 
2338 		if (unlikely(!nskb)) {
2339 			atomic_inc(&sk->sk_drops);
2340 			__UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS,
2341 					IS_UDPLITE(sk));
2342 			__UDP_INC_STATS(net, UDP_MIB_INERRORS,
2343 					IS_UDPLITE(sk));
2344 			continue;
2345 		}
2346 		if (udp_queue_rcv_skb(sk, nskb) > 0)
2347 			consume_skb(nskb);
2348 	}
2349 
2350 	/* Also lookup *:port if we are using hash2 and haven't done so yet. */
2351 	if (use_hash2 && hash2 != hash2_any) {
2352 		hash2 = hash2_any;
2353 		goto start_lookup;
2354 	}
2355 
2356 	if (first) {
2357 		if (udp_queue_rcv_skb(first, skb) > 0)
2358 			consume_skb(skb);
2359 	} else {
2360 		kfree_skb(skb);
2361 		__UDP_INC_STATS(net, UDP_MIB_IGNOREDMULTI,
2362 				proto == IPPROTO_UDPLITE);
2363 	}
2364 	return 0;
2365 }
2366 
2367 /* Initialize UDP checksum. If exited with zero value (success),
2368  * CHECKSUM_UNNECESSARY means, that no more checks are required.
2369  * Otherwise, csum completion requires checksumming packet body,
2370  * including udp header and folding it to skb->csum.
2371  */
udp4_csum_init(struct sk_buff * skb,struct udphdr * uh,int proto)2372 static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
2373 				 int proto)
2374 {
2375 	int err;
2376 
2377 	UDP_SKB_CB(skb)->partial_cov = 0;
2378 	UDP_SKB_CB(skb)->cscov = skb->len;
2379 
2380 	if (proto == IPPROTO_UDPLITE) {
2381 		err = udplite_checksum_init(skb, uh);
2382 		if (err)
2383 			return err;
2384 
2385 		if (UDP_SKB_CB(skb)->partial_cov) {
2386 			skb->csum = inet_compute_pseudo(skb, proto);
2387 			return 0;
2388 		}
2389 	}
2390 
2391 	/* Note, we are only interested in != 0 or == 0, thus the
2392 	 * force to int.
2393 	 */
2394 	err = (__force int)skb_checksum_init_zero_check(skb, proto, uh->check,
2395 							inet_compute_pseudo);
2396 	if (err)
2397 		return err;
2398 
2399 	if (skb->ip_summed == CHECKSUM_COMPLETE && !skb->csum_valid) {
2400 		/* If SW calculated the value, we know it's bad */
2401 		if (skb->csum_complete_sw)
2402 			return 1;
2403 
2404 		/* HW says the value is bad. Let's validate that.
2405 		 * skb->csum is no longer the full packet checksum,
2406 		 * so don't treat it as such.
2407 		 */
2408 		skb_checksum_complete_unset(skb);
2409 	}
2410 
2411 	return 0;
2412 }
2413 
2414 /* wrapper for udp_queue_rcv_skb tacking care of csum conversion and
2415  * return code conversion for ip layer consumption
2416  */
udp_unicast_rcv_skb(struct sock * sk,struct sk_buff * skb,struct udphdr * uh)2417 static int udp_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb,
2418 			       struct udphdr *uh)
2419 {
2420 	int ret;
2421 
2422 	if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk))
2423 		skb_checksum_try_convert(skb, IPPROTO_UDP, inet_compute_pseudo);
2424 
2425 	ret = udp_queue_rcv_skb(sk, skb);
2426 
2427 	/* a return value > 0 means to resubmit the input, but
2428 	 * it wants the return to be -protocol, or 0
2429 	 */
2430 	if (ret > 0)
2431 		return -ret;
2432 	return 0;
2433 }
2434 
2435 /*
2436  *	All we need to do is get the socket, and then do a checksum.
2437  */
2438 
__udp4_lib_rcv(struct sk_buff * skb,struct udp_table * udptable,int proto)2439 int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
2440 		   int proto)
2441 {
2442 	struct sock *sk;
2443 	struct udphdr *uh;
2444 	unsigned short ulen;
2445 	struct rtable *rt = skb_rtable(skb);
2446 	__be32 saddr, daddr;
2447 	struct net *net = dev_net(skb->dev);
2448 	bool refcounted;
2449 	int drop_reason;
2450 
2451 	drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2452 
2453 	/*
2454 	 *  Validate the packet.
2455 	 */
2456 	if (!pskb_may_pull(skb, sizeof(struct udphdr)))
2457 		goto drop;		/* No space for header. */
2458 
2459 	uh   = udp_hdr(skb);
2460 	ulen = ntohs(uh->len);
2461 	saddr = ip_hdr(skb)->saddr;
2462 	daddr = ip_hdr(skb)->daddr;
2463 
2464 	if (ulen > skb->len)
2465 		goto short_packet;
2466 
2467 	if (proto == IPPROTO_UDP) {
2468 		/* UDP validates ulen. */
2469 		if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
2470 			goto short_packet;
2471 		uh = udp_hdr(skb);
2472 	}
2473 
2474 	if (udp4_csum_init(skb, uh, proto))
2475 		goto csum_error;
2476 
2477 	sk = inet_steal_sock(net, skb, sizeof(struct udphdr), saddr, uh->source, daddr, uh->dest,
2478 			     &refcounted, udp_ehashfn);
2479 	if (IS_ERR(sk))
2480 		goto no_sk;
2481 
2482 	if (sk) {
2483 		struct dst_entry *dst = skb_dst(skb);
2484 		int ret;
2485 
2486 		if (unlikely(rcu_dereference(sk->sk_rx_dst) != dst))
2487 			udp_sk_rx_dst_set(sk, dst);
2488 
2489 		ret = udp_unicast_rcv_skb(sk, skb, uh);
2490 		if (refcounted)
2491 			sock_put(sk);
2492 		return ret;
2493 	}
2494 
2495 	if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
2496 		return __udp4_lib_mcast_deliver(net, skb, uh,
2497 						saddr, daddr, udptable, proto);
2498 
2499 	sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
2500 	if (sk)
2501 		return udp_unicast_rcv_skb(sk, skb, uh);
2502 no_sk:
2503 	if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
2504 		goto drop;
2505 	nf_reset_ct(skb);
2506 
2507 	/* No socket. Drop packet silently, if checksum is wrong */
2508 	if (udp_lib_checksum_complete(skb))
2509 		goto csum_error;
2510 
2511 	drop_reason = SKB_DROP_REASON_NO_SOCKET;
2512 	__UDP_INC_STATS(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
2513 	icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
2514 
2515 	/*
2516 	 * Hmm.  We got an UDP packet to a port to which we
2517 	 * don't wanna listen.  Ignore it.
2518 	 */
2519 	kfree_skb_reason(skb, drop_reason);
2520 	return 0;
2521 
2522 short_packet:
2523 	drop_reason = SKB_DROP_REASON_PKT_TOO_SMALL;
2524 	net_dbg_ratelimited("UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
2525 			    proto == IPPROTO_UDPLITE ? "Lite" : "",
2526 			    &saddr, ntohs(uh->source),
2527 			    ulen, skb->len,
2528 			    &daddr, ntohs(uh->dest));
2529 	goto drop;
2530 
2531 csum_error:
2532 	/*
2533 	 * RFC1122: OK.  Discards the bad packet silently (as far as
2534 	 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
2535 	 */
2536 	drop_reason = SKB_DROP_REASON_UDP_CSUM;
2537 	net_dbg_ratelimited("UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
2538 			    proto == IPPROTO_UDPLITE ? "Lite" : "",
2539 			    &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
2540 			    ulen);
2541 	__UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
2542 drop:
2543 	__UDP_INC_STATS(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
2544 	kfree_skb_reason(skb, drop_reason);
2545 	return 0;
2546 }
2547 
2548 /* We can only early demux multicast if there is a single matching socket.
2549  * If more than one socket found returns NULL
2550  */
__udp4_lib_mcast_demux_lookup(struct net * net,__be16 loc_port,__be32 loc_addr,__be16 rmt_port,__be32 rmt_addr,int dif,int sdif)2551 static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net,
2552 						  __be16 loc_port, __be32 loc_addr,
2553 						  __be16 rmt_port, __be32 rmt_addr,
2554 						  int dif, int sdif)
2555 {
2556 	struct udp_table *udptable = net->ipv4.udp_table;
2557 	unsigned short hnum = ntohs(loc_port);
2558 	struct sock *sk, *result;
2559 	struct udp_hslot *hslot;
2560 	unsigned int slot;
2561 
2562 	slot = udp_hashfn(net, hnum, udptable->mask);
2563 	hslot = &udptable->hash[slot];
2564 
2565 	/* Do not bother scanning a too big list */
2566 	if (hslot->count > 10)
2567 		return NULL;
2568 
2569 	result = NULL;
2570 	sk_for_each_rcu(sk, &hslot->head) {
2571 		if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr,
2572 					rmt_port, rmt_addr, dif, sdif, hnum)) {
2573 			if (result)
2574 				return NULL;
2575 			result = sk;
2576 		}
2577 	}
2578 
2579 	return result;
2580 }
2581 
2582 /* For unicast we should only early demux connected sockets or we can
2583  * break forwarding setups.  The chains here can be long so only check
2584  * if the first socket is an exact match and if not move on.
2585  */
__udp4_lib_demux_lookup(struct net * net,__be16 loc_port,__be32 loc_addr,__be16 rmt_port,__be32 rmt_addr,int dif,int sdif)2586 static struct sock *__udp4_lib_demux_lookup(struct net *net,
2587 					    __be16 loc_port, __be32 loc_addr,
2588 					    __be16 rmt_port, __be32 rmt_addr,
2589 					    int dif, int sdif)
2590 {
2591 	struct udp_table *udptable = net->ipv4.udp_table;
2592 	INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr);
2593 	unsigned short hnum = ntohs(loc_port);
2594 	unsigned int hash2, slot2;
2595 	struct udp_hslot *hslot2;
2596 	__portpair ports;
2597 	struct sock *sk;
2598 
2599 	hash2 = ipv4_portaddr_hash(net, loc_addr, hnum);
2600 	slot2 = hash2 & udptable->mask;
2601 	hslot2 = &udptable->hash2[slot2];
2602 	ports = INET_COMBINED_PORTS(rmt_port, hnum);
2603 
2604 	udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
2605 		if (inet_match(net, sk, acookie, ports, dif, sdif))
2606 			return sk;
2607 		/* Only check first socket in chain */
2608 		break;
2609 	}
2610 	return NULL;
2611 }
2612 
udp_v4_early_demux(struct sk_buff * skb)2613 int udp_v4_early_demux(struct sk_buff *skb)
2614 {
2615 	struct net *net = dev_net(skb->dev);
2616 	struct in_device *in_dev = NULL;
2617 	const struct iphdr *iph;
2618 	const struct udphdr *uh;
2619 	struct sock *sk = NULL;
2620 	struct dst_entry *dst;
2621 	int dif = skb->dev->ifindex;
2622 	int sdif = inet_sdif(skb);
2623 	int ours;
2624 
2625 	/* validate the packet */
2626 	if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)))
2627 		return 0;
2628 
2629 	iph = ip_hdr(skb);
2630 	uh = udp_hdr(skb);
2631 
2632 	if (skb->pkt_type == PACKET_MULTICAST) {
2633 		in_dev = __in_dev_get_rcu(skb->dev);
2634 
2635 		if (!in_dev)
2636 			return 0;
2637 
2638 		ours = ip_check_mc_rcu(in_dev, iph->daddr, iph->saddr,
2639 				       iph->protocol);
2640 		if (!ours)
2641 			return 0;
2642 
2643 		sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr,
2644 						   uh->source, iph->saddr,
2645 						   dif, sdif);
2646 	} else if (skb->pkt_type == PACKET_HOST) {
2647 		sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr,
2648 					     uh->source, iph->saddr, dif, sdif);
2649 	}
2650 
2651 	if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
2652 		return 0;
2653 
2654 	skb->sk = sk;
2655 	skb->destructor = sock_efree;
2656 	dst = rcu_dereference(sk->sk_rx_dst);
2657 
2658 	if (dst)
2659 		dst = dst_check(dst, 0);
2660 	if (dst) {
2661 		u32 itag = 0;
2662 
2663 		/* set noref for now.
2664 		 * any place which wants to hold dst has to call
2665 		 * dst_hold_safe()
2666 		 */
2667 		skb_dst_set_noref(skb, dst);
2668 
2669 		/* for unconnected multicast sockets we need to validate
2670 		 * the source on each packet
2671 		 */
2672 		if (!inet_sk(sk)->inet_daddr && in_dev)
2673 			return ip_mc_validate_source(skb, iph->daddr,
2674 						     iph->saddr,
2675 						     iph->tos & IPTOS_RT_MASK,
2676 						     skb->dev, in_dev, &itag);
2677 	}
2678 	return 0;
2679 }
2680 
udp_rcv(struct sk_buff * skb)2681 int udp_rcv(struct sk_buff *skb)
2682 {
2683 	return __udp4_lib_rcv(skb, dev_net(skb->dev)->ipv4.udp_table, IPPROTO_UDP);
2684 }
2685 
udp_destroy_sock(struct sock * sk)2686 void udp_destroy_sock(struct sock *sk)
2687 {
2688 	struct udp_sock *up = udp_sk(sk);
2689 	bool slow = lock_sock_fast(sk);
2690 
2691 	/* protects from races with udp_abort() */
2692 	sock_set_flag(sk, SOCK_DEAD);
2693 	udp_flush_pending_frames(sk);
2694 	unlock_sock_fast(sk, slow);
2695 	if (static_branch_unlikely(&udp_encap_needed_key)) {
2696 		if (up->encap_type) {
2697 			void (*encap_destroy)(struct sock *sk);
2698 			encap_destroy = READ_ONCE(up->encap_destroy);
2699 			if (encap_destroy)
2700 				encap_destroy(sk);
2701 		}
2702 		if (udp_test_bit(ENCAP_ENABLED, sk))
2703 			static_branch_dec(&udp_encap_needed_key);
2704 	}
2705 }
2706 
2707 /*
2708  *	Socket option code for UDP
2709  */
udp_lib_setsockopt(struct sock * sk,int level,int optname,sockptr_t optval,unsigned int optlen,int (* push_pending_frames)(struct sock *))2710 int udp_lib_setsockopt(struct sock *sk, int level, int optname,
2711 		       sockptr_t optval, unsigned int optlen,
2712 		       int (*push_pending_frames)(struct sock *))
2713 {
2714 	struct udp_sock *up = udp_sk(sk);
2715 	int val, valbool;
2716 	int err = 0;
2717 	int is_udplite = IS_UDPLITE(sk);
2718 
2719 	if (level == SOL_SOCKET) {
2720 		err = sk_setsockopt(sk, level, optname, optval, optlen);
2721 
2722 		if (optname == SO_RCVBUF || optname == SO_RCVBUFFORCE) {
2723 			sockopt_lock_sock(sk);
2724 			/* paired with READ_ONCE in udp_rmem_release() */
2725 			WRITE_ONCE(up->forward_threshold, sk->sk_rcvbuf >> 2);
2726 			sockopt_release_sock(sk);
2727 		}
2728 		return err;
2729 	}
2730 
2731 	if (optlen < sizeof(int))
2732 		return -EINVAL;
2733 
2734 	if (copy_from_sockptr(&val, optval, sizeof(val)))
2735 		return -EFAULT;
2736 
2737 	valbool = val ? 1 : 0;
2738 
2739 	switch (optname) {
2740 	case UDP_CORK:
2741 		if (val != 0) {
2742 			udp_set_bit(CORK, sk);
2743 		} else {
2744 			udp_clear_bit(CORK, sk);
2745 			lock_sock(sk);
2746 			push_pending_frames(sk);
2747 			release_sock(sk);
2748 		}
2749 		break;
2750 
2751 	case UDP_ENCAP:
2752 		switch (val) {
2753 		case 0:
2754 #ifdef CONFIG_XFRM
2755 		case UDP_ENCAP_ESPINUDP:
2756 		case UDP_ENCAP_ESPINUDP_NON_IKE:
2757 #if IS_ENABLED(CONFIG_IPV6)
2758 			if (sk->sk_family == AF_INET6)
2759 				WRITE_ONCE(up->encap_rcv,
2760 					   ipv6_stub->xfrm6_udp_encap_rcv);
2761 			else
2762 #endif
2763 				WRITE_ONCE(up->encap_rcv,
2764 					   xfrm4_udp_encap_rcv);
2765 #endif
2766 			fallthrough;
2767 		case UDP_ENCAP_L2TPINUDP:
2768 			WRITE_ONCE(up->encap_type, val);
2769 			udp_tunnel_encap_enable(sk);
2770 			break;
2771 		default:
2772 			err = -ENOPROTOOPT;
2773 			break;
2774 		}
2775 		break;
2776 
2777 	case UDP_NO_CHECK6_TX:
2778 		udp_set_no_check6_tx(sk, valbool);
2779 		break;
2780 
2781 	case UDP_NO_CHECK6_RX:
2782 		udp_set_no_check6_rx(sk, valbool);
2783 		break;
2784 
2785 	case UDP_SEGMENT:
2786 		if (val < 0 || val > USHRT_MAX)
2787 			return -EINVAL;
2788 		WRITE_ONCE(up->gso_size, val);
2789 		break;
2790 
2791 	case UDP_GRO:
2792 
2793 		/* when enabling GRO, accept the related GSO packet type */
2794 		if (valbool)
2795 			udp_tunnel_encap_enable(sk);
2796 		udp_assign_bit(GRO_ENABLED, sk, valbool);
2797 		udp_assign_bit(ACCEPT_L4, sk, valbool);
2798 		break;
2799 
2800 	/*
2801 	 * 	UDP-Lite's partial checksum coverage (RFC 3828).
2802 	 */
2803 	/* The sender sets actual checksum coverage length via this option.
2804 	 * The case coverage > packet length is handled by send module. */
2805 	case UDPLITE_SEND_CSCOV:
2806 		if (!is_udplite)         /* Disable the option on UDP sockets */
2807 			return -ENOPROTOOPT;
2808 		if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
2809 			val = 8;
2810 		else if (val > USHRT_MAX)
2811 			val = USHRT_MAX;
2812 		WRITE_ONCE(up->pcslen, val);
2813 		udp_set_bit(UDPLITE_SEND_CC, sk);
2814 		break;
2815 
2816 	/* The receiver specifies a minimum checksum coverage value. To make
2817 	 * sense, this should be set to at least 8 (as done below). If zero is
2818 	 * used, this again means full checksum coverage.                     */
2819 	case UDPLITE_RECV_CSCOV:
2820 		if (!is_udplite)         /* Disable the option on UDP sockets */
2821 			return -ENOPROTOOPT;
2822 		if (val != 0 && val < 8) /* Avoid silly minimal values.       */
2823 			val = 8;
2824 		else if (val > USHRT_MAX)
2825 			val = USHRT_MAX;
2826 		WRITE_ONCE(up->pcrlen, val);
2827 		udp_set_bit(UDPLITE_RECV_CC, sk);
2828 		break;
2829 
2830 	default:
2831 		err = -ENOPROTOOPT;
2832 		break;
2833 	}
2834 
2835 	return err;
2836 }
2837 EXPORT_SYMBOL(udp_lib_setsockopt);
2838 
udp_setsockopt(struct sock * sk,int level,int optname,sockptr_t optval,unsigned int optlen)2839 int udp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
2840 		   unsigned int optlen)
2841 {
2842 	if (level == SOL_UDP  ||  level == SOL_UDPLITE || level == SOL_SOCKET)
2843 		return udp_lib_setsockopt(sk, level, optname,
2844 					  optval, optlen,
2845 					  udp_push_pending_frames);
2846 	return ip_setsockopt(sk, level, optname, optval, optlen);
2847 }
2848 
udp_lib_getsockopt(struct sock * sk,int level,int optname,char __user * optval,int __user * optlen)2849 int udp_lib_getsockopt(struct sock *sk, int level, int optname,
2850 		       char __user *optval, int __user *optlen)
2851 {
2852 	struct udp_sock *up = udp_sk(sk);
2853 	int val, len;
2854 
2855 	if (get_user(len, optlen))
2856 		return -EFAULT;
2857 
2858 	if (len < 0)
2859 		return -EINVAL;
2860 
2861 	len = min_t(unsigned int, len, sizeof(int));
2862 
2863 	switch (optname) {
2864 	case UDP_CORK:
2865 		val = udp_test_bit(CORK, sk);
2866 		break;
2867 
2868 	case UDP_ENCAP:
2869 		val = READ_ONCE(up->encap_type);
2870 		break;
2871 
2872 	case UDP_NO_CHECK6_TX:
2873 		val = udp_get_no_check6_tx(sk);
2874 		break;
2875 
2876 	case UDP_NO_CHECK6_RX:
2877 		val = udp_get_no_check6_rx(sk);
2878 		break;
2879 
2880 	case UDP_SEGMENT:
2881 		val = READ_ONCE(up->gso_size);
2882 		break;
2883 
2884 	case UDP_GRO:
2885 		val = udp_test_bit(GRO_ENABLED, sk);
2886 		break;
2887 
2888 	/* The following two cannot be changed on UDP sockets, the return is
2889 	 * always 0 (which corresponds to the full checksum coverage of UDP). */
2890 	case UDPLITE_SEND_CSCOV:
2891 		val = READ_ONCE(up->pcslen);
2892 		break;
2893 
2894 	case UDPLITE_RECV_CSCOV:
2895 		val = READ_ONCE(up->pcrlen);
2896 		break;
2897 
2898 	default:
2899 		return -ENOPROTOOPT;
2900 	}
2901 
2902 	if (put_user(len, optlen))
2903 		return -EFAULT;
2904 	if (copy_to_user(optval, &val, len))
2905 		return -EFAULT;
2906 	return 0;
2907 }
2908 EXPORT_SYMBOL(udp_lib_getsockopt);
2909 
udp_getsockopt(struct sock * sk,int level,int optname,char __user * optval,int __user * optlen)2910 int udp_getsockopt(struct sock *sk, int level, int optname,
2911 		   char __user *optval, int __user *optlen)
2912 {
2913 	if (level == SOL_UDP  ||  level == SOL_UDPLITE)
2914 		return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2915 	return ip_getsockopt(sk, level, optname, optval, optlen);
2916 }
2917 
2918 /**
2919  * 	udp_poll - wait for a UDP event.
2920  *	@file: - file struct
2921  *	@sock: - socket
2922  *	@wait: - poll table
2923  *
2924  *	This is same as datagram poll, except for the special case of
2925  *	blocking sockets. If application is using a blocking fd
2926  *	and a packet with checksum error is in the queue;
2927  *	then it could get return from select indicating data available
2928  *	but then block when reading it. Add special case code
2929  *	to work around these arguably broken applications.
2930  */
udp_poll(struct file * file,struct socket * sock,poll_table * wait)2931 __poll_t udp_poll(struct file *file, struct socket *sock, poll_table *wait)
2932 {
2933 	__poll_t mask = datagram_poll(file, sock, wait);
2934 	struct sock *sk = sock->sk;
2935 
2936 	if (!skb_queue_empty_lockless(&udp_sk(sk)->reader_queue))
2937 		mask |= EPOLLIN | EPOLLRDNORM;
2938 
2939 	/* Check for false positives due to checksum errors */
2940 	if ((mask & EPOLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
2941 	    !(sk->sk_shutdown & RCV_SHUTDOWN) && first_packet_length(sk) == -1)
2942 		mask &= ~(EPOLLIN | EPOLLRDNORM);
2943 
2944 	/* psock ingress_msg queue should not contain any bad checksum frames */
2945 	if (sk_is_readable(sk))
2946 		mask |= EPOLLIN | EPOLLRDNORM;
2947 	return mask;
2948 
2949 }
2950 EXPORT_SYMBOL(udp_poll);
2951 
udp_abort(struct sock * sk,int err)2952 int udp_abort(struct sock *sk, int err)
2953 {
2954 	if (!has_current_bpf_ctx())
2955 		lock_sock(sk);
2956 
2957 	/* udp{v6}_destroy_sock() sets it under the sk lock, avoid racing
2958 	 * with close()
2959 	 */
2960 	if (sock_flag(sk, SOCK_DEAD))
2961 		goto out;
2962 
2963 	sk->sk_err = err;
2964 	sk_error_report(sk);
2965 	__udp_disconnect(sk, 0);
2966 
2967 out:
2968 	if (!has_current_bpf_ctx())
2969 		release_sock(sk);
2970 
2971 	return 0;
2972 }
2973 EXPORT_SYMBOL_GPL(udp_abort);
2974 
2975 struct proto udp_prot = {
2976 	.name			= "UDP",
2977 	.owner			= THIS_MODULE,
2978 	.close			= udp_lib_close,
2979 	.pre_connect		= udp_pre_connect,
2980 	.connect		= ip4_datagram_connect,
2981 	.disconnect		= udp_disconnect,
2982 	.ioctl			= udp_ioctl,
2983 	.init			= udp_init_sock,
2984 	.destroy		= udp_destroy_sock,
2985 	.setsockopt		= udp_setsockopt,
2986 	.getsockopt		= udp_getsockopt,
2987 	.sendmsg		= udp_sendmsg,
2988 	.recvmsg		= udp_recvmsg,
2989 	.splice_eof		= udp_splice_eof,
2990 	.release_cb		= ip4_datagram_release_cb,
2991 	.hash			= udp_lib_hash,
2992 	.unhash			= udp_lib_unhash,
2993 	.rehash			= udp_v4_rehash,
2994 	.get_port		= udp_v4_get_port,
2995 	.put_port		= udp_lib_unhash,
2996 #ifdef CONFIG_BPF_SYSCALL
2997 	.psock_update_sk_prot	= udp_bpf_update_proto,
2998 #endif
2999 	.memory_allocated	= &udp_memory_allocated,
3000 	.per_cpu_fw_alloc	= &udp_memory_per_cpu_fw_alloc,
3001 
3002 	.sysctl_mem		= sysctl_udp_mem,
3003 	.sysctl_wmem_offset	= offsetof(struct net, ipv4.sysctl_udp_wmem_min),
3004 	.sysctl_rmem_offset	= offsetof(struct net, ipv4.sysctl_udp_rmem_min),
3005 	.obj_size		= sizeof(struct udp_sock),
3006 	.h.udp_table		= NULL,
3007 	.diag_destroy		= udp_abort,
3008 };
3009 EXPORT_SYMBOL(udp_prot);
3010 
3011 /* ------------------------------------------------------------------------ */
3012 #ifdef CONFIG_PROC_FS
3013 
3014 static unsigned short seq_file_family(const struct seq_file *seq);
seq_sk_match(struct seq_file * seq,const struct sock * sk)3015 static bool seq_sk_match(struct seq_file *seq, const struct sock *sk)
3016 {
3017 	unsigned short family = seq_file_family(seq);
3018 
3019 	/* AF_UNSPEC is used as a match all */
3020 	return ((family == AF_UNSPEC || family == sk->sk_family) &&
3021 		net_eq(sock_net(sk), seq_file_net(seq)));
3022 }
3023 
3024 #ifdef CONFIG_BPF_SYSCALL
3025 static const struct seq_operations bpf_iter_udp_seq_ops;
3026 #endif
udp_get_table_seq(struct seq_file * seq,struct net * net)3027 static struct udp_table *udp_get_table_seq(struct seq_file *seq,
3028 					   struct net *net)
3029 {
3030 	const struct udp_seq_afinfo *afinfo;
3031 
3032 #ifdef CONFIG_BPF_SYSCALL
3033 	if (seq->op == &bpf_iter_udp_seq_ops)
3034 		return net->ipv4.udp_table;
3035 #endif
3036 
3037 	afinfo = pde_data(file_inode(seq->file));
3038 	return afinfo->udp_table ? : net->ipv4.udp_table;
3039 }
3040 
udp_get_first(struct seq_file * seq,int start)3041 static struct sock *udp_get_first(struct seq_file *seq, int start)
3042 {
3043 	struct udp_iter_state *state = seq->private;
3044 	struct net *net = seq_file_net(seq);
3045 	struct udp_table *udptable;
3046 	struct sock *sk;
3047 
3048 	udptable = udp_get_table_seq(seq, net);
3049 
3050 	for (state->bucket = start; state->bucket <= udptable->mask;
3051 	     ++state->bucket) {
3052 		struct udp_hslot *hslot = &udptable->hash[state->bucket];
3053 
3054 		if (hlist_empty(&hslot->head))
3055 			continue;
3056 
3057 		spin_lock_bh(&hslot->lock);
3058 		sk_for_each(sk, &hslot->head) {
3059 			if (seq_sk_match(seq, sk))
3060 				goto found;
3061 		}
3062 		spin_unlock_bh(&hslot->lock);
3063 	}
3064 	sk = NULL;
3065 found:
3066 	return sk;
3067 }
3068 
udp_get_next(struct seq_file * seq,struct sock * sk)3069 static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
3070 {
3071 	struct udp_iter_state *state = seq->private;
3072 	struct net *net = seq_file_net(seq);
3073 	struct udp_table *udptable;
3074 
3075 	do {
3076 		sk = sk_next(sk);
3077 	} while (sk && !seq_sk_match(seq, sk));
3078 
3079 	if (!sk) {
3080 		udptable = udp_get_table_seq(seq, net);
3081 
3082 		if (state->bucket <= udptable->mask)
3083 			spin_unlock_bh(&udptable->hash[state->bucket].lock);
3084 
3085 		return udp_get_first(seq, state->bucket + 1);
3086 	}
3087 	return sk;
3088 }
3089 
udp_get_idx(struct seq_file * seq,loff_t pos)3090 static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
3091 {
3092 	struct sock *sk = udp_get_first(seq, 0);
3093 
3094 	if (sk)
3095 		while (pos && (sk = udp_get_next(seq, sk)) != NULL)
3096 			--pos;
3097 	return pos ? NULL : sk;
3098 }
3099 
udp_seq_start(struct seq_file * seq,loff_t * pos)3100 void *udp_seq_start(struct seq_file *seq, loff_t *pos)
3101 {
3102 	struct udp_iter_state *state = seq->private;
3103 	state->bucket = MAX_UDP_PORTS;
3104 
3105 	return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
3106 }
3107 EXPORT_SYMBOL(udp_seq_start);
3108 
udp_seq_next(struct seq_file * seq,void * v,loff_t * pos)3109 void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3110 {
3111 	struct sock *sk;
3112 
3113 	if (v == SEQ_START_TOKEN)
3114 		sk = udp_get_idx(seq, 0);
3115 	else
3116 		sk = udp_get_next(seq, v);
3117 
3118 	++*pos;
3119 	return sk;
3120 }
3121 EXPORT_SYMBOL(udp_seq_next);
3122 
udp_seq_stop(struct seq_file * seq,void * v)3123 void udp_seq_stop(struct seq_file *seq, void *v)
3124 {
3125 	struct udp_iter_state *state = seq->private;
3126 	struct udp_table *udptable;
3127 
3128 	udptable = udp_get_table_seq(seq, seq_file_net(seq));
3129 
3130 	if (state->bucket <= udptable->mask)
3131 		spin_unlock_bh(&udptable->hash[state->bucket].lock);
3132 }
3133 EXPORT_SYMBOL(udp_seq_stop);
3134 
3135 /* ------------------------------------------------------------------------ */
udp4_format_sock(struct sock * sp,struct seq_file * f,int bucket)3136 static void udp4_format_sock(struct sock *sp, struct seq_file *f,
3137 		int bucket)
3138 {
3139 	struct inet_sock *inet = inet_sk(sp);
3140 	__be32 dest = inet->inet_daddr;
3141 	__be32 src  = inet->inet_rcv_saddr;
3142 	__u16 destp	  = ntohs(inet->inet_dport);
3143 	__u16 srcp	  = ntohs(inet->inet_sport);
3144 
3145 	seq_printf(f, "%5d: %08X:%04X %08X:%04X"
3146 		" %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %u",
3147 		bucket, src, srcp, dest, destp, sp->sk_state,
3148 		sk_wmem_alloc_get(sp),
3149 		udp_rqueue_get(sp),
3150 		0, 0L, 0,
3151 		from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
3152 		0, sock_i_ino(sp),
3153 		refcount_read(&sp->sk_refcnt), sp,
3154 		atomic_read(&sp->sk_drops));
3155 }
3156 
udp4_seq_show(struct seq_file * seq,void * v)3157 int udp4_seq_show(struct seq_file *seq, void *v)
3158 {
3159 	seq_setwidth(seq, 127);
3160 	if (v == SEQ_START_TOKEN)
3161 		seq_puts(seq, "   sl  local_address rem_address   st tx_queue "
3162 			   "rx_queue tr tm->when retrnsmt   uid  timeout "
3163 			   "inode ref pointer drops");
3164 	else {
3165 		struct udp_iter_state *state = seq->private;
3166 
3167 		udp4_format_sock(v, seq, state->bucket);
3168 	}
3169 	seq_pad(seq, '\n');
3170 	return 0;
3171 }
3172 
3173 #ifdef CONFIG_BPF_SYSCALL
3174 struct bpf_iter__udp {
3175 	__bpf_md_ptr(struct bpf_iter_meta *, meta);
3176 	__bpf_md_ptr(struct udp_sock *, udp_sk);
3177 	uid_t uid __aligned(8);
3178 	int bucket __aligned(8);
3179 };
3180 
3181 struct bpf_udp_iter_state {
3182 	struct udp_iter_state state;
3183 	unsigned int cur_sk;
3184 	unsigned int end_sk;
3185 	unsigned int max_sk;
3186 	int offset;
3187 	struct sock **batch;
3188 	bool st_bucket_done;
3189 };
3190 
3191 static int bpf_iter_udp_realloc_batch(struct bpf_udp_iter_state *iter,
3192 				      unsigned int new_batch_sz);
bpf_iter_udp_batch(struct seq_file * seq)3193 static struct sock *bpf_iter_udp_batch(struct seq_file *seq)
3194 {
3195 	struct bpf_udp_iter_state *iter = seq->private;
3196 	struct udp_iter_state *state = &iter->state;
3197 	struct net *net = seq_file_net(seq);
3198 	int resume_bucket, resume_offset;
3199 	struct udp_table *udptable;
3200 	unsigned int batch_sks = 0;
3201 	bool resized = false;
3202 	struct sock *sk;
3203 
3204 	resume_bucket = state->bucket;
3205 	resume_offset = iter->offset;
3206 
3207 	/* The current batch is done, so advance the bucket. */
3208 	if (iter->st_bucket_done)
3209 		state->bucket++;
3210 
3211 	udptable = udp_get_table_seq(seq, net);
3212 
3213 again:
3214 	/* New batch for the next bucket.
3215 	 * Iterate over the hash table to find a bucket with sockets matching
3216 	 * the iterator attributes, and return the first matching socket from
3217 	 * the bucket. The remaining matched sockets from the bucket are batched
3218 	 * before releasing the bucket lock. This allows BPF programs that are
3219 	 * called in seq_show to acquire the bucket lock if needed.
3220 	 */
3221 	iter->cur_sk = 0;
3222 	iter->end_sk = 0;
3223 	iter->st_bucket_done = false;
3224 	batch_sks = 0;
3225 
3226 	for (; state->bucket <= udptable->mask; state->bucket++) {
3227 		struct udp_hslot *hslot2 = &udptable->hash2[state->bucket];
3228 
3229 		if (hlist_empty(&hslot2->head))
3230 			continue;
3231 
3232 		iter->offset = 0;
3233 		spin_lock_bh(&hslot2->lock);
3234 		udp_portaddr_for_each_entry(sk, &hslot2->head) {
3235 			if (seq_sk_match(seq, sk)) {
3236 				/* Resume from the last iterated socket at the
3237 				 * offset in the bucket before iterator was stopped.
3238 				 */
3239 				if (state->bucket == resume_bucket &&
3240 				    iter->offset < resume_offset) {
3241 					++iter->offset;
3242 					continue;
3243 				}
3244 				if (iter->end_sk < iter->max_sk) {
3245 					sock_hold(sk);
3246 					iter->batch[iter->end_sk++] = sk;
3247 				}
3248 				batch_sks++;
3249 			}
3250 		}
3251 		spin_unlock_bh(&hslot2->lock);
3252 
3253 		if (iter->end_sk)
3254 			break;
3255 	}
3256 
3257 	/* All done: no batch made. */
3258 	if (!iter->end_sk)
3259 		return NULL;
3260 
3261 	if (iter->end_sk == batch_sks) {
3262 		/* Batching is done for the current bucket; return the first
3263 		 * socket to be iterated from the batch.
3264 		 */
3265 		iter->st_bucket_done = true;
3266 		goto done;
3267 	}
3268 	if (!resized && !bpf_iter_udp_realloc_batch(iter, batch_sks * 3 / 2)) {
3269 		resized = true;
3270 		/* After allocating a larger batch, retry one more time to grab
3271 		 * the whole bucket.
3272 		 */
3273 		goto again;
3274 	}
3275 done:
3276 	return iter->batch[0];
3277 }
3278 
bpf_iter_udp_seq_next(struct seq_file * seq,void * v,loff_t * pos)3279 static void *bpf_iter_udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3280 {
3281 	struct bpf_udp_iter_state *iter = seq->private;
3282 	struct sock *sk;
3283 
3284 	/* Whenever seq_next() is called, the iter->cur_sk is
3285 	 * done with seq_show(), so unref the iter->cur_sk.
3286 	 */
3287 	if (iter->cur_sk < iter->end_sk) {
3288 		sock_put(iter->batch[iter->cur_sk++]);
3289 		++iter->offset;
3290 	}
3291 
3292 	/* After updating iter->cur_sk, check if there are more sockets
3293 	 * available in the current bucket batch.
3294 	 */
3295 	if (iter->cur_sk < iter->end_sk)
3296 		sk = iter->batch[iter->cur_sk];
3297 	else
3298 		/* Prepare a new batch. */
3299 		sk = bpf_iter_udp_batch(seq);
3300 
3301 	++*pos;
3302 	return sk;
3303 }
3304 
bpf_iter_udp_seq_start(struct seq_file * seq,loff_t * pos)3305 static void *bpf_iter_udp_seq_start(struct seq_file *seq, loff_t *pos)
3306 {
3307 	/* bpf iter does not support lseek, so it always
3308 	 * continue from where it was stop()-ped.
3309 	 */
3310 	if (*pos)
3311 		return bpf_iter_udp_batch(seq);
3312 
3313 	return SEQ_START_TOKEN;
3314 }
3315 
udp_prog_seq_show(struct bpf_prog * prog,struct bpf_iter_meta * meta,struct udp_sock * udp_sk,uid_t uid,int bucket)3316 static int udp_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
3317 			     struct udp_sock *udp_sk, uid_t uid, int bucket)
3318 {
3319 	struct bpf_iter__udp ctx;
3320 
3321 	meta->seq_num--;  /* skip SEQ_START_TOKEN */
3322 	ctx.meta = meta;
3323 	ctx.udp_sk = udp_sk;
3324 	ctx.uid = uid;
3325 	ctx.bucket = bucket;
3326 	return bpf_iter_run_prog(prog, &ctx);
3327 }
3328 
bpf_iter_udp_seq_show(struct seq_file * seq,void * v)3329 static int bpf_iter_udp_seq_show(struct seq_file *seq, void *v)
3330 {
3331 	struct udp_iter_state *state = seq->private;
3332 	struct bpf_iter_meta meta;
3333 	struct bpf_prog *prog;
3334 	struct sock *sk = v;
3335 	uid_t uid;
3336 	int ret;
3337 
3338 	if (v == SEQ_START_TOKEN)
3339 		return 0;
3340 
3341 	lock_sock(sk);
3342 
3343 	if (unlikely(sk_unhashed(sk))) {
3344 		ret = SEQ_SKIP;
3345 		goto unlock;
3346 	}
3347 
3348 	uid = from_kuid_munged(seq_user_ns(seq), sock_i_uid(sk));
3349 	meta.seq = seq;
3350 	prog = bpf_iter_get_info(&meta, false);
3351 	ret = udp_prog_seq_show(prog, &meta, v, uid, state->bucket);
3352 
3353 unlock:
3354 	release_sock(sk);
3355 	return ret;
3356 }
3357 
bpf_iter_udp_put_batch(struct bpf_udp_iter_state * iter)3358 static void bpf_iter_udp_put_batch(struct bpf_udp_iter_state *iter)
3359 {
3360 	while (iter->cur_sk < iter->end_sk)
3361 		sock_put(iter->batch[iter->cur_sk++]);
3362 }
3363 
bpf_iter_udp_seq_stop(struct seq_file * seq,void * v)3364 static void bpf_iter_udp_seq_stop(struct seq_file *seq, void *v)
3365 {
3366 	struct bpf_udp_iter_state *iter = seq->private;
3367 	struct bpf_iter_meta meta;
3368 	struct bpf_prog *prog;
3369 
3370 	if (!v) {
3371 		meta.seq = seq;
3372 		prog = bpf_iter_get_info(&meta, true);
3373 		if (prog)
3374 			(void)udp_prog_seq_show(prog, &meta, v, 0, 0);
3375 	}
3376 
3377 	if (iter->cur_sk < iter->end_sk) {
3378 		bpf_iter_udp_put_batch(iter);
3379 		iter->st_bucket_done = false;
3380 	}
3381 }
3382 
3383 static const struct seq_operations bpf_iter_udp_seq_ops = {
3384 	.start		= bpf_iter_udp_seq_start,
3385 	.next		= bpf_iter_udp_seq_next,
3386 	.stop		= bpf_iter_udp_seq_stop,
3387 	.show		= bpf_iter_udp_seq_show,
3388 };
3389 #endif
3390 
seq_file_family(const struct seq_file * seq)3391 static unsigned short seq_file_family(const struct seq_file *seq)
3392 {
3393 	const struct udp_seq_afinfo *afinfo;
3394 
3395 #ifdef CONFIG_BPF_SYSCALL
3396 	/* BPF iterator: bpf programs to filter sockets. */
3397 	if (seq->op == &bpf_iter_udp_seq_ops)
3398 		return AF_UNSPEC;
3399 #endif
3400 
3401 	/* Proc fs iterator */
3402 	afinfo = pde_data(file_inode(seq->file));
3403 	return afinfo->family;
3404 }
3405 
3406 const struct seq_operations udp_seq_ops = {
3407 	.start		= udp_seq_start,
3408 	.next		= udp_seq_next,
3409 	.stop		= udp_seq_stop,
3410 	.show		= udp4_seq_show,
3411 };
3412 EXPORT_SYMBOL(udp_seq_ops);
3413 
3414 static struct udp_seq_afinfo udp4_seq_afinfo = {
3415 	.family		= AF_INET,
3416 	.udp_table	= NULL,
3417 };
3418 
udp4_proc_init_net(struct net * net)3419 static int __net_init udp4_proc_init_net(struct net *net)
3420 {
3421 	if (!proc_create_net_data("udp", 0444, net->proc_net, &udp_seq_ops,
3422 			sizeof(struct udp_iter_state), &udp4_seq_afinfo))
3423 		return -ENOMEM;
3424 	return 0;
3425 }
3426 
udp4_proc_exit_net(struct net * net)3427 static void __net_exit udp4_proc_exit_net(struct net *net)
3428 {
3429 	remove_proc_entry("udp", net->proc_net);
3430 }
3431 
3432 static struct pernet_operations udp4_net_ops = {
3433 	.init = udp4_proc_init_net,
3434 	.exit = udp4_proc_exit_net,
3435 };
3436 
udp4_proc_init(void)3437 int __init udp4_proc_init(void)
3438 {
3439 	return register_pernet_subsys(&udp4_net_ops);
3440 }
3441 
udp4_proc_exit(void)3442 void udp4_proc_exit(void)
3443 {
3444 	unregister_pernet_subsys(&udp4_net_ops);
3445 }
3446 #endif /* CONFIG_PROC_FS */
3447 
3448 static __initdata unsigned long uhash_entries;
set_uhash_entries(char * str)3449 static int __init set_uhash_entries(char *str)
3450 {
3451 	ssize_t ret;
3452 
3453 	if (!str)
3454 		return 0;
3455 
3456 	ret = kstrtoul(str, 0, &uhash_entries);
3457 	if (ret)
3458 		return 0;
3459 
3460 	if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
3461 		uhash_entries = UDP_HTABLE_SIZE_MIN;
3462 	return 1;
3463 }
3464 __setup("uhash_entries=", set_uhash_entries);
3465 
udp_table_init(struct udp_table * table,const char * name)3466 void __init udp_table_init(struct udp_table *table, const char *name)
3467 {
3468 	unsigned int i;
3469 
3470 	table->hash = alloc_large_system_hash(name,
3471 					      2 * sizeof(struct udp_hslot),
3472 					      uhash_entries,
3473 					      21, /* one slot per 2 MB */
3474 					      0,
3475 					      &table->log,
3476 					      &table->mask,
3477 					      UDP_HTABLE_SIZE_MIN,
3478 					      UDP_HTABLE_SIZE_MAX);
3479 
3480 	table->hash2 = table->hash + (table->mask + 1);
3481 	for (i = 0; i <= table->mask; i++) {
3482 		INIT_HLIST_HEAD(&table->hash[i].head);
3483 		table->hash[i].count = 0;
3484 		spin_lock_init(&table->hash[i].lock);
3485 	}
3486 	for (i = 0; i <= table->mask; i++) {
3487 		INIT_HLIST_HEAD(&table->hash2[i].head);
3488 		table->hash2[i].count = 0;
3489 		spin_lock_init(&table->hash2[i].lock);
3490 	}
3491 }
3492 
udp_flow_hashrnd(void)3493 u32 udp_flow_hashrnd(void)
3494 {
3495 	static u32 hashrnd __read_mostly;
3496 
3497 	net_get_random_once(&hashrnd, sizeof(hashrnd));
3498 
3499 	return hashrnd;
3500 }
3501 EXPORT_SYMBOL(udp_flow_hashrnd);
3502 
udp_sysctl_init(struct net * net)3503 static void __net_init udp_sysctl_init(struct net *net)
3504 {
3505 	net->ipv4.sysctl_udp_rmem_min = PAGE_SIZE;
3506 	net->ipv4.sysctl_udp_wmem_min = PAGE_SIZE;
3507 
3508 #ifdef CONFIG_NET_L3_MASTER_DEV
3509 	net->ipv4.sysctl_udp_l3mdev_accept = 0;
3510 #endif
3511 }
3512 
udp_pernet_table_alloc(unsigned int hash_entries)3513 static struct udp_table __net_init *udp_pernet_table_alloc(unsigned int hash_entries)
3514 {
3515 	struct udp_table *udptable;
3516 	int i;
3517 
3518 	udptable = kmalloc(sizeof(*udptable), GFP_KERNEL);
3519 	if (!udptable)
3520 		goto out;
3521 
3522 	udptable->hash = vmalloc_huge(hash_entries * 2 * sizeof(struct udp_hslot),
3523 				      GFP_KERNEL_ACCOUNT);
3524 	if (!udptable->hash)
3525 		goto free_table;
3526 
3527 	udptable->hash2 = udptable->hash + hash_entries;
3528 	udptable->mask = hash_entries - 1;
3529 	udptable->log = ilog2(hash_entries);
3530 
3531 	for (i = 0; i < hash_entries; i++) {
3532 		INIT_HLIST_HEAD(&udptable->hash[i].head);
3533 		udptable->hash[i].count = 0;
3534 		spin_lock_init(&udptable->hash[i].lock);
3535 
3536 		INIT_HLIST_HEAD(&udptable->hash2[i].head);
3537 		udptable->hash2[i].count = 0;
3538 		spin_lock_init(&udptable->hash2[i].lock);
3539 	}
3540 
3541 	return udptable;
3542 
3543 free_table:
3544 	kfree(udptable);
3545 out:
3546 	return NULL;
3547 }
3548 
udp_pernet_table_free(struct net * net)3549 static void __net_exit udp_pernet_table_free(struct net *net)
3550 {
3551 	struct udp_table *udptable = net->ipv4.udp_table;
3552 
3553 	if (udptable == &udp_table)
3554 		return;
3555 
3556 	kvfree(udptable->hash);
3557 	kfree(udptable);
3558 }
3559 
udp_set_table(struct net * net)3560 static void __net_init udp_set_table(struct net *net)
3561 {
3562 	struct udp_table *udptable;
3563 	unsigned int hash_entries;
3564 	struct net *old_net;
3565 
3566 	if (net_eq(net, &init_net))
3567 		goto fallback;
3568 
3569 	old_net = current->nsproxy->net_ns;
3570 	hash_entries = READ_ONCE(old_net->ipv4.sysctl_udp_child_hash_entries);
3571 	if (!hash_entries)
3572 		goto fallback;
3573 
3574 	/* Set min to keep the bitmap on stack in udp_lib_get_port() */
3575 	if (hash_entries < UDP_HTABLE_SIZE_MIN_PERNET)
3576 		hash_entries = UDP_HTABLE_SIZE_MIN_PERNET;
3577 	else
3578 		hash_entries = roundup_pow_of_two(hash_entries);
3579 
3580 	udptable = udp_pernet_table_alloc(hash_entries);
3581 	if (udptable) {
3582 		net->ipv4.udp_table = udptable;
3583 	} else {
3584 		pr_warn("Failed to allocate UDP hash table (entries: %u) "
3585 			"for a netns, fallback to the global one\n",
3586 			hash_entries);
3587 fallback:
3588 		net->ipv4.udp_table = &udp_table;
3589 	}
3590 }
3591 
udp_pernet_init(struct net * net)3592 static int __net_init udp_pernet_init(struct net *net)
3593 {
3594 	udp_sysctl_init(net);
3595 	udp_set_table(net);
3596 
3597 	return 0;
3598 }
3599 
udp_pernet_exit(struct net * net)3600 static void __net_exit udp_pernet_exit(struct net *net)
3601 {
3602 	udp_pernet_table_free(net);
3603 }
3604 
3605 static struct pernet_operations __net_initdata udp_sysctl_ops = {
3606 	.init	= udp_pernet_init,
3607 	.exit	= udp_pernet_exit,
3608 };
3609 
3610 #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)3611 DEFINE_BPF_ITER_FUNC(udp, struct bpf_iter_meta *meta,
3612 		     struct udp_sock *udp_sk, uid_t uid, int bucket)
3613 
3614 static int bpf_iter_udp_realloc_batch(struct bpf_udp_iter_state *iter,
3615 				      unsigned int new_batch_sz)
3616 {
3617 	struct sock **new_batch;
3618 
3619 	new_batch = kvmalloc_array(new_batch_sz, sizeof(*new_batch),
3620 				   GFP_USER | __GFP_NOWARN);
3621 	if (!new_batch)
3622 		return -ENOMEM;
3623 
3624 	bpf_iter_udp_put_batch(iter);
3625 	kvfree(iter->batch);
3626 	iter->batch = new_batch;
3627 	iter->max_sk = new_batch_sz;
3628 
3629 	return 0;
3630 }
3631 
3632 #define INIT_BATCH_SZ 16
3633 
bpf_iter_init_udp(void * priv_data,struct bpf_iter_aux_info * aux)3634 static int bpf_iter_init_udp(void *priv_data, struct bpf_iter_aux_info *aux)
3635 {
3636 	struct bpf_udp_iter_state *iter = priv_data;
3637 	int ret;
3638 
3639 	ret = bpf_iter_init_seq_net(priv_data, aux);
3640 	if (ret)
3641 		return ret;
3642 
3643 	ret = bpf_iter_udp_realloc_batch(iter, INIT_BATCH_SZ);
3644 	if (ret)
3645 		bpf_iter_fini_seq_net(priv_data);
3646 
3647 	return ret;
3648 }
3649 
bpf_iter_fini_udp(void * priv_data)3650 static void bpf_iter_fini_udp(void *priv_data)
3651 {
3652 	struct bpf_udp_iter_state *iter = priv_data;
3653 
3654 	bpf_iter_fini_seq_net(priv_data);
3655 	kvfree(iter->batch);
3656 }
3657 
3658 static const struct bpf_iter_seq_info udp_seq_info = {
3659 	.seq_ops		= &bpf_iter_udp_seq_ops,
3660 	.init_seq_private	= bpf_iter_init_udp,
3661 	.fini_seq_private	= bpf_iter_fini_udp,
3662 	.seq_priv_size		= sizeof(struct bpf_udp_iter_state),
3663 };
3664 
3665 static struct bpf_iter_reg udp_reg_info = {
3666 	.target			= "udp",
3667 	.ctx_arg_info_size	= 1,
3668 	.ctx_arg_info		= {
3669 		{ offsetof(struct bpf_iter__udp, udp_sk),
3670 		  PTR_TO_BTF_ID_OR_NULL | PTR_TRUSTED },
3671 	},
3672 	.seq_info		= &udp_seq_info,
3673 };
3674 
bpf_iter_register(void)3675 static void __init bpf_iter_register(void)
3676 {
3677 	udp_reg_info.ctx_arg_info[0].btf_id = btf_sock_ids[BTF_SOCK_TYPE_UDP];
3678 	if (bpf_iter_reg_target(&udp_reg_info))
3679 		pr_warn("Warning: could not register bpf iterator udp\n");
3680 }
3681 #endif
3682 
udp_init(void)3683 void __init udp_init(void)
3684 {
3685 	unsigned long limit;
3686 	unsigned int i;
3687 
3688 	udp_table_init(&udp_table, "UDP");
3689 	limit = nr_free_buffer_pages() / 8;
3690 	limit = max(limit, 128UL);
3691 	sysctl_udp_mem[0] = limit / 4 * 3;
3692 	sysctl_udp_mem[1] = limit;
3693 	sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
3694 
3695 	/* 16 spinlocks per cpu */
3696 	udp_busylocks_log = ilog2(nr_cpu_ids) + 4;
3697 	udp_busylocks = kmalloc(sizeof(spinlock_t) << udp_busylocks_log,
3698 				GFP_KERNEL);
3699 	if (!udp_busylocks)
3700 		panic("UDP: failed to alloc udp_busylocks\n");
3701 	for (i = 0; i < (1U << udp_busylocks_log); i++)
3702 		spin_lock_init(udp_busylocks + i);
3703 
3704 	if (register_pernet_subsys(&udp_sysctl_ops))
3705 		panic("UDP: failed to init sysctl parameters.\n");
3706 
3707 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
3708 	bpf_iter_register();
3709 #endif
3710 }
3711