bpf: Make btf_sock_ids global
[linux-2.6-block.git] / net / ipv4 / udp.c
CommitLineData
2874c5fd 1// SPDX-License-Identifier: GPL-2.0-or-later
1da177e4
LT
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 *
02c30a84 9 * Authors: Ross Biro
1da177e4
LT
10 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
11 * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
113aa838 12 * Alan Cox, <alan@lxorguk.ukuu.org.uk>
1da177e4
LT
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
e905a9ed
YH
22 * Alan Cox : Tidied select() semantics.
23 * Alan Cox : udp_err() fixed properly, also now
1da177e4
LT
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
e905a9ed 58 * for connect.
1da177e4
LT
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
342f0234 72 * James Chapman : Add L2TP encapsulation type.
1da177e4 73 */
e905a9ed 74
afd46503
JP
75#define pr_fmt(fmt) "UDP: " fmt
76
7c0f6ba6 77#include <linux/uaccess.h>
1da177e4 78#include <asm/ioctls.h>
57c8a661 79#include <linux/memblock.h>
8203efb3
ED
80#include <linux/highmem.h>
81#include <linux/swap.h>
1da177e4
LT
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>
14c85021 87#include <linux/igmp.h>
6e540309 88#include <linux/inetdevice.h>
1da177e4
LT
89#include <linux/in.h>
90#include <linux/errno.h>
91#include <linux/timer.h>
92#include <linux/mm.h>
1da177e4 93#include <linux/inet.h>
1da177e4 94#include <linux/netdevice.h>
5a0e3ad6 95#include <linux/slab.h>
c752f073 96#include <net/tcp_states.h>
1da177e4
LT
97#include <linux/skbuff.h>
98#include <linux/proc_fs.h>
99#include <linux/seq_file.h>
457c4cbc 100#include <net/net_namespace.h>
1da177e4 101#include <net/icmp.h>
421b3885 102#include <net/inet_hashtables.h>
e7cc0824 103#include <net/ip_tunnels.h>
1da177e4 104#include <net/route.h>
1da177e4
LT
105#include <net/checksum.h>
106#include <net/xfrm.h>
296f7ea7 107#include <trace/events/udp.h>
447167bf 108#include <linux/static_key.h>
22911fc5 109#include <trace/events/skb.h>
076bb0c8 110#include <net/busy_poll.h>
ba4e58ec 111#include "udp_impl.h"
e32ea7e7 112#include <net/sock_reuseport.h>
217375a0 113#include <net/addrconf.h>
60fb9567 114#include <net/udp_tunnel.h>
0146dca7
SD
115#if IS_ENABLED(CONFIG_IPV6)
116#include <net/ipv6_stubs.h>
117#endif
1da177e4 118
f86dcc5a 119struct udp_table udp_table __read_mostly;
645ca708 120EXPORT_SYMBOL(udp_table);
1da177e4 121
8d987e5c 122long sysctl_udp_mem[3] __read_mostly;
95766fff 123EXPORT_SYMBOL(sysctl_udp_mem);
c482c568 124
8d987e5c 125atomic_long_t udp_memory_allocated;
95766fff
HA
126EXPORT_SYMBOL(udp_memory_allocated);
127
f86dcc5a
ED
128#define MAX_UDP_PORTS 65536
129#define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN)
98322f22 130
f24d43c0 131static int udp_lib_lport_inuse(struct net *net, __u16 num,
645ca708 132 const struct udp_hslot *hslot,
98322f22 133 unsigned long *bitmap,
fe38d2a1 134 struct sock *sk, unsigned int log)
1da177e4 135{
f24d43c0 136 struct sock *sk2;
ba418fa3 137 kuid_t uid = sock_i_uid(sk);
25030a7f 138
ca065d0c 139 sk_for_each(sk2, &hslot->head) {
9d4fb27d
JP
140 if (net_eq(sock_net(sk2), net) &&
141 sk2 != sk &&
d4cada4a 142 (bitmap || udp_sk(sk2)->udp_port_hash == num) &&
9d4fb27d
JP
143 (!sk2->sk_reuse || !sk->sk_reuse) &&
144 (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
145 sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
fe38d2a1 146 inet_rcv_saddr_equal(sk, sk2, true)) {
df560056
EG
147 if (sk2->sk_reuseport && sk->sk_reuseport &&
148 !rcu_access_pointer(sk->sk_reuseport_cb) &&
149 uid_eq(uid, sock_i_uid(sk2))) {
150 if (!bitmap)
151 return 0;
152 } else {
153 if (!bitmap)
154 return 1;
155 __set_bit(udp_sk(sk2)->udp_port_hash >> log,
156 bitmap);
157 }
98322f22 158 }
4243cdc2 159 }
25030a7f
GR
160 return 0;
161}
162
30fff923
ED
163/*
164 * Note: we still hold spinlock of primary hash chain, so no other writer
165 * can insert/delete a socket with local_port == num
166 */
167static int udp_lib_lport_inuse2(struct net *net, __u16 num,
4243cdc2 168 struct udp_hslot *hslot2,
fe38d2a1 169 struct sock *sk)
30fff923
ED
170{
171 struct sock *sk2;
ba418fa3 172 kuid_t uid = sock_i_uid(sk);
30fff923
ED
173 int res = 0;
174
175 spin_lock(&hslot2->lock);
ca065d0c 176 udp_portaddr_for_each_entry(sk2, &hslot2->head) {
9d4fb27d
JP
177 if (net_eq(sock_net(sk2), net) &&
178 sk2 != sk &&
179 (udp_sk(sk2)->udp_port_hash == num) &&
180 (!sk2->sk_reuse || !sk->sk_reuse) &&
181 (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
182 sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
fe38d2a1 183 inet_rcv_saddr_equal(sk, sk2, true)) {
df560056
EG
184 if (sk2->sk_reuseport && sk->sk_reuseport &&
185 !rcu_access_pointer(sk->sk_reuseport_cb) &&
186 uid_eq(uid, sock_i_uid(sk2))) {
187 res = 0;
188 } else {
189 res = 1;
190 }
30fff923
ED
191 break;
192 }
4243cdc2 193 }
30fff923
ED
194 spin_unlock(&hslot2->lock);
195 return res;
196}
197
fe38d2a1 198static int udp_reuseport_add_sock(struct sock *sk, struct udp_hslot *hslot)
e32ea7e7
CG
199{
200 struct net *net = sock_net(sk);
e32ea7e7
CG
201 kuid_t uid = sock_i_uid(sk);
202 struct sock *sk2;
203
ca065d0c 204 sk_for_each(sk2, &hslot->head) {
e32ea7e7
CG
205 if (net_eq(sock_net(sk2), net) &&
206 sk2 != sk &&
207 sk2->sk_family == sk->sk_family &&
208 ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
209 (udp_sk(sk2)->udp_port_hash == udp_sk(sk)->udp_port_hash) &&
210 (sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
211 sk2->sk_reuseport && uid_eq(uid, sock_i_uid(sk2)) &&
fe38d2a1 212 inet_rcv_saddr_equal(sk, sk2, false)) {
2dbb9b9e
MKL
213 return reuseport_add_sock(sk, sk2,
214 inet_rcv_saddr_any(sk));
e32ea7e7
CG
215 }
216 }
217
2dbb9b9e 218 return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
e32ea7e7
CG
219}
220
25030a7f 221/**
6ba5a3c5 222 * udp_lib_get_port - UDP/-Lite port lookup for IPv4 and IPv6
25030a7f
GR
223 *
224 * @sk: socket struct in question
225 * @snum: port number to look up
25985edc 226 * @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
30fff923 227 * with NULL address
25030a7f 228 */
6ba5a3c5 229int udp_lib_get_port(struct sock *sk, unsigned short snum,
30fff923 230 unsigned int hash2_nulladdr)
25030a7f 231{
512615b6 232 struct udp_hslot *hslot, *hslot2;
645ca708 233 struct udp_table *udptable = sk->sk_prot->h.udp_table;
25030a7f 234 int error = 1;
3b1e0a65 235 struct net *net = sock_net(sk);
1da177e4 236
32c1da70 237 if (!snum) {
9088c560 238 int low, high, remaining;
95c96174 239 unsigned int rand;
98322f22
ED
240 unsigned short first, last;
241 DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
32c1da70 242
0bbf87d8 243 inet_get_local_port_range(net, &low, &high);
a25de534 244 remaining = (high - low) + 1;
227b60f5 245
63862b5b 246 rand = prandom_u32();
8fc54f68 247 first = reciprocal_scale(rand, remaining) + low;
98322f22
ED
248 /*
249 * force rand to be an odd multiple of UDP_HTABLE_SIZE
250 */
f86dcc5a 251 rand = (rand | 1) * (udptable->mask + 1);
5781b235
ED
252 last = first + udptable->mask + 1;
253 do {
f86dcc5a 254 hslot = udp_hashslot(udptable, net, first);
98322f22 255 bitmap_zero(bitmap, PORTS_PER_CHAIN);
645ca708 256 spin_lock_bh(&hslot->lock);
98322f22 257 udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
fe38d2a1 258 udptable->log);
98322f22
ED
259
260 snum = first;
261 /*
262 * Iterate on all possible values of snum for this hash.
263 * Using steps of an odd multiple of UDP_HTABLE_SIZE
264 * give us randomization and full range coverage.
265 */
9088c560 266 do {
98322f22 267 if (low <= snum && snum <= high &&
e3826f1e 268 !test_bit(snum >> udptable->log, bitmap) &&
122ff243 269 !inet_is_local_reserved_port(net, snum))
98322f22
ED
270 goto found;
271 snum += rand;
272 } while (snum != first);
273 spin_unlock_bh(&hslot->lock);
df560056 274 cond_resched();
5781b235 275 } while (++first != last);
98322f22 276 goto fail;
645ca708 277 } else {
f86dcc5a 278 hslot = udp_hashslot(udptable, net, snum);
645ca708 279 spin_lock_bh(&hslot->lock);
30fff923
ED
280 if (hslot->count > 10) {
281 int exist;
282 unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
283
284 slot2 &= udptable->mask;
285 hash2_nulladdr &= udptable->mask;
286
287 hslot2 = udp_hashslot2(udptable, slot2);
288 if (hslot->count < hslot2->count)
289 goto scan_primary_hash;
290
fe38d2a1 291 exist = udp_lib_lport_inuse2(net, snum, hslot2, sk);
30fff923
ED
292 if (!exist && (hash2_nulladdr != slot2)) {
293 hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
294 exist = udp_lib_lport_inuse2(net, snum, hslot2,
fe38d2a1 295 sk);
30fff923
ED
296 }
297 if (exist)
298 goto fail_unlock;
299 else
300 goto found;
301 }
302scan_primary_hash:
fe38d2a1 303 if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, 0))
645ca708
ED
304 goto fail_unlock;
305 }
98322f22 306found:
c720c7e8 307 inet_sk(sk)->inet_num = snum;
d4cada4a
ED
308 udp_sk(sk)->udp_port_hash = snum;
309 udp_sk(sk)->udp_portaddr_hash ^= snum;
1da177e4 310 if (sk_unhashed(sk)) {
e32ea7e7 311 if (sk->sk_reuseport &&
fe38d2a1 312 udp_reuseport_add_sock(sk, hslot)) {
e32ea7e7
CG
313 inet_sk(sk)->inet_num = 0;
314 udp_sk(sk)->udp_port_hash = 0;
315 udp_sk(sk)->udp_portaddr_hash ^= snum;
316 goto fail_unlock;
317 }
318
ca065d0c 319 sk_add_node_rcu(sk, &hslot->head);
fdcc8aa9 320 hslot->count++;
c29a0bc4 321 sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
512615b6
ED
322
323 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
324 spin_lock(&hslot2->lock);
d894ba18 325 if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
1602f49b
DM
326 sk->sk_family == AF_INET6)
327 hlist_add_tail_rcu(&udp_sk(sk)->udp_portaddr_node,
328 &hslot2->head);
d894ba18 329 else
1602f49b
DM
330 hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
331 &hslot2->head);
512615b6
ED
332 hslot2->count++;
333 spin_unlock(&hslot2->lock);
1da177e4 334 }
ca065d0c 335 sock_set_flag(sk, SOCK_RCU_FREE);
25030a7f 336 error = 0;
645ca708
ED
337fail_unlock:
338 spin_unlock_bh(&hslot->lock);
1da177e4 339fail:
25030a7f
GR
340 return error;
341}
c482c568 342EXPORT_SYMBOL(udp_lib_get_port);
25030a7f 343
6ba5a3c5 344int udp_v4_get_port(struct sock *sk, unsigned short snum)
db8dac20 345{
30fff923 346 unsigned int hash2_nulladdr =
f0b1e64c 347 ipv4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
30fff923 348 unsigned int hash2_partial =
f0b1e64c 349 ipv4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
30fff923 350
d4cada4a 351 /* precompute partial secondary hash */
30fff923 352 udp_sk(sk)->udp_portaddr_hash = hash2_partial;
fe38d2a1 353 return udp_lib_get_port(sk, snum, hash2_nulladdr);
db8dac20
DM
354}
355
d1e37288
SX
356static int compute_score(struct sock *sk, struct net *net,
357 __be32 saddr, __be16 sport,
fb74c277 358 __be32 daddr, unsigned short hnum,
73545373 359 int dif, int sdif)
645ca708 360{
60c04aec
JP
361 int score;
362 struct inet_sock *inet;
6da5b0f0 363 bool dev_match;
645ca708 364
60c04aec
JP
365 if (!net_eq(sock_net(sk), net) ||
366 udp_sk(sk)->udp_port_hash != hnum ||
367 ipv6_only_sock(sk))
368 return -1;
645ca708 369
4cdeeee9
PO
370 if (sk->sk_rcv_saddr != daddr)
371 return -1;
60c04aec 372
4cdeeee9 373 score = (sk->sk_family == PF_INET) ? 2 : 1;
60c04aec 374
4cdeeee9 375 inet = inet_sk(sk);
60c04aec
JP
376 if (inet->inet_daddr) {
377 if (inet->inet_daddr != saddr)
378 return -1;
379 score += 4;
380 }
381
382 if (inet->inet_dport) {
383 if (inet->inet_dport != sport)
384 return -1;
385 score += 4;
386 }
387
6da5b0f0
MM
388 dev_match = udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if,
389 dif, sdif);
390 if (!dev_match)
391 return -1;
392 score += 4;
fb74c277 393
7170a977 394 if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
70da268b 395 score++;
645ca708
ED
396 return score;
397}
398
6eada011
ED
399static u32 udp_ehashfn(const struct net *net, const __be32 laddr,
400 const __u16 lport, const __be32 faddr,
401 const __be16 fport)
65cd8033 402{
1bbdceef
HFS
403 static u32 udp_ehash_secret __read_mostly;
404
405 net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret));
406
65cd8033 407 return __inet_ehashfn(laddr, lport, faddr, fport,
1bbdceef 408 udp_ehash_secret + net_hash_mix(net));
65cd8033
HFS
409}
410
7629c73a
JS
411static inline struct sock *lookup_reuseport(struct net *net, struct sock *sk,
412 struct sk_buff *skb,
413 __be32 saddr, __be16 sport,
414 __be32 daddr, unsigned short hnum)
415{
416 struct sock *reuse_sk = NULL;
417 u32 hash;
418
419 if (sk->sk_reuseport && sk->sk_state != TCP_ESTABLISHED) {
420 hash = udp_ehashfn(net, daddr, hnum, saddr, sport);
421 reuse_sk = reuseport_select_sock(sk, hash, skb,
422 sizeof(struct udphdr));
423 /* Fall back to scoring if group has connections */
424 if (reuseport_has_conns(sk, false))
425 return NULL;
426 }
427 return reuse_sk;
428}
429
d1e37288 430/* called with rcu_read_lock() */
5051ebd2 431static struct sock *udp4_lib_lookup2(struct net *net,
fb74c277
DA
432 __be32 saddr, __be16 sport,
433 __be32 daddr, unsigned int hnum,
73545373 434 int dif, int sdif,
fb74c277
DA
435 struct udp_hslot *hslot2,
436 struct sk_buff *skb)
5051ebd2
ED
437{
438 struct sock *sk, *result;
e94a62f5 439 int score, badness;
5051ebd2 440
5051ebd2 441 result = NULL;
ba418fa3 442 badness = 0;
ca065d0c 443 udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
d1e37288 444 score = compute_score(sk, net, saddr, sport,
73545373 445 daddr, hnum, dif, sdif);
5051ebd2 446 if (score > badness) {
7629c73a
JS
447 result = lookup_reuseport(net, sk, skb,
448 saddr, sport, daddr, hnum);
449 if (result)
450 return result;
451
ca065d0c
ED
452 badness = score;
453 result = sk;
5051ebd2
ED
454 }
455 }
5051ebd2
ED
456 return result;
457}
458
72f7e944
JS
459static inline struct sock *udp4_lookup_run_bpf(struct net *net,
460 struct udp_table *udptable,
461 struct sk_buff *skb,
462 __be32 saddr, __be16 sport,
463 __be32 daddr, u16 hnum)
464{
465 struct sock *sk, *reuse_sk;
466 bool no_reuseport;
467
468 if (udptable != &udp_table)
469 return NULL; /* only UDP is supported */
470
471 no_reuseport = bpf_sk_lookup_run_v4(net, IPPROTO_UDP,
472 saddr, sport, daddr, hnum, &sk);
473 if (no_reuseport || IS_ERR_OR_NULL(sk))
474 return sk;
475
476 reuse_sk = lookup_reuseport(net, sk, skb, saddr, sport, daddr, hnum);
477 if (reuse_sk)
478 sk = reuse_sk;
479 return sk;
480}
481
db8dac20
DM
482/* UDP is nearly always wildcards out the wazoo, it makes no sense to try
483 * harder than this. -DaveM
484 */
fce82338 485struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
fb74c277
DA
486 __be16 sport, __be32 daddr, __be16 dport, int dif,
487 int sdif, struct udp_table *udptable, struct sk_buff *skb)
db8dac20 488{
db8dac20 489 unsigned short hnum = ntohs(dport);
4cdeeee9
PO
490 unsigned int hash2, slot2;
491 struct udp_hslot *hslot2;
72f7e944 492 struct sock *result, *sk;
645ca708 493
4cdeeee9
PO
494 hash2 = ipv4_portaddr_hash(net, daddr, hnum);
495 slot2 = hash2 & udptable->mask;
496 hslot2 = &udptable->hash2[slot2];
497
72f7e944 498 /* Lookup connected or non-wildcard socket */
4cdeeee9
PO
499 result = udp4_lib_lookup2(net, saddr, sport,
500 daddr, hnum, dif, sdif,
73545373 501 hslot2, skb);
72f7e944
JS
502 if (!IS_ERR_OR_NULL(result) && result->sk_state == TCP_ESTABLISHED)
503 goto done;
504
505 /* Lookup redirect from BPF */
506 if (static_branch_unlikely(&bpf_sk_lookup_enabled)) {
507 sk = udp4_lookup_run_bpf(net, udptable, skb,
508 saddr, sport, daddr, hnum);
509 if (sk) {
510 result = sk;
511 goto done;
512 }
db8dac20 513 }
72f7e944
JS
514
515 /* Got non-wildcard socket or error on first lookup */
516 if (result)
517 goto done;
518
519 /* Lookup wildcard sockets */
520 hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
521 slot2 = hash2 & udptable->mask;
522 hslot2 = &udptable->hash2[slot2];
523
524 result = udp4_lib_lookup2(net, saddr, sport,
525 htonl(INADDR_ANY), hnum, dif, sdif,
526 hslot2, skb);
527done:
88e235b8 528 if (IS_ERR(result))
4cdeeee9 529 return NULL;
db8dac20
DM
530 return result;
531}
fce82338 532EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
db8dac20 533
607c4aaf
KK
534static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
535 __be16 sport, __be16 dport,
645ca708 536 struct udp_table *udptable)
607c4aaf
KK
537{
538 const struct iphdr *iph = ip_hdr(skb);
539
ed7cbbce 540 return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
8afdd99a 541 iph->daddr, dport, inet_iif(skb),
fb74c277 542 inet_sdif(skb), udptable, skb);
607c4aaf
KK
543}
544
63058308
TH
545struct sock *udp4_lib_lookup_skb(struct sk_buff *skb,
546 __be16 sport, __be16 dport)
547{
257a525f
MKL
548 const struct iphdr *iph = ip_hdr(skb);
549
550 return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
551 iph->daddr, dport, inet_iif(skb),
552 inet_sdif(skb), &udp_table, NULL);
63058308
TH
553}
554EXPORT_SYMBOL_GPL(udp4_lib_lookup_skb);
555
ca065d0c
ED
556/* Must be called under rcu_read_lock().
557 * Does increment socket refcount.
558 */
6e86000c 559#if IS_ENABLED(CONFIG_NF_TPROXY_IPV4) || IS_ENABLED(CONFIG_NF_SOCKET_IPV4)
bcd41303
KK
560struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
561 __be32 daddr, __be16 dport, int dif)
562{
ca065d0c
ED
563 struct sock *sk;
564
565 sk = __udp4_lib_lookup(net, saddr, sport, daddr, dport,
fb74c277 566 dif, 0, &udp_table, NULL);
41c6d650 567 if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
ca065d0c
ED
568 sk = NULL;
569 return sk;
bcd41303
KK
570}
571EXPORT_SYMBOL_GPL(udp4_lib_lookup);
ca065d0c 572#endif
bcd41303 573
421b3885
SB
574static inline bool __udp_is_mcast_sock(struct net *net, struct sock *sk,
575 __be16 loc_port, __be32 loc_addr,
576 __be16 rmt_port, __be32 rmt_addr,
fb74c277 577 int dif, int sdif, unsigned short hnum)
421b3885
SB
578{
579 struct inet_sock *inet = inet_sk(sk);
580
581 if (!net_eq(sock_net(sk), net) ||
582 udp_sk(sk)->udp_port_hash != hnum ||
583 (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
584 (inet->inet_dport != rmt_port && inet->inet_dport) ||
585 (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) ||
586 ipv6_only_sock(sk) ||
82ba25c6 587 !udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif))
421b3885 588 return false;
60d9b031 589 if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif, sdif))
421b3885
SB
590 return false;
591 return true;
592}
593
a36e185e
SB
594DEFINE_STATIC_KEY_FALSE(udp_encap_needed_key);
595void udp_encap_enable(void)
596{
9c480601 597 static_branch_inc(&udp_encap_needed_key);
a36e185e
SB
598}
599EXPORT_SYMBOL(udp_encap_enable);
600
e7cc0824
SB
601/* Handler for tunnels with arbitrary destination ports: no socket lookup, go
602 * through error handlers in encapsulations looking for a match.
603 */
604static int __udp4_lib_err_encap_no_sk(struct sk_buff *skb, u32 info)
605{
606 int i;
607
608 for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) {
609 int (*handler)(struct sk_buff *skb, u32 info);
92b95364 610 const struct ip_tunnel_encap_ops *encap;
e7cc0824 611
92b95364
PA
612 encap = rcu_dereference(iptun_encaps[i]);
613 if (!encap)
e7cc0824 614 continue;
92b95364 615 handler = encap->err_handler;
e7cc0824
SB
616 if (handler && !handler(skb, info))
617 return 0;
618 }
619
620 return -ENOENT;
621}
622
a36e185e
SB
623/* Try to match ICMP errors to UDP tunnels by looking up a socket without
624 * reversing source and destination port: this will match tunnels that force the
625 * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that
626 * lwtunnels might actually break this assumption by being configured with
627 * different destination ports on endpoints, in this case we won't be able to
628 * trace ICMP messages back to them.
629 *
e7cc0824
SB
630 * If this doesn't match any socket, probe tunnels with arbitrary destination
631 * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port
632 * we've sent packets to won't necessarily match the local destination port.
633 *
a36e185e
SB
634 * Then ask the tunnel implementation to match the error against a valid
635 * association.
636 *
e7cc0824
SB
637 * Return an error if we can't find a match, the socket if we need further
638 * processing, zero otherwise.
a36e185e
SB
639 */
640static struct sock *__udp4_lib_err_encap(struct net *net,
641 const struct iphdr *iph,
642 struct udphdr *uh,
643 struct udp_table *udptable,
e7cc0824 644 struct sk_buff *skb, u32 info)
a36e185e 645{
a36e185e 646 int network_offset, transport_offset;
a36e185e
SB
647 struct sock *sk;
648
a36e185e
SB
649 network_offset = skb_network_offset(skb);
650 transport_offset = skb_transport_offset(skb);
651
652 /* Network header needs to point to the outer IPv4 header inside ICMP */
653 skb_reset_network_header(skb);
654
655 /* Transport header needs to point to the UDP header */
656 skb_set_transport_header(skb, iph->ihl << 2);
657
e7cc0824
SB
658 sk = __udp4_lib_lookup(net, iph->daddr, uh->source,
659 iph->saddr, uh->dest, skb->dev->ifindex, 0,
660 udptable, NULL);
661 if (sk) {
662 int (*lookup)(struct sock *sk, struct sk_buff *skb);
663 struct udp_sock *up = udp_sk(sk);
664
665 lookup = READ_ONCE(up->encap_err_lookup);
666 if (!lookup || lookup(sk, skb))
667 sk = NULL;
668 }
669
670 if (!sk)
671 sk = ERR_PTR(__udp4_lib_err_encap_no_sk(skb, info));
a36e185e
SB
672
673 skb_set_transport_header(skb, transport_offset);
674 skb_set_network_header(skb, network_offset);
675
676 return sk;
677}
678
db8dac20
DM
679/*
680 * This routine is called by the ICMP module when it gets some
681 * sort of error condition. If err < 0 then the socket should
682 * be closed and the error returned to the user. If err > 0
683 * it's just the icmp type << 8 | icmp code.
684 * Header points to the ip header of the error packet. We move
685 * on past this. Then (as it used to claim before adjustment)
686 * header points to the first 8 bytes of the udp header. We need
687 * to find the appropriate port.
688 */
689
32bbd879 690int __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
db8dac20
DM
691{
692 struct inet_sock *inet;
b71d1d42 693 const struct iphdr *iph = (const struct iphdr *)skb->data;
c482c568 694 struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
db8dac20
DM
695 const int type = icmp_hdr(skb)->type;
696 const int code = icmp_hdr(skb)->code;
a36e185e 697 bool tunnel = false;
db8dac20
DM
698 struct sock *sk;
699 int harderr;
700 int err;
fd54d716 701 struct net *net = dev_net(skb->dev);
db8dac20 702
fd54d716 703 sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
f64bf6b8
MM
704 iph->saddr, uh->source, skb->dev->ifindex,
705 inet_sdif(skb), udptable, NULL);
51456b29 706 if (!sk) {
a36e185e 707 /* No socket for error: try tunnels before discarding */
e7cc0824
SB
708 sk = ERR_PTR(-ENOENT);
709 if (static_branch_unlikely(&udp_encap_needed_key)) {
710 sk = __udp4_lib_err_encap(net, iph, uh, udptable, skb,
711 info);
712 if (!sk)
713 return 0;
714 }
a36e185e 715
e7cc0824 716 if (IS_ERR(sk)) {
a36e185e 717 __ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
e7cc0824 718 return PTR_ERR(sk);
a36e185e 719 }
e7cc0824 720
a36e185e 721 tunnel = true;
db8dac20
DM
722 }
723
724 err = 0;
725 harderr = 0;
726 inet = inet_sk(sk);
727
728 switch (type) {
729 default:
730 case ICMP_TIME_EXCEEDED:
731 err = EHOSTUNREACH;
732 break;
733 case ICMP_SOURCE_QUENCH:
734 goto out;
735 case ICMP_PARAMETERPROB:
736 err = EPROTO;
737 harderr = 1;
738 break;
739 case ICMP_DEST_UNREACH:
740 if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
36393395 741 ipv4_sk_update_pmtu(skb, sk, info);
db8dac20
DM
742 if (inet->pmtudisc != IP_PMTUDISC_DONT) {
743 err = EMSGSIZE;
744 harderr = 1;
745 break;
746 }
747 goto out;
748 }
749 err = EHOSTUNREACH;
750 if (code <= NR_ICMP_UNREACH) {
751 harderr = icmp_err_convert[code].fatal;
752 err = icmp_err_convert[code].errno;
753 }
754 break;
55be7a9c
DM
755 case ICMP_REDIRECT:
756 ipv4_sk_redirect(skb, sk);
1a462d18 757 goto out;
db8dac20
DM
758 }
759
760 /*
761 * RFC1122: OK. Passes ICMP errors back to application, as per
762 * 4.1.3.3.
763 */
a36e185e
SB
764 if (tunnel) {
765 /* ...not for tunnels though: we don't have a sending socket */
766 goto out;
767 }
db8dac20
DM
768 if (!inet->recverr) {
769 if (!harderr || sk->sk_state != TCP_ESTABLISHED)
770 goto out;
b1faf566 771 } else
c482c568 772 ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
b1faf566 773
db8dac20
DM
774 sk->sk_err = err;
775 sk->sk_error_report(sk);
776out:
32bbd879 777 return 0;
db8dac20
DM
778}
779
32bbd879 780int udp_err(struct sk_buff *skb, u32 info)
db8dac20 781{
32bbd879 782 return __udp4_lib_err(skb, info, &udp_table);
db8dac20
DM
783}
784
785/*
786 * Throw away all pending data and cancel the corking. Socket is locked.
787 */
36d926b9 788void udp_flush_pending_frames(struct sock *sk)
db8dac20
DM
789{
790 struct udp_sock *up = udp_sk(sk);
791
792 if (up->pending) {
793 up->len = 0;
794 up->pending = 0;
795 ip_flush_pending_frames(sk);
796 }
797}
36d926b9 798EXPORT_SYMBOL(udp_flush_pending_frames);
db8dac20
DM
799
800/**
f6b9664f 801 * udp4_hwcsum - handle outgoing HW checksumming
db8dac20
DM
802 * @skb: sk_buff containing the filled-in UDP header
803 * (checksum field must be zeroed out)
f6b9664f
HX
804 * @src: source IP address
805 * @dst: destination IP address
db8dac20 806 */
c26bf4a5 807void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
db8dac20 808{
db8dac20 809 struct udphdr *uh = udp_hdr(skb);
f6b9664f
HX
810 int offset = skb_transport_offset(skb);
811 int len = skb->len - offset;
812 int hlen = len;
db8dac20
DM
813 __wsum csum = 0;
814
ebbe495f 815 if (!skb_has_frag_list(skb)) {
db8dac20
DM
816 /*
817 * Only one fragment on the socket.
818 */
819 skb->csum_start = skb_transport_header(skb) - skb->head;
820 skb->csum_offset = offsetof(struct udphdr, check);
f6b9664f
HX
821 uh->check = ~csum_tcpudp_magic(src, dst, len,
822 IPPROTO_UDP, 0);
db8dac20 823 } else {
ebbe495f
WC
824 struct sk_buff *frags;
825
db8dac20
DM
826 /*
827 * HW-checksum won't work as there are two or more
828 * fragments on the socket so that all csums of sk_buffs
829 * should be together
830 */
ebbe495f 831 skb_walk_frags(skb, frags) {
f6b9664f
HX
832 csum = csum_add(csum, frags->csum);
833 hlen -= frags->len;
ebbe495f 834 }
db8dac20 835
f6b9664f 836 csum = skb_checksum(skb, offset, hlen, csum);
db8dac20
DM
837 skb->ip_summed = CHECKSUM_NONE;
838
db8dac20
DM
839 uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
840 if (uh->check == 0)
841 uh->check = CSUM_MANGLED_0;
842 }
843}
c26bf4a5 844EXPORT_SYMBOL_GPL(udp4_hwcsum);
db8dac20 845
af5fcba7
TH
846/* Function to set UDP checksum for an IPv4 UDP packet. This is intended
847 * for the simple case like when setting the checksum for a UDP tunnel.
848 */
849void udp_set_csum(bool nocheck, struct sk_buff *skb,
850 __be32 saddr, __be32 daddr, int len)
851{
852 struct udphdr *uh = udp_hdr(skb);
853
179bc67f 854 if (nocheck) {
af5fcba7 855 uh->check = 0;
179bc67f 856 } else if (skb_is_gso(skb)) {
af5fcba7 857 uh->check = ~udp_v4_check(len, saddr, daddr, 0);
179bc67f
EC
858 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
859 uh->check = 0;
860 uh->check = udp_v4_check(len, saddr, daddr, lco_csum(skb));
861 if (uh->check == 0)
862 uh->check = CSUM_MANGLED_0;
d75f1306 863 } else {
af5fcba7
TH
864 skb->ip_summed = CHECKSUM_PARTIAL;
865 skb->csum_start = skb_transport_header(skb) - skb->head;
866 skb->csum_offset = offsetof(struct udphdr, check);
867 uh->check = ~udp_v4_check(len, saddr, daddr, 0);
af5fcba7
TH
868 }
869}
870EXPORT_SYMBOL(udp_set_csum);
871
bec1f6f6
WB
872static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4,
873 struct inet_cork *cork)
db8dac20 874{
f6b9664f 875 struct sock *sk = skb->sk;
db8dac20 876 struct inet_sock *inet = inet_sk(sk);
db8dac20
DM
877 struct udphdr *uh;
878 int err = 0;
879 int is_udplite = IS_UDPLITE(sk);
f6b9664f
HX
880 int offset = skb_transport_offset(skb);
881 int len = skb->len - offset;
4094871d 882 int datalen = len - sizeof(*uh);
db8dac20
DM
883 __wsum csum = 0;
884
db8dac20
DM
885 /*
886 * Create a UDP header
887 */
888 uh = udp_hdr(skb);
f6b9664f 889 uh->source = inet->inet_sport;
79ab0531 890 uh->dest = fl4->fl4_dport;
f6b9664f 891 uh->len = htons(len);
db8dac20
DM
892 uh->check = 0;
893
bec1f6f6
WB
894 if (cork->gso_size) {
895 const int hlen = skb_network_header_len(skb) +
896 sizeof(struct udphdr);
897
0f149c9f
WB
898 if (hlen + cork->gso_size > cork->fragsize) {
899 kfree_skb(skb);
bec1f6f6 900 return -EINVAL;
0f149c9f
WB
901 }
902 if (skb->len > cork->gso_size * UDP_MAX_SEGMENTS) {
903 kfree_skb(skb);
bec1f6f6 904 return -EINVAL;
0f149c9f
WB
905 }
906 if (sk->sk_no_check_tx) {
907 kfree_skb(skb);
a8c744a8 908 return -EINVAL;
0f149c9f 909 }
ff06342c 910 if (skb->ip_summed != CHECKSUM_PARTIAL || is_udplite ||
0f149c9f
WB
911 dst_xfrm(skb_dst(skb))) {
912 kfree_skb(skb);
bec1f6f6 913 return -EIO;
0f149c9f 914 }
bec1f6f6 915
4094871d
JH
916 if (datalen > cork->gso_size) {
917 skb_shinfo(skb)->gso_size = cork->gso_size;
918 skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4;
919 skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(datalen,
920 cork->gso_size);
921 }
a8c744a8 922 goto csum_partial;
bec1f6f6
WB
923 }
924
db8dac20 925 if (is_udplite) /* UDP-Lite */
f6b9664f 926 csum = udplite_csum(skb);
db8dac20 927
ab2fb7e3 928 else if (sk->sk_no_check_tx) { /* UDP csum off */
db8dac20
DM
929
930 skb->ip_summed = CHECKSUM_NONE;
931 goto send;
932
933 } else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
a8c744a8 934csum_partial:
db8dac20 935
79ab0531 936 udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
db8dac20
DM
937 goto send;
938
f6b9664f
HX
939 } else
940 csum = udp_csum(skb);
db8dac20
DM
941
942 /* add protocol-dependent pseudo-header */
79ab0531 943 uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
c482c568 944 sk->sk_protocol, csum);
db8dac20
DM
945 if (uh->check == 0)
946 uh->check = CSUM_MANGLED_0;
947
948send:
b5ec8eea 949 err = ip_send_skb(sock_net(sk), skb);
6ce9e7b5
ED
950 if (err) {
951 if (err == -ENOBUFS && !inet->recverr) {
6aef70a8
ED
952 UDP_INC_STATS(sock_net(sk),
953 UDP_MIB_SNDBUFERRORS, is_udplite);
6ce9e7b5
ED
954 err = 0;
955 }
956 } else
6aef70a8
ED
957 UDP_INC_STATS(sock_net(sk),
958 UDP_MIB_OUTDATAGRAMS, is_udplite);
f6b9664f
HX
959 return err;
960}
961
962/*
963 * Push out all pending data as one UDP datagram. Socket is locked.
964 */
8822b64a 965int udp_push_pending_frames(struct sock *sk)
f6b9664f
HX
966{
967 struct udp_sock *up = udp_sk(sk);
968 struct inet_sock *inet = inet_sk(sk);
b6f21b26 969 struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
f6b9664f
HX
970 struct sk_buff *skb;
971 int err = 0;
972
77968b78 973 skb = ip_finish_skb(sk, fl4);
f6b9664f
HX
974 if (!skb)
975 goto out;
976
bec1f6f6 977 err = udp_send_skb(skb, fl4, &inet->cork.base);
f6b9664f 978
db8dac20
DM
979out:
980 up->len = 0;
981 up->pending = 0;
db8dac20
DM
982 return err;
983}
8822b64a 984EXPORT_SYMBOL(udp_push_pending_frames);
db8dac20 985
2e8de857
WB
986static int __udp_cmsg_send(struct cmsghdr *cmsg, u16 *gso_size)
987{
988 switch (cmsg->cmsg_type) {
989 case UDP_SEGMENT:
990 if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u16)))
991 return -EINVAL;
992 *gso_size = *(__u16 *)CMSG_DATA(cmsg);
993 return 0;
994 default:
995 return -EINVAL;
996 }
997}
998
999int udp_cmsg_send(struct sock *sk, struct msghdr *msg, u16 *gso_size)
1000{
1001 struct cmsghdr *cmsg;
1002 bool need_ip = false;
1003 int err;
1004
1005 for_each_cmsghdr(cmsg, msg) {
1006 if (!CMSG_OK(msg, cmsg))
1007 return -EINVAL;
1008
1009 if (cmsg->cmsg_level != SOL_UDP) {
1010 need_ip = true;
1011 continue;
1012 }
1013
1014 err = __udp_cmsg_send(cmsg, gso_size);
1015 if (err)
1016 return err;
1017 }
1018
1019 return need_ip;
1020}
1021EXPORT_SYMBOL_GPL(udp_cmsg_send);
1022
1b784140 1023int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
db8dac20
DM
1024{
1025 struct inet_sock *inet = inet_sk(sk);
1026 struct udp_sock *up = udp_sk(sk);
1cedee13 1027 DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
e474995f 1028 struct flowi4 fl4_stack;
b6f21b26 1029 struct flowi4 *fl4;
db8dac20
DM
1030 int ulen = len;
1031 struct ipcm_cookie ipc;
1032 struct rtable *rt = NULL;
1033 int free = 0;
1034 int connected = 0;
1035 __be32 daddr, faddr, saddr;
1036 __be16 dport;
1037 u8 tos;
1038 int err, is_udplite = IS_UDPLITE(sk);
1039 int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
1040 int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
903ab86d 1041 struct sk_buff *skb;
f6d8bd05 1042 struct ip_options_data opt_copy;
db8dac20
DM
1043
1044 if (len > 0xFFFF)
1045 return -EMSGSIZE;
1046
1047 /*
1048 * Check the flags.
1049 */
1050
c482c568 1051 if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
db8dac20
DM
1052 return -EOPNOTSUPP;
1053
903ab86d
HX
1054 getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
1055
f5fca608 1056 fl4 = &inet->cork.fl.u.ip4;
db8dac20
DM
1057 if (up->pending) {
1058 /*
1059 * There are pending frames.
1060 * The socket lock must be held while it's corked.
1061 */
1062 lock_sock(sk);
1063 if (likely(up->pending)) {
1064 if (unlikely(up->pending != AF_INET)) {
1065 release_sock(sk);
1066 return -EINVAL;
1067 }
1068 goto do_append_data;
1069 }
1070 release_sock(sk);
1071 }
1072 ulen += sizeof(struct udphdr);
1073
1074 /*
1075 * Get and verify the address.
1076 */
1cedee13 1077 if (usin) {
db8dac20
DM
1078 if (msg->msg_namelen < sizeof(*usin))
1079 return -EINVAL;
1080 if (usin->sin_family != AF_INET) {
1081 if (usin->sin_family != AF_UNSPEC)
1082 return -EAFNOSUPPORT;
1083 }
1084
1085 daddr = usin->sin_addr.s_addr;
1086 dport = usin->sin_port;
1087 if (dport == 0)
1088 return -EINVAL;
1089 } else {
1090 if (sk->sk_state != TCP_ESTABLISHED)
1091 return -EDESTADDRREQ;
c720c7e8
ED
1092 daddr = inet->inet_daddr;
1093 dport = inet->inet_dport;
db8dac20
DM
1094 /* Open fast path for connected socket.
1095 Route will not be used, if at least one option is set.
1096 */
1097 connected = 1;
1098 }
db8dac20 1099
35178206 1100 ipcm_init_sk(&ipc, inet);
bec1f6f6 1101 ipc.gso_size = up->gso_size;
bf84a010 1102
db8dac20 1103 if (msg->msg_controllen) {
2e8de857
WB
1104 err = udp_cmsg_send(sk, msg, &ipc.gso_size);
1105 if (err > 0)
1106 err = ip_cmsg_send(sk, msg, &ipc,
1107 sk->sk_family == AF_INET6);
1108 if (unlikely(err < 0)) {
91948309 1109 kfree(ipc.opt);
db8dac20 1110 return err;
91948309 1111 }
db8dac20
DM
1112 if (ipc.opt)
1113 free = 1;
1114 connected = 0;
1115 }
f6d8bd05
ED
1116 if (!ipc.opt) {
1117 struct ip_options_rcu *inet_opt;
1118
1119 rcu_read_lock();
1120 inet_opt = rcu_dereference(inet->inet_opt);
1121 if (inet_opt) {
1122 memcpy(&opt_copy, inet_opt,
1123 sizeof(*inet_opt) + inet_opt->opt.optlen);
1124 ipc.opt = &opt_copy.opt;
1125 }
1126 rcu_read_unlock();
1127 }
db8dac20 1128
1cedee13
AI
1129 if (cgroup_bpf_enabled && !connected) {
1130 err = BPF_CGROUP_RUN_PROG_UDP4_SENDMSG_LOCK(sk,
1131 (struct sockaddr *)usin, &ipc.addr);
1132 if (err)
1133 goto out_free;
1134 if (usin) {
1135 if (usin->sin_port == 0) {
1136 /* BPF program set invalid port. Reject it. */
1137 err = -EINVAL;
1138 goto out_free;
1139 }
1140 daddr = usin->sin_addr.s_addr;
1141 dport = usin->sin_port;
1142 }
1143 }
1144
db8dac20
DM
1145 saddr = ipc.addr;
1146 ipc.addr = faddr = daddr;
1147
f6d8bd05 1148 if (ipc.opt && ipc.opt->opt.srr) {
1b97013b
AI
1149 if (!daddr) {
1150 err = -EINVAL;
1151 goto out_free;
1152 }
f6d8bd05 1153 faddr = ipc.opt->opt.faddr;
db8dac20
DM
1154 connected = 0;
1155 }
aa661581 1156 tos = get_rttos(&ipc, inet);
db8dac20
DM
1157 if (sock_flag(sk, SOCK_LOCALROUTE) ||
1158 (msg->msg_flags & MSG_DONTROUTE) ||
f6d8bd05 1159 (ipc.opt && ipc.opt->opt.is_strictroute)) {
db8dac20
DM
1160 tos |= RTO_ONLINK;
1161 connected = 0;
1162 }
1163
1164 if (ipv4_is_multicast(daddr)) {
854da991 1165 if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif))
db8dac20
DM
1166 ipc.oif = inet->mc_index;
1167 if (!saddr)
1168 saddr = inet->mc_addr;
1169 connected = 0;
9515a2e0 1170 } else if (!ipc.oif) {
76e21053 1171 ipc.oif = inet->uc_index;
9515a2e0
DA
1172 } else if (ipv4_is_lbcast(daddr) && inet->uc_index) {
1173 /* oif is set, packet is to local broadcast and
1174 * and uc_index is set. oif is most likely set
1175 * by sk_bound_dev_if. If uc_index != oif check if the
1176 * oif is an L3 master and uc_index is an L3 slave.
1177 * If so, we want to allow the send using the uc_index.
1178 */
1179 if (ipc.oif != inet->uc_index &&
1180 ipc.oif == l3mdev_master_ifindex_by_index(sock_net(sk),
1181 inet->uc_index)) {
1182 ipc.oif = inet->uc_index;
1183 }
1184 }
db8dac20
DM
1185
1186 if (connected)
c482c568 1187 rt = (struct rtable *)sk_dst_check(sk, 0);
db8dac20 1188
51456b29 1189 if (!rt) {
84a3aa00 1190 struct net *net = sock_net(sk);
9a24abfa 1191 __u8 flow_flags = inet_sk_flowi_flags(sk);
84a3aa00 1192
e474995f 1193 fl4 = &fl4_stack;
9a24abfa 1194
c6af0c22 1195 flowi4_init_output(fl4, ipc.oif, ipc.sockc.mark, tos,
c0951cbc 1196 RT_SCOPE_UNIVERSE, sk->sk_protocol,
9a24abfa 1197 flow_flags,
e2d118a1
LC
1198 faddr, saddr, dport, inet->inet_sport,
1199 sk->sk_uid);
c0951cbc 1200
e474995f
DM
1201 security_sk_classify_flow(sk, flowi4_to_flowi(fl4));
1202 rt = ip_route_output_flow(net, fl4, sk);
b23dd4fe
DM
1203 if (IS_ERR(rt)) {
1204 err = PTR_ERR(rt);
06dc94b1 1205 rt = NULL;
db8dac20 1206 if (err == -ENETUNREACH)
f1d8cba6 1207 IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
db8dac20
DM
1208 goto out;
1209 }
1210
1211 err = -EACCES;
1212 if ((rt->rt_flags & RTCF_BROADCAST) &&
1213 !sock_flag(sk, SOCK_BROADCAST))
1214 goto out;
1215 if (connected)
d8d1f30b 1216 sk_dst_set(sk, dst_clone(&rt->dst));
db8dac20
DM
1217 }
1218
1219 if (msg->msg_flags&MSG_CONFIRM)
1220 goto do_confirm;
1221back_from_confirm:
1222
e474995f 1223 saddr = fl4->saddr;
db8dac20 1224 if (!ipc.addr)
e474995f 1225 daddr = ipc.addr = fl4->daddr;
db8dac20 1226
903ab86d
HX
1227 /* Lockless fast path for the non-corking case. */
1228 if (!corkreq) {
1cd7884d
WB
1229 struct inet_cork cork;
1230
f69e6d13 1231 skb = ip_make_skb(sk, fl4, getfrag, msg, ulen,
903ab86d 1232 sizeof(struct udphdr), &ipc, &rt,
1cd7884d 1233 &cork, msg->msg_flags);
903ab86d 1234 err = PTR_ERR(skb);
50c3a487 1235 if (!IS_ERR_OR_NULL(skb))
bec1f6f6 1236 err = udp_send_skb(skb, fl4, &cork);
903ab86d
HX
1237 goto out;
1238 }
1239
db8dac20
DM
1240 lock_sock(sk);
1241 if (unlikely(up->pending)) {
1242 /* The socket is already corked while preparing it. */
1243 /* ... which is an evident application bug. --ANK */
1244 release_sock(sk);
1245
197df02c 1246 net_dbg_ratelimited("socket already corked\n");
db8dac20
DM
1247 err = -EINVAL;
1248 goto out;
1249 }
1250 /*
1251 * Now cork the socket to pend data.
1252 */
b6f21b26
DM
1253 fl4 = &inet->cork.fl.u.ip4;
1254 fl4->daddr = daddr;
1255 fl4->saddr = saddr;
9cce96df
DM
1256 fl4->fl4_dport = dport;
1257 fl4->fl4_sport = inet->inet_sport;
db8dac20
DM
1258 up->pending = AF_INET;
1259
1260do_append_data:
1261 up->len += ulen;
f69e6d13 1262 err = ip_append_data(sk, fl4, getfrag, msg, ulen,
f5fca608
DM
1263 sizeof(struct udphdr), &ipc, &rt,
1264 corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
db8dac20
DM
1265 if (err)
1266 udp_flush_pending_frames(sk);
1267 else if (!corkreq)
1268 err = udp_push_pending_frames(sk);
1269 else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
1270 up->pending = 0;
1271 release_sock(sk);
1272
1273out:
1274 ip_rt_put(rt);
1b97013b 1275out_free:
db8dac20
DM
1276 if (free)
1277 kfree(ipc.opt);
1278 if (!err)
1279 return len;
1280 /*
1281 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting
1282 * ENOBUFS might not be good (it's not tunable per se), but otherwise
1283 * we don't have a good statistic (IpOutDiscards but it can be too many
1284 * things). We could add another new stat but at least for now that
1285 * seems like overkill.
1286 */
1287 if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
6aef70a8
ED
1288 UDP_INC_STATS(sock_net(sk),
1289 UDP_MIB_SNDBUFERRORS, is_udplite);
db8dac20
DM
1290 }
1291 return err;
1292
1293do_confirm:
0dec879f
JA
1294 if (msg->msg_flags & MSG_PROBE)
1295 dst_confirm_neigh(&rt->dst, &fl4->daddr);
db8dac20
DM
1296 if (!(msg->msg_flags&MSG_PROBE) || len)
1297 goto back_from_confirm;
1298 err = 0;
1299 goto out;
1300}
c482c568 1301EXPORT_SYMBOL(udp_sendmsg);
db8dac20
DM
1302
1303int udp_sendpage(struct sock *sk, struct page *page, int offset,
1304 size_t size, int flags)
1305{
f5fca608 1306 struct inet_sock *inet = inet_sk(sk);
db8dac20
DM
1307 struct udp_sock *up = udp_sk(sk);
1308 int ret;
1309
d3f7d56a
SL
1310 if (flags & MSG_SENDPAGE_NOTLAST)
1311 flags |= MSG_MORE;
1312
db8dac20
DM
1313 if (!up->pending) {
1314 struct msghdr msg = { .msg_flags = flags|MSG_MORE };
1315
1316 /* Call udp_sendmsg to specify destination address which
1317 * sendpage interface can't pass.
1318 * This will succeed only when the socket is connected.
1319 */
1b784140 1320 ret = udp_sendmsg(sk, &msg, 0);
db8dac20
DM
1321 if (ret < 0)
1322 return ret;
1323 }
1324
1325 lock_sock(sk);
1326
1327 if (unlikely(!up->pending)) {
1328 release_sock(sk);
1329
197df02c 1330 net_dbg_ratelimited("cork failed\n");
db8dac20
DM
1331 return -EINVAL;
1332 }
1333
f5fca608
DM
1334 ret = ip_append_page(sk, &inet->cork.fl.u.ip4,
1335 page, offset, size, flags);
db8dac20
DM
1336 if (ret == -EOPNOTSUPP) {
1337 release_sock(sk);
1338 return sock_no_sendpage(sk->sk_socket, page, offset,
1339 size, flags);
1340 }
1341 if (ret < 0) {
1342 udp_flush_pending_frames(sk);
1343 goto out;
1344 }
1345
1346 up->len += size;
1347 if (!(up->corkflag || (flags&MSG_MORE)))
1348 ret = udp_push_pending_frames(sk);
1349 if (!ret)
1350 ret = size;
1351out:
1352 release_sock(sk);
1353 return ret;
1354}
1355
dce4551c
PA
1356#define UDP_SKB_IS_STATELESS 0x80000000
1357
677bf08c
FW
1358/* all head states (dst, sk, nf conntrack) except skb extensions are
1359 * cleared by udp_rcv().
1360 *
1361 * We need to preserve secpath, if present, to eventually process
1362 * IP_CMSG_PASSSEC at recvmsg() time.
1363 *
1364 * Other extensions can be cleared.
1365 */
1366static bool udp_try_make_stateless(struct sk_buff *skb)
1367{
1368 if (!skb_has_extensions(skb))
1369 return true;
1370
1371 if (!secpath_exists(skb)) {
1372 skb_ext_reset(skb);
1373 return true;
1374 }
1375
1376 return false;
1377}
1378
b65ac446
PA
1379static void udp_set_dev_scratch(struct sk_buff *skb)
1380{
dce4551c 1381 struct udp_dev_scratch *scratch = udp_skb_scratch(skb);
b65ac446
PA
1382
1383 BUILD_BUG_ON(sizeof(struct udp_dev_scratch) > sizeof(long));
dce4551c
PA
1384 scratch->_tsize_state = skb->truesize;
1385#if BITS_PER_LONG == 64
b65ac446
PA
1386 scratch->len = skb->len;
1387 scratch->csum_unnecessary = !!skb_csum_unnecessary(skb);
1388 scratch->is_linear = !skb_is_nonlinear(skb);
dce4551c 1389#endif
677bf08c 1390 if (udp_try_make_stateless(skb))
dce4551c 1391 scratch->_tsize_state |= UDP_SKB_IS_STATELESS;
b65ac446
PA
1392}
1393
a793183c
ED
1394static void udp_skb_csum_unnecessary_set(struct sk_buff *skb)
1395{
1396 /* We come here after udp_lib_checksum_complete() returned 0.
1397 * This means that __skb_checksum_complete() might have
1398 * set skb->csum_valid to 1.
1399 * On 64bit platforms, we can set csum_unnecessary
1400 * to true, but only if the skb is not shared.
1401 */
1402#if BITS_PER_LONG == 64
1403 if (!skb_shared(skb))
1404 udp_skb_scratch(skb)->csum_unnecessary = true;
1405#endif
1406}
1407
b65ac446
PA
1408static int udp_skb_truesize(struct sk_buff *skb)
1409{
dce4551c 1410 return udp_skb_scratch(skb)->_tsize_state & ~UDP_SKB_IS_STATELESS;
b65ac446
PA
1411}
1412
dce4551c 1413static bool udp_skb_has_head_state(struct sk_buff *skb)
b65ac446 1414{
dce4551c 1415 return !(udp_skb_scratch(skb)->_tsize_state & UDP_SKB_IS_STATELESS);
b65ac446 1416}
b65ac446 1417
7c13f97f 1418/* fully reclaim rmem/fwd memory allocated for skb */
6dfb4367
PA
1419static void udp_rmem_release(struct sock *sk, int size, int partial,
1420 bool rx_queue_lock_held)
f970bd9e 1421{
6b229cf7 1422 struct udp_sock *up = udp_sk(sk);
2276f58a 1423 struct sk_buff_head *sk_queue;
f970bd9e
PA
1424 int amt;
1425
6b229cf7
ED
1426 if (likely(partial)) {
1427 up->forward_deficit += size;
1428 size = up->forward_deficit;
d39ca259
PA
1429 if (size < (sk->sk_rcvbuf >> 2) &&
1430 !skb_queue_empty(&up->reader_queue))
6b229cf7
ED
1431 return;
1432 } else {
1433 size += up->forward_deficit;
1434 }
1435 up->forward_deficit = 0;
1436
6dfb4367
PA
1437 /* acquire the sk_receive_queue for fwd allocated memory scheduling,
1438 * if the called don't held it already
1439 */
2276f58a 1440 sk_queue = &sk->sk_receive_queue;
6dfb4367
PA
1441 if (!rx_queue_lock_held)
1442 spin_lock(&sk_queue->lock);
1443
2276f58a 1444
f970bd9e
PA
1445 sk->sk_forward_alloc += size;
1446 amt = (sk->sk_forward_alloc - partial) & ~(SK_MEM_QUANTUM - 1);
1447 sk->sk_forward_alloc -= amt;
f970bd9e
PA
1448
1449 if (amt)
1450 __sk_mem_reduce_allocated(sk, amt >> SK_MEM_QUANTUM_SHIFT);
02ab0d13
ED
1451
1452 atomic_sub(size, &sk->sk_rmem_alloc);
2276f58a
PA
1453
1454 /* this can save us from acquiring the rx queue lock on next receive */
1455 skb_queue_splice_tail_init(sk_queue, &up->reader_queue);
1456
6dfb4367
PA
1457 if (!rx_queue_lock_held)
1458 spin_unlock(&sk_queue->lock);
f970bd9e
PA
1459}
1460
2276f58a 1461/* Note: called with reader_queue.lock held.
c84d9490
ED
1462 * Instead of using skb->truesize here, find a copy of it in skb->dev_scratch
1463 * This avoids a cache line miss while receive_queue lock is held.
1464 * Look at __udp_enqueue_schedule_skb() to find where this copy is done.
1465 */
7c13f97f 1466void udp_skb_destructor(struct sock *sk, struct sk_buff *skb)
f970bd9e 1467{
b65ac446
PA
1468 prefetch(&skb->data);
1469 udp_rmem_release(sk, udp_skb_truesize(skb), 1, false);
f970bd9e 1470}
7c13f97f 1471EXPORT_SYMBOL(udp_skb_destructor);
f970bd9e 1472
6dfb4367 1473/* as above, but the caller held the rx queue lock, too */
64f5102d 1474static void udp_skb_dtor_locked(struct sock *sk, struct sk_buff *skb)
6dfb4367 1475{
b65ac446
PA
1476 prefetch(&skb->data);
1477 udp_rmem_release(sk, udp_skb_truesize(skb), 1, true);
6dfb4367
PA
1478}
1479
4b272750
ED
1480/* Idea of busylocks is to let producers grab an extra spinlock
1481 * to relieve pressure on the receive_queue spinlock shared by consumer.
1482 * Under flood, this means that only one producer can be in line
1483 * trying to acquire the receive_queue spinlock.
1484 * These busylock can be allocated on a per cpu manner, instead of a
1485 * per socket one (that would consume a cache line per socket)
1486 */
1487static int udp_busylocks_log __read_mostly;
1488static spinlock_t *udp_busylocks __read_mostly;
1489
1490static spinlock_t *busylock_acquire(void *ptr)
1491{
1492 spinlock_t *busy;
1493
1494 busy = udp_busylocks + hash_ptr(ptr, udp_busylocks_log);
1495 spin_lock(busy);
1496 return busy;
1497}
1498
1499static void busylock_release(spinlock_t *busy)
1500{
1501 if (busy)
1502 spin_unlock(busy);
1503}
1504
f970bd9e
PA
1505int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb)
1506{
1507 struct sk_buff_head *list = &sk->sk_receive_queue;
1508 int rmem, delta, amt, err = -ENOMEM;
4b272750 1509 spinlock_t *busy = NULL;
c8c8b127 1510 int size;
f970bd9e
PA
1511
1512 /* try to avoid the costly atomic add/sub pair when the receive
1513 * queue is full; always allow at least a packet
1514 */
1515 rmem = atomic_read(&sk->sk_rmem_alloc);
363dc73a 1516 if (rmem > sk->sk_rcvbuf)
f970bd9e
PA
1517 goto drop;
1518
c8c8b127
ED
1519 /* Under mem pressure, it might be helpful to help udp_recvmsg()
1520 * having linear skbs :
1521 * - Reduce memory overhead and thus increase receive queue capacity
1522 * - Less cache line misses at copyout() time
1523 * - Less work at consume_skb() (less alien page frag freeing)
1524 */
4b272750 1525 if (rmem > (sk->sk_rcvbuf >> 1)) {
c8c8b127 1526 skb_condense(skb);
4b272750
ED
1527
1528 busy = busylock_acquire(sk);
1529 }
c8c8b127 1530 size = skb->truesize;
b65ac446 1531 udp_set_dev_scratch(skb);
c8c8b127 1532
f970bd9e
PA
1533 /* we drop only if the receive buf is full and the receive
1534 * queue contains some other skb
1535 */
1536 rmem = atomic_add_return(size, &sk->sk_rmem_alloc);
feed8a4f 1537 if (rmem > (size + (unsigned int)sk->sk_rcvbuf))
f970bd9e
PA
1538 goto uncharge_drop;
1539
1540 spin_lock(&list->lock);
1541 if (size >= sk->sk_forward_alloc) {
1542 amt = sk_mem_pages(size);
1543 delta = amt << SK_MEM_QUANTUM_SHIFT;
1544 if (!__sk_mem_raise_allocated(sk, delta, amt, SK_MEM_RECV)) {
1545 err = -ENOBUFS;
1546 spin_unlock(&list->lock);
1547 goto uncharge_drop;
1548 }
1549
1550 sk->sk_forward_alloc += delta;
1551 }
1552
1553 sk->sk_forward_alloc -= size;
1554
7c13f97f
PA
1555 /* no need to setup a destructor, we will explicitly release the
1556 * forward allocated memory on dequeue
1557 */
f970bd9e
PA
1558 sock_skb_set_dropcount(sk, skb);
1559
1560 __skb_queue_tail(list, skb);
1561 spin_unlock(&list->lock);
1562
1563 if (!sock_flag(sk, SOCK_DEAD))
1564 sk->sk_data_ready(sk);
1565
4b272750 1566 busylock_release(busy);
f970bd9e
PA
1567 return 0;
1568
1569uncharge_drop:
1570 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
1571
1572drop:
1573 atomic_inc(&sk->sk_drops);
4b272750 1574 busylock_release(busy);
f970bd9e
PA
1575 return err;
1576}
1577EXPORT_SYMBOL_GPL(__udp_enqueue_schedule_skb);
1578
c915fe13 1579void udp_destruct_sock(struct sock *sk)
f970bd9e
PA
1580{
1581 /* reclaim completely the forward allocated memory */
2276f58a 1582 struct udp_sock *up = udp_sk(sk);
7c13f97f
PA
1583 unsigned int total = 0;
1584 struct sk_buff *skb;
1585
2276f58a
PA
1586 skb_queue_splice_tail_init(&sk->sk_receive_queue, &up->reader_queue);
1587 while ((skb = __skb_dequeue(&up->reader_queue)) != NULL) {
7c13f97f
PA
1588 total += skb->truesize;
1589 kfree_skb(skb);
1590 }
6dfb4367 1591 udp_rmem_release(sk, total, 0, true);
7c13f97f 1592
f970bd9e
PA
1593 inet_sock_destruct(sk);
1594}
c915fe13 1595EXPORT_SYMBOL_GPL(udp_destruct_sock);
f970bd9e
PA
1596
1597int udp_init_sock(struct sock *sk)
1598{
2276f58a 1599 skb_queue_head_init(&udp_sk(sk)->reader_queue);
f970bd9e
PA
1600 sk->sk_destruct = udp_destruct_sock;
1601 return 0;
1602}
1603EXPORT_SYMBOL_GPL(udp_init_sock);
1604
1605void skb_consume_udp(struct sock *sk, struct sk_buff *skb, int len)
1606{
1607 if (unlikely(READ_ONCE(sk->sk_peek_off) >= 0)) {
1608 bool slow = lock_sock_fast(sk);
1609
1610 sk_peek_offset_bwd(sk, len);
1611 unlock_sock_fast(sk, slow);
1612 }
0a463c78 1613
ca2c1418
PA
1614 if (!skb_unref(skb))
1615 return;
1616
dce4551c
PA
1617 /* In the more common cases we cleared the head states previously,
1618 * see __udp_queue_rcv_skb().
0ddf3fb2 1619 */
dce4551c 1620 if (unlikely(udp_skb_has_head_state(skb)))
0ddf3fb2 1621 skb_release_head_state(skb);
ca2c1418 1622 __consume_stateless_skb(skb);
f970bd9e
PA
1623}
1624EXPORT_SYMBOL_GPL(skb_consume_udp);
1625
2276f58a
PA
1626static struct sk_buff *__first_packet_length(struct sock *sk,
1627 struct sk_buff_head *rcvq,
1628 int *total)
1629{
1630 struct sk_buff *skb;
1631
9bd780f5
PA
1632 while ((skb = skb_peek(rcvq)) != NULL) {
1633 if (udp_lib_checksum_complete(skb)) {
1634 __UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS,
1635 IS_UDPLITE(sk));
1636 __UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS,
1637 IS_UDPLITE(sk));
1638 atomic_inc(&sk->sk_drops);
1639 __skb_unlink(skb, rcvq);
1640 *total += skb->truesize;
1641 kfree_skb(skb);
1642 } else {
a793183c 1643 udp_skb_csum_unnecessary_set(skb);
9bd780f5
PA
1644 break;
1645 }
2276f58a
PA
1646 }
1647 return skb;
1648}
1649
85584672
ED
1650/**
1651 * first_packet_length - return length of first packet in receive queue
1652 * @sk: socket
1653 *
1654 * Drops all bad checksum frames, until a valid one is found.
e83c6744 1655 * Returns the length of found skb, or -1 if none is found.
85584672 1656 */
e83c6744 1657static int first_packet_length(struct sock *sk)
85584672 1658{
2276f58a
PA
1659 struct sk_buff_head *rcvq = &udp_sk(sk)->reader_queue;
1660 struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
85584672 1661 struct sk_buff *skb;
7c13f97f 1662 int total = 0;
e83c6744 1663 int res;
85584672 1664
85584672 1665 spin_lock_bh(&rcvq->lock);
2276f58a 1666 skb = __first_packet_length(sk, rcvq, &total);
137a0dbe 1667 if (!skb && !skb_queue_empty_lockless(sk_queue)) {
2276f58a
PA
1668 spin_lock(&sk_queue->lock);
1669 skb_queue_splice_tail_init(sk_queue, rcvq);
1670 spin_unlock(&sk_queue->lock);
1671
1672 skb = __first_packet_length(sk, rcvq, &total);
85584672 1673 }
e83c6744 1674 res = skb ? skb->len : -1;
7c13f97f 1675 if (total)
6dfb4367 1676 udp_rmem_release(sk, total, 1, false);
85584672 1677 spin_unlock_bh(&rcvq->lock);
85584672
ED
1678 return res;
1679}
1680
1da177e4
LT
1681/*
1682 * IOCTL requests applicable to the UDP protocol
1683 */
e905a9ed 1684
1da177e4
LT
1685int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
1686{
6516c655
SH
1687 switch (cmd) {
1688 case SIOCOUTQ:
1da177e4 1689 {
31e6d363
ED
1690 int amount = sk_wmem_alloc_get(sk);
1691
6516c655
SH
1692 return put_user(amount, (int __user *)arg);
1693 }
1da177e4 1694
6516c655
SH
1695 case SIOCINQ:
1696 {
e83c6744 1697 int amount = max_t(int, 0, first_packet_length(sk));
6516c655 1698
6516c655
SH
1699 return put_user(amount, (int __user *)arg);
1700 }
1da177e4 1701
6516c655
SH
1702 default:
1703 return -ENOIOCTLCMD;
1da177e4 1704 }
6516c655
SH
1705
1706 return 0;
1da177e4 1707}
c482c568 1708EXPORT_SYMBOL(udp_ioctl);
1da177e4 1709
2276f58a 1710struct sk_buff *__skb_recv_udp(struct sock *sk, unsigned int flags,
fd69c399 1711 int noblock, int *off, int *err)
2276f58a
PA
1712{
1713 struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
1714 struct sk_buff_head *queue;
1715 struct sk_buff *last;
1716 long timeo;
1717 int error;
1718
1719 queue = &udp_sk(sk)->reader_queue;
1720 flags |= noblock ? MSG_DONTWAIT : 0;
1721 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1722 do {
1723 struct sk_buff *skb;
1724
1725 error = sock_error(sk);
1726 if (error)
1727 break;
1728
1729 error = -EAGAIN;
2276f58a 1730 do {
2276f58a 1731 spin_lock_bh(&queue->lock);
e427cad6
PA
1732 skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1733 err, &last);
2276f58a 1734 if (skb) {
e427cad6
PA
1735 if (!(flags & MSG_PEEK))
1736 udp_skb_destructor(sk, skb);
2276f58a 1737 spin_unlock_bh(&queue->lock);
2276f58a
PA
1738 return skb;
1739 }
1740
137a0dbe 1741 if (skb_queue_empty_lockless(sk_queue)) {
2276f58a
PA
1742 spin_unlock_bh(&queue->lock);
1743 goto busy_check;
1744 }
1745
6dfb4367
PA
1746 /* refill the reader queue and walk it again
1747 * keep both queues locked to avoid re-acquiring
1748 * the sk_receive_queue lock if fwd memory scheduling
1749 * is needed.
1750 */
2276f58a
PA
1751 spin_lock(&sk_queue->lock);
1752 skb_queue_splice_tail_init(sk_queue, queue);
2276f58a 1753
e427cad6
PA
1754 skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1755 err, &last);
1756 if (skb && !(flags & MSG_PEEK))
1757 udp_skb_dtor_locked(sk, skb);
6dfb4367 1758 spin_unlock(&sk_queue->lock);
2276f58a 1759 spin_unlock_bh(&queue->lock);
de321ed3 1760 if (skb)
2276f58a 1761 return skb;
2276f58a
PA
1762
1763busy_check:
1764 if (!sk_can_busy_loop(sk))
1765 break;
1766
1767 sk_busy_loop(sk, flags & MSG_DONTWAIT);
137a0dbe 1768 } while (!skb_queue_empty_lockless(sk_queue));
2276f58a
PA
1769
1770 /* sk_queue is empty, reader_queue may contain peeked packets */
1771 } while (timeo &&
b50b0580
SD
1772 !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,
1773 &error, &timeo,
2276f58a
PA
1774 (struct sk_buff *)sk_queue));
1775
1776 *err = error;
1777 return NULL;
1778}
7e823644 1779EXPORT_SYMBOL(__skb_recv_udp);
2276f58a 1780
db8dac20
DM
1781/*
1782 * This should be easy, if there is something there we
1783 * return it, otherwise we block.
1784 */
1785
1b784140
YX
1786int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock,
1787 int flags, int *addr_len)
db8dac20
DM
1788{
1789 struct inet_sock *inet = inet_sk(sk);
342dfc30 1790 DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
db8dac20 1791 struct sk_buff *skb;
59c2cdae 1792 unsigned int ulen, copied;
fd69c399 1793 int off, err, peeking = flags & MSG_PEEK;
db8dac20 1794 int is_udplite = IS_UDPLITE(sk);
197c949e 1795 bool checksum_valid = false;
db8dac20 1796
db8dac20 1797 if (flags & MSG_ERRQUEUE)
85fbaa75 1798 return ip_recv_error(sk, msg, len, addr_len);
db8dac20
DM
1799
1800try_again:
a0917e0b 1801 off = sk_peek_offset(sk, flags);
fd69c399 1802 skb = __skb_recv_udp(sk, flags, noblock, &off, &err);
db8dac20 1803 if (!skb)
627d2d6b 1804 return err;
db8dac20 1805
b65ac446 1806 ulen = udp_skb_len(skb);
59c2cdae 1807 copied = len;
627d2d6b 1808 if (copied > ulen - off)
1809 copied = ulen - off;
59c2cdae 1810 else if (copied < ulen)
db8dac20
DM
1811 msg->msg_flags |= MSG_TRUNC;
1812
1813 /*
1814 * If checksum is needed at all, try to do it while copying the
1815 * data. If the data is truncated, or if we only want a partial
1816 * coverage checksum (UDP-Lite), do it before the copy.
1817 */
1818
d21dbdfe
ED
1819 if (copied < ulen || peeking ||
1820 (is_udplite && UDP_SKB_CB(skb)->partial_cov)) {
b65ac446
PA
1821 checksum_valid = udp_skb_csum_unnecessary(skb) ||
1822 !__udp_lib_checksum_complete(skb);
197c949e 1823 if (!checksum_valid)
db8dac20
DM
1824 goto csum_copy_err;
1825 }
1826
b65ac446
PA
1827 if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
1828 if (udp_skb_is_linear(skb))
1829 err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
1830 else
1831 err = skb_copy_datagram_msg(skb, off, msg, copied);
1832 } else {
627d2d6b 1833 err = skb_copy_and_csum_datagram_msg(skb, off, msg);
db8dac20
DM
1834
1835 if (err == -EINVAL)
1836 goto csum_copy_err;
1837 }
1838
22911fc5 1839 if (unlikely(err)) {
fd69c399 1840 if (!peeking) {
979402b1 1841 atomic_inc(&sk->sk_drops);
6aef70a8
ED
1842 UDP_INC_STATS(sock_net(sk),
1843 UDP_MIB_INERRORS, is_udplite);
979402b1 1844 }
850cbadd 1845 kfree_skb(skb);
627d2d6b 1846 return err;
22911fc5 1847 }
db8dac20 1848
fd69c399 1849 if (!peeking)
6aef70a8
ED
1850 UDP_INC_STATS(sock_net(sk),
1851 UDP_MIB_INDATAGRAMS, is_udplite);
db8dac20 1852
3b885787 1853 sock_recv_ts_and_drops(msg, sk, skb);
db8dac20
DM
1854
1855 /* Copy the address. */
c482c568 1856 if (sin) {
db8dac20
DM
1857 sin->sin_family = AF_INET;
1858 sin->sin_port = udp_hdr(skb)->source;
1859 sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
1860 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
bceaa902 1861 *addr_len = sizeof(*sin);
983695fa
DB
1862
1863 if (cgroup_bpf_enabled)
1864 BPF_CGROUP_RUN_PROG_UDP4_RECVMSG_LOCK(sk,
1865 (struct sockaddr *)sin);
db8dac20 1866 }
bcd1665e
PA
1867
1868 if (udp_sk(sk)->gro_enabled)
1869 udp_cmsg_recv(msg, sk, skb);
1870
db8dac20 1871 if (inet->cmsg_flags)
ad959036 1872 ip_cmsg_recv_offset(msg, sk, skb, sizeof(struct udphdr), off);
db8dac20 1873
59c2cdae 1874 err = copied;
db8dac20
DM
1875 if (flags & MSG_TRUNC)
1876 err = ulen;
1877
850cbadd 1878 skb_consume_udp(sk, skb, peeking ? -err : err);
db8dac20
DM
1879 return err;
1880
1881csum_copy_err:
2276f58a
PA
1882 if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags,
1883 udp_skb_destructor)) {
6aef70a8
ED
1884 UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
1885 UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
6a5dc9e5 1886 }
850cbadd 1887 kfree_skb(skb);
db8dac20 1888
beb39db5
ED
1889 /* starting over for a new packet, but check if we need to yield */
1890 cond_resched();
9cfaa8de 1891 msg->msg_flags &= ~MSG_TRUNC;
db8dac20
DM
1892 goto try_again;
1893}
1894
d74bad4e
AI
1895int udp_pre_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
1896{
1897 /* This check is replicated from __ip4_datagram_connect() and
1898 * intended to prevent BPF program called below from accessing bytes
1899 * that are out of the bound specified by user in addr_len.
1900 */
1901 if (addr_len < sizeof(struct sockaddr_in))
1902 return -EINVAL;
1903
1904 return BPF_CGROUP_RUN_PROG_INET4_CONNECT_LOCK(sk, uaddr);
1905}
1906EXPORT_SYMBOL(udp_pre_connect);
1907
286c72de 1908int __udp_disconnect(struct sock *sk, int flags)
1da177e4
LT
1909{
1910 struct inet_sock *inet = inet_sk(sk);
1911 /*
1912 * 1003.1g - break association.
1913 */
e905a9ed 1914
1da177e4 1915 sk->sk_state = TCP_CLOSE;
c720c7e8
ED
1916 inet->inet_daddr = 0;
1917 inet->inet_dport = 0;
bdeab991 1918 sock_rps_reset_rxhash(sk);
1da177e4 1919 sk->sk_bound_dev_if = 0;
303d0403 1920 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) {
1da177e4 1921 inet_reset_saddr(sk);
303d0403
WB
1922 if (sk->sk_prot->rehash &&
1923 (sk->sk_userlocks & SOCK_BINDPORT_LOCK))
1924 sk->sk_prot->rehash(sk);
1925 }
1da177e4
LT
1926
1927 if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
1928 sk->sk_prot->unhash(sk);
c720c7e8 1929 inet->inet_sport = 0;
1da177e4
LT
1930 }
1931 sk_dst_reset(sk);
1932 return 0;
1933}
286c72de
ED
1934EXPORT_SYMBOL(__udp_disconnect);
1935
1936int udp_disconnect(struct sock *sk, int flags)
1937{
1938 lock_sock(sk);
1939 __udp_disconnect(sk, flags);
1940 release_sock(sk);
1941 return 0;
1942}
c482c568 1943EXPORT_SYMBOL(udp_disconnect);
1da177e4 1944
645ca708
ED
1945void udp_lib_unhash(struct sock *sk)
1946{
723b4610
ED
1947 if (sk_hashed(sk)) {
1948 struct udp_table *udptable = sk->sk_prot->h.udp_table;
512615b6
ED
1949 struct udp_hslot *hslot, *hslot2;
1950
1951 hslot = udp_hashslot(udptable, sock_net(sk),
1952 udp_sk(sk)->udp_port_hash);
1953 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
645ca708 1954
723b4610 1955 spin_lock_bh(&hslot->lock);
e32ea7e7
CG
1956 if (rcu_access_pointer(sk->sk_reuseport_cb))
1957 reuseport_detach_sock(sk);
ca065d0c 1958 if (sk_del_node_init_rcu(sk)) {
fdcc8aa9 1959 hslot->count--;
c720c7e8 1960 inet_sk(sk)->inet_num = 0;
723b4610 1961 sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
512615b6
ED
1962
1963 spin_lock(&hslot2->lock);
ca065d0c 1964 hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
512615b6
ED
1965 hslot2->count--;
1966 spin_unlock(&hslot2->lock);
723b4610
ED
1967 }
1968 spin_unlock_bh(&hslot->lock);
645ca708 1969 }
645ca708
ED
1970}
1971EXPORT_SYMBOL(udp_lib_unhash);
1972
719f8358
ED
1973/*
1974 * inet_rcv_saddr was changed, we must rehash secondary hash
1975 */
1976void udp_lib_rehash(struct sock *sk, u16 newhash)
1977{
1978 if (sk_hashed(sk)) {
1979 struct udp_table *udptable = sk->sk_prot->h.udp_table;
1980 struct udp_hslot *hslot, *hslot2, *nhslot2;
1981
1982 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
1983 nhslot2 = udp_hashslot2(udptable, newhash);
1984 udp_sk(sk)->udp_portaddr_hash = newhash;
e32ea7e7
CG
1985
1986 if (hslot2 != nhslot2 ||
1987 rcu_access_pointer(sk->sk_reuseport_cb)) {
719f8358
ED
1988 hslot = udp_hashslot(udptable, sock_net(sk),
1989 udp_sk(sk)->udp_port_hash);
1990 /* we must lock primary chain too */
1991 spin_lock_bh(&hslot->lock);
e32ea7e7
CG
1992 if (rcu_access_pointer(sk->sk_reuseport_cb))
1993 reuseport_detach_sock(sk);
1994
1995 if (hslot2 != nhslot2) {
1996 spin_lock(&hslot2->lock);
ca065d0c 1997 hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
e32ea7e7
CG
1998 hslot2->count--;
1999 spin_unlock(&hslot2->lock);
2000
2001 spin_lock(&nhslot2->lock);
ca065d0c 2002 hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
e32ea7e7
CG
2003 &nhslot2->head);
2004 nhslot2->count++;
2005 spin_unlock(&nhslot2->lock);
2006 }
719f8358
ED
2007
2008 spin_unlock_bh(&hslot->lock);
2009 }
2010 }
2011}
2012EXPORT_SYMBOL(udp_lib_rehash);
2013
8f6b5392 2014void udp_v4_rehash(struct sock *sk)
719f8358 2015{
f0b1e64c 2016 u16 new_hash = ipv4_portaddr_hash(sock_net(sk),
719f8358
ED
2017 inet_sk(sk)->inet_rcv_saddr,
2018 inet_sk(sk)->inet_num);
2019 udp_lib_rehash(sk, new_hash);
2020}
2021
a3f96c47 2022static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
93821778 2023{
fec5e652 2024 int rc;
766e9037 2025
005ec974 2026 if (inet_sk(sk)->inet_daddr) {
bdeab991 2027 sock_rps_save_rxhash(sk, skb);
005ec974 2028 sk_mark_napi_id(sk, skb);
2c8c56e1 2029 sk_incoming_cpu_update(sk);
e68b6e50
ED
2030 } else {
2031 sk_mark_napi_id_once(sk, skb);
005ec974 2032 }
fec5e652 2033
850cbadd 2034 rc = __udp_enqueue_schedule_skb(sk, skb);
766e9037
ED
2035 if (rc < 0) {
2036 int is_udplite = IS_UDPLITE(sk);
93821778 2037
93821778 2038 /* Note that an ENOMEM error is charged twice */
766e9037 2039 if (rc == -ENOMEM)
e61da9e2 2040 UDP_INC_STATS(sock_net(sk), UDP_MIB_RCVBUFERRORS,
02c22347 2041 is_udplite);
e61da9e2 2042 UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
766e9037 2043 kfree_skb(skb);
296f7ea7 2044 trace_udp_fail_queue_rcv_skb(rc, sk);
766e9037 2045 return -1;
93821778
HX
2046 }
2047
2048 return 0;
93821778
HX
2049}
2050
db8dac20
DM
2051/* returns:
2052 * -1: error
2053 * 0: success
2054 * >0: "udp encap" protocol resubmission
2055 *
2056 * Note that in the success and error cases, the skb is assumed to
2057 * have either been requeued or freed.
2058 */
cf329aa4 2059static int udp_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
db8dac20
DM
2060{
2061 struct udp_sock *up = udp_sk(sk);
db8dac20
DM
2062 int is_udplite = IS_UDPLITE(sk);
2063
2064 /*
2065 * Charge it to the socket, dropping if the queue is full.
2066 */
2067 if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
2068 goto drop;
895b5c9f 2069 nf_reset_ct(skb);
db8dac20 2070
88ab3108 2071 if (static_branch_unlikely(&udp_encap_needed_key) && up->encap_type) {
0ad92ad0
ED
2072 int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
2073
db8dac20
DM
2074 /*
2075 * This is an encapsulation socket so pass the skb to
2076 * the socket's udp_encap_rcv() hook. Otherwise, just
2077 * fall through and pass this up the UDP socket.
2078 * up->encap_rcv() returns the following value:
2079 * =0 if skb was successfully passed to the encap
2080 * handler or was discarded by it.
2081 * >0 if skb should be passed on to UDP.
2082 * <0 if skb should be resubmitted as proto -N
2083 */
2084
2085 /* if we're overly short, let UDP handle it */
6aa7de05 2086 encap_rcv = READ_ONCE(up->encap_rcv);
e5aed006 2087 if (encap_rcv) {
db8dac20
DM
2088 int ret;
2089
0a80966b
TH
2090 /* Verify checksum before giving to encap */
2091 if (udp_lib_checksum_complete(skb))
2092 goto csum_error;
2093
0ad92ad0 2094 ret = encap_rcv(sk, skb);
db8dac20 2095 if (ret <= 0) {
02c22347
ED
2096 __UDP_INC_STATS(sock_net(sk),
2097 UDP_MIB_INDATAGRAMS,
2098 is_udplite);
db8dac20
DM
2099 return -ret;
2100 }
2101 }
2102
2103 /* FALLTHROUGH -- it's a UDP Packet */
2104 }
2105
2106 /*
2107 * UDP-Lite specific tests, ignored on UDP sockets
2108 */
2109 if ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) {
2110
2111 /*
2112 * MIB statistics other than incrementing the error count are
2113 * disabled for the following two types of errors: these depend
2114 * on the application settings, not on the functioning of the
2115 * protocol stack as such.
2116 *
2117 * RFC 3828 here recommends (sec 3.3): "There should also be a
2118 * way ... to ... at least let the receiving application block
2119 * delivery of packets with coverage values less than a value
2120 * provided by the application."
2121 */
2122 if (up->pcrlen == 0) { /* full coverage was set */
ba7a46f1
JP
2123 net_dbg_ratelimited("UDPLite: partial coverage %d while full coverage %d requested\n",
2124 UDP_SKB_CB(skb)->cscov, skb->len);
db8dac20
DM
2125 goto drop;
2126 }
2127 /* The next case involves violating the min. coverage requested
2128 * by the receiver. This is subtle: if receiver wants x and x is
2129 * greater than the buffersize/MTU then receiver will complain
2130 * that it wants x while sender emits packets of smaller size y.
2131 * Therefore the above ...()->partial_cov statement is essential.
2132 */
2133 if (UDP_SKB_CB(skb)->cscov < up->pcrlen) {
ba7a46f1
JP
2134 net_dbg_ratelimited("UDPLite: coverage %d too small, need min %d\n",
2135 UDP_SKB_CB(skb)->cscov, up->pcrlen);
db8dac20
DM
2136 goto drop;
2137 }
2138 }
2139
dd99e425 2140 prefetch(&sk->sk_rmem_alloc);
ce25d66a
ED
2141 if (rcu_access_pointer(sk->sk_filter) &&
2142 udp_lib_checksum_complete(skb))
e6afc8ac 2143 goto csum_error;
ce25d66a 2144
ba66bbe5 2145 if (sk_filter_trim_cap(sk, skb, sizeof(struct udphdr)))
a6127697 2146 goto drop;
db8dac20 2147
e6afc8ac 2148 udp_csum_pull_header(skb);
db8dac20 2149
fbf8866d 2150 ipv4_pktinfo_prepare(sk, skb);
850cbadd 2151 return __udp_queue_rcv_skb(sk, skb);
db8dac20 2152
6a5dc9e5 2153csum_error:
02c22347 2154 __UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
db8dac20 2155drop:
02c22347 2156 __UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
8edf19c2 2157 atomic_inc(&sk->sk_drops);
db8dac20
DM
2158 kfree_skb(skb);
2159 return -1;
2160}
2161
cf329aa4
PA
2162static int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2163{
2164 struct sk_buff *next, *segs;
2165 int ret;
2166
2167 if (likely(!udp_unexpected_gso(sk, skb)))
2168 return udp_queue_rcv_one_skb(sk, skb);
2169
a08e7fd9 2170 BUILD_BUG_ON(sizeof(struct udp_skb_cb) > SKB_GSO_CB_OFFSET);
cf329aa4
PA
2171 __skb_push(skb, -skb_mac_offset(skb));
2172 segs = udp_rcv_segment(sk, skb, true);
1a186c14 2173 skb_list_walk_safe(segs, skb, next) {
cf329aa4
PA
2174 __skb_pull(skb, skb_transport_offset(skb));
2175 ret = udp_queue_rcv_one_skb(sk, skb);
2176 if (ret > 0)
2177 ip_protocol_deliver_rcu(dev_net(skb->dev), skb, -ret);
2178 }
2179 return 0;
2180}
2181
97502231 2182/* For TCP sockets, sk_rx_dst is protected by socket lock
e47eb5df 2183 * For UDP, we use xchg() to guard against concurrent changes.
97502231 2184 */
64f0f5d1 2185bool udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
421b3885 2186{
97502231
ED
2187 struct dst_entry *old;
2188
d24406c8
WW
2189 if (dst_hold_safe(dst)) {
2190 old = xchg(&sk->sk_rx_dst, dst);
2191 dst_release(old);
64f0f5d1 2192 return old != dst;
d24406c8 2193 }
64f0f5d1 2194 return false;
421b3885 2195}
c9f2c1ae 2196EXPORT_SYMBOL(udp_sk_rx_dst_set);
421b3885 2197
db8dac20
DM
2198/*
2199 * Multicasts and broadcasts go to each listener.
2200 *
1240d137 2201 * Note: called only from the BH handler context.
db8dac20 2202 */
e3163493 2203static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
db8dac20
DM
2204 struct udphdr *uh,
2205 __be32 saddr, __be32 daddr,
36cbb245
RJ
2206 struct udp_table *udptable,
2207 int proto)
db8dac20 2208{
ca065d0c 2209 struct sock *sk, *first = NULL;
5cf3d461
DH
2210 unsigned short hnum = ntohs(uh->dest);
2211 struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum);
2dc41cff 2212 unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10);
ca065d0c
ED
2213 unsigned int offset = offsetof(typeof(*sk), sk_node);
2214 int dif = skb->dev->ifindex;
fb74c277 2215 int sdif = inet_sdif(skb);
ca065d0c
ED
2216 struct hlist_node *node;
2217 struct sk_buff *nskb;
2dc41cff
DH
2218
2219 if (use_hash2) {
f0b1e64c 2220 hash2_any = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum) &
73e2d5e3 2221 udptable->mask;
f0b1e64c 2222 hash2 = ipv4_portaddr_hash(net, daddr, hnum) & udptable->mask;
2dc41cff 2223start_lookup:
73e2d5e3 2224 hslot = &udptable->hash2[hash2];
2dc41cff
DH
2225 offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
2226 }
db8dac20 2227
ca065d0c
ED
2228 sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
2229 if (!__udp_is_mcast_sock(net, sk, uh->dest, daddr,
fb74c277 2230 uh->source, saddr, dif, sdif, hnum))
ca065d0c
ED
2231 continue;
2232
2233 if (!first) {
2234 first = sk;
2235 continue;
1240d137 2236 }
ca065d0c 2237 nskb = skb_clone(skb, GFP_ATOMIC);
1240d137 2238
ca065d0c
ED
2239 if (unlikely(!nskb)) {
2240 atomic_inc(&sk->sk_drops);
02c22347
ED
2241 __UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS,
2242 IS_UDPLITE(sk));
2243 __UDP_INC_STATS(net, UDP_MIB_INERRORS,
2244 IS_UDPLITE(sk));
ca065d0c
ED
2245 continue;
2246 }
2247 if (udp_queue_rcv_skb(sk, nskb) > 0)
2248 consume_skb(nskb);
2249 }
1240d137 2250
2dc41cff
DH
2251 /* Also lookup *:port if we are using hash2 and haven't done so yet. */
2252 if (use_hash2 && hash2 != hash2_any) {
2253 hash2 = hash2_any;
2254 goto start_lookup;
2255 }
2256
ca065d0c
ED
2257 if (first) {
2258 if (udp_queue_rcv_skb(first, skb) > 0)
2259 consume_skb(skb);
1240d137 2260 } else {
ca065d0c 2261 kfree_skb(skb);
02c22347
ED
2262 __UDP_INC_STATS(net, UDP_MIB_IGNOREDMULTI,
2263 proto == IPPROTO_UDPLITE);
1240d137 2264 }
db8dac20
DM
2265 return 0;
2266}
2267
2268/* Initialize UDP checksum. If exited with zero value (success),
2269 * CHECKSUM_UNNECESSARY means, that no more checks are required.
666a3d6e 2270 * Otherwise, csum completion requires checksumming packet body,
db8dac20
DM
2271 * including udp header and folding it to skb->csum.
2272 */
2273static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
2274 int proto)
2275{
db8dac20
DM
2276 int err;
2277
2278 UDP_SKB_CB(skb)->partial_cov = 0;
2279 UDP_SKB_CB(skb)->cscov = skb->len;
2280
2281 if (proto == IPPROTO_UDPLITE) {
2282 err = udplite_checksum_init(skb, uh);
2283 if (err)
2284 return err;
15f35d49
AK
2285
2286 if (UDP_SKB_CB(skb)->partial_cov) {
2287 skb->csum = inet_compute_pseudo(skb, proto);
2288 return 0;
2289 }
db8dac20
DM
2290 }
2291
b46d9f62
HFS
2292 /* Note, we are only interested in != 0 or == 0, thus the
2293 * force to int.
2294 */
db4f1be3
ST
2295 err = (__force int)skb_checksum_init_zero_check(skb, proto, uh->check,
2296 inet_compute_pseudo);
2297 if (err)
2298 return err;
2299
2300 if (skb->ip_summed == CHECKSUM_COMPLETE && !skb->csum_valid) {
2301 /* If SW calculated the value, we know it's bad */
2302 if (skb->csum_complete_sw)
2303 return 1;
2304
2305 /* HW says the value is bad. Let's validate that.
2306 * skb->csum is no longer the full packet checksum,
2307 * so don't treat it as such.
2308 */
2309 skb_checksum_complete_unset(skb);
2310 }
2311
2312 return 0;
db8dac20
DM
2313}
2314
2b5a9217
PA
2315/* wrapper for udp_queue_rcv_skb tacking care of csum conversion and
2316 * return code conversion for ip layer consumption
2317 */
2318static int udp_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb,
2319 struct udphdr *uh)
2320{
2321 int ret;
2322
2323 if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk))
e4aa33ad 2324 skb_checksum_try_convert(skb, IPPROTO_UDP, inet_compute_pseudo);
2b5a9217
PA
2325
2326 ret = udp_queue_rcv_skb(sk, skb);
2327
2328 /* a return value > 0 means to resubmit the input, but
2329 * it wants the return to be -protocol, or 0
2330 */
2331 if (ret > 0)
2332 return -ret;
2333 return 0;
2334}
2335
db8dac20
DM
2336/*
2337 * All we need to do is get the socket, and then do a checksum.
2338 */
2339
645ca708 2340int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
db8dac20
DM
2341 int proto)
2342{
2343 struct sock *sk;
7b5e56f9 2344 struct udphdr *uh;
db8dac20 2345 unsigned short ulen;
adf30907 2346 struct rtable *rt = skb_rtable(skb);
2783ef23 2347 __be32 saddr, daddr;
0283328e 2348 struct net *net = dev_net(skb->dev);
71489e21 2349 bool refcounted;
db8dac20
DM
2350
2351 /*
2352 * Validate the packet.
2353 */
2354 if (!pskb_may_pull(skb, sizeof(struct udphdr)))
2355 goto drop; /* No space for header. */
2356
7b5e56f9 2357 uh = udp_hdr(skb);
db8dac20 2358 ulen = ntohs(uh->len);
ccc2d97c
BM
2359 saddr = ip_hdr(skb)->saddr;
2360 daddr = ip_hdr(skb)->daddr;
2361
db8dac20
DM
2362 if (ulen > skb->len)
2363 goto short_packet;
2364
2365 if (proto == IPPROTO_UDP) {
2366 /* UDP validates ulen. */
2367 if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
2368 goto short_packet;
2369 uh = udp_hdr(skb);
2370 }
2371
2372 if (udp4_csum_init(skb, uh, proto))
2373 goto csum_error;
2374
71489e21 2375 sk = skb_steal_sock(skb, &refcounted);
8afdd99a 2376 if (sk) {
97502231 2377 struct dst_entry *dst = skb_dst(skb);
421b3885 2378 int ret;
421b3885 2379
97502231
ED
2380 if (unlikely(sk->sk_rx_dst != dst))
2381 udp_sk_rx_dst_set(sk, dst);
db8dac20 2382
2b5a9217 2383 ret = udp_unicast_rcv_skb(sk, skb, uh);
71489e21
JS
2384 if (refcounted)
2385 sock_put(sk);
2b5a9217 2386 return ret;
421b3885 2387 }
db8dac20 2388
c18450a5
FF
2389 if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
2390 return __udp4_lib_mcast_deliver(net, skb, uh,
36cbb245 2391 saddr, daddr, udptable, proto);
c18450a5
FF
2392
2393 sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
2b5a9217
PA
2394 if (sk)
2395 return udp_unicast_rcv_skb(sk, skb, uh);
db8dac20
DM
2396
2397 if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
2398 goto drop;
895b5c9f 2399 nf_reset_ct(skb);
db8dac20
DM
2400
2401 /* No socket. Drop packet silently, if checksum is wrong */
2402 if (udp_lib_checksum_complete(skb))
2403 goto csum_error;
2404
02c22347 2405 __UDP_INC_STATS(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
db8dac20
DM
2406 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
2407
2408 /*
2409 * Hmm. We got an UDP packet to a port to which we
2410 * don't wanna listen. Ignore it.
2411 */
2412 kfree_skb(skb);
2413 return 0;
2414
2415short_packet:
ba7a46f1
JP
2416 net_dbg_ratelimited("UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
2417 proto == IPPROTO_UDPLITE ? "Lite" : "",
2418 &saddr, ntohs(uh->source),
2419 ulen, skb->len,
2420 &daddr, ntohs(uh->dest));
db8dac20
DM
2421 goto drop;
2422
2423csum_error:
2424 /*
2425 * RFC1122: OK. Discards the bad packet silently (as far as
2426 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
2427 */
ba7a46f1
JP
2428 net_dbg_ratelimited("UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
2429 proto == IPPROTO_UDPLITE ? "Lite" : "",
2430 &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
2431 ulen);
02c22347 2432 __UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
db8dac20 2433drop:
02c22347 2434 __UDP_INC_STATS(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
db8dac20
DM
2435 kfree_skb(skb);
2436 return 0;
2437}
2438
421b3885
SB
2439/* We can only early demux multicast if there is a single matching socket.
2440 * If more than one socket found returns NULL
2441 */
2442static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net,
2443 __be16 loc_port, __be32 loc_addr,
2444 __be16 rmt_port, __be32 rmt_addr,
fb74c277 2445 int dif, int sdif)
421b3885
SB
2446{
2447 struct sock *sk, *result;
421b3885 2448 unsigned short hnum = ntohs(loc_port);
ca065d0c 2449 unsigned int slot = udp_hashfn(net, hnum, udp_table.mask);
421b3885
SB
2450 struct udp_hslot *hslot = &udp_table.hash[slot];
2451
63c6f81c
ED
2452 /* Do not bother scanning a too big list */
2453 if (hslot->count > 10)
2454 return NULL;
2455
421b3885 2456 result = NULL;
ca065d0c
ED
2457 sk_for_each_rcu(sk, &hslot->head) {
2458 if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr,
fb74c277 2459 rmt_port, rmt_addr, dif, sdif, hnum)) {
ca065d0c
ED
2460 if (result)
2461 return NULL;
421b3885 2462 result = sk;
421b3885
SB
2463 }
2464 }
ca065d0c 2465
421b3885
SB
2466 return result;
2467}
2468
2469/* For unicast we should only early demux connected sockets or we can
2470 * break forwarding setups. The chains here can be long so only check
2471 * if the first socket is an exact match and if not move on.
2472 */
2473static struct sock *__udp4_lib_demux_lookup(struct net *net,
2474 __be16 loc_port, __be32 loc_addr,
2475 __be16 rmt_port, __be32 rmt_addr,
3fa6f616 2476 int dif, int sdif)
421b3885 2477{
421b3885 2478 unsigned short hnum = ntohs(loc_port);
f0b1e64c 2479 unsigned int hash2 = ipv4_portaddr_hash(net, loc_addr, hnum);
421b3885
SB
2480 unsigned int slot2 = hash2 & udp_table.mask;
2481 struct udp_hslot *hslot2 = &udp_table.hash2[slot2];
c7228317 2482 INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr);
421b3885 2483 const __portpair ports = INET_COMBINED_PORTS(rmt_port, hnum);
ca065d0c 2484 struct sock *sk;
421b3885 2485
ca065d0c
ED
2486 udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
2487 if (INET_MATCH(sk, net, acookie, rmt_addr,
3fa6f616 2488 loc_addr, ports, dif, sdif))
ca065d0c 2489 return sk;
421b3885
SB
2490 /* Only check first socket in chain */
2491 break;
2492 }
ca065d0c 2493 return NULL;
421b3885
SB
2494}
2495
7487449c 2496int udp_v4_early_demux(struct sk_buff *skb)
421b3885 2497{
610438b7 2498 struct net *net = dev_net(skb->dev);
bc044e8d 2499 struct in_device *in_dev = NULL;
610438b7
ED
2500 const struct iphdr *iph;
2501 const struct udphdr *uh;
ca065d0c 2502 struct sock *sk = NULL;
421b3885 2503 struct dst_entry *dst;
421b3885 2504 int dif = skb->dev->ifindex;
fb74c277 2505 int sdif = inet_sdif(skb);
6e540309 2506 int ours;
421b3885
SB
2507
2508 /* validate the packet */
2509 if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)))
7487449c 2510 return 0;
421b3885 2511
610438b7
ED
2512 iph = ip_hdr(skb);
2513 uh = udp_hdr(skb);
2514
996b44fc 2515 if (skb->pkt_type == PACKET_MULTICAST) {
bc044e8d 2516 in_dev = __in_dev_get_rcu(skb->dev);
6e540309
SB
2517
2518 if (!in_dev)
7487449c 2519 return 0;
6e540309 2520
996b44fc
PA
2521 ours = ip_check_mc_rcu(in_dev, iph->daddr, iph->saddr,
2522 iph->protocol);
2523 if (!ours)
2524 return 0;
ad0ea198 2525
421b3885 2526 sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr,
fb74c277
DA
2527 uh->source, iph->saddr,
2528 dif, sdif);
6e540309 2529 } else if (skb->pkt_type == PACKET_HOST) {
421b3885 2530 sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr,
3fa6f616 2531 uh->source, iph->saddr, dif, sdif);
6e540309 2532 }
421b3885 2533
41c6d650 2534 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
7487449c 2535 return 0;
421b3885
SB
2536
2537 skb->sk = sk;
82eabd9e 2538 skb->destructor = sock_efree;
10e2eb87 2539 dst = READ_ONCE(sk->sk_rx_dst);
421b3885
SB
2540
2541 if (dst)
2542 dst = dst_check(dst, 0);
10e2eb87 2543 if (dst) {
bc044e8d
PA
2544 u32 itag = 0;
2545
d24406c8
WW
2546 /* set noref for now.
2547 * any place which wants to hold dst has to call
2548 * dst_hold_safe()
2549 */
2550 skb_dst_set_noref(skb, dst);
bc044e8d
PA
2551
2552 /* for unconnected multicast sockets we need to validate
2553 * the source on each packet
2554 */
2555 if (!inet_sk(sk)->inet_daddr && in_dev)
2556 return ip_mc_validate_source(skb, iph->daddr,
2557 iph->saddr, iph->tos,
2558 skb->dev, in_dev, &itag);
10e2eb87 2559 }
7487449c 2560 return 0;
421b3885
SB
2561}
2562
db8dac20
DM
2563int udp_rcv(struct sk_buff *skb)
2564{
645ca708 2565 return __udp4_lib_rcv(skb, &udp_table, IPPROTO_UDP);
db8dac20
DM
2566}
2567
7d06b2e0 2568void udp_destroy_sock(struct sock *sk)
db8dac20 2569{
44046a59 2570 struct udp_sock *up = udp_sk(sk);
8a74ad60 2571 bool slow = lock_sock_fast(sk);
db8dac20 2572 udp_flush_pending_frames(sk);
8a74ad60 2573 unlock_sock_fast(sk, slow);
60fb9567
PA
2574 if (static_branch_unlikely(&udp_encap_needed_key)) {
2575 if (up->encap_type) {
2576 void (*encap_destroy)(struct sock *sk);
2577 encap_destroy = READ_ONCE(up->encap_destroy);
2578 if (encap_destroy)
2579 encap_destroy(sk);
2580 }
2581 if (up->encap_enabled)
9c480601 2582 static_branch_dec(&udp_encap_needed_key);
44046a59 2583 }
db8dac20
DM
2584}
2585
1da177e4
LT
2586/*
2587 * Socket option code for UDP
2588 */
4c0a6cb0 2589int udp_lib_setsockopt(struct sock *sk, int level, int optname,
b7058842 2590 char __user *optval, unsigned int optlen,
4c0a6cb0 2591 int (*push_pending_frames)(struct sock *))
1da177e4
LT
2592{
2593 struct udp_sock *up = udp_sk(sk);
1c19448c 2594 int val, valbool;
1da177e4 2595 int err = 0;
b2bf1e26 2596 int is_udplite = IS_UDPLITE(sk);
1da177e4 2597
c482c568 2598 if (optlen < sizeof(int))
1da177e4
LT
2599 return -EINVAL;
2600
2601 if (get_user(val, (int __user *)optval))
2602 return -EFAULT;
2603
1c19448c
TH
2604 valbool = val ? 1 : 0;
2605
6516c655 2606 switch (optname) {
1da177e4
LT
2607 case UDP_CORK:
2608 if (val != 0) {
2609 up->corkflag = 1;
2610 } else {
2611 up->corkflag = 0;
2612 lock_sock(sk);
4243cdc2 2613 push_pending_frames(sk);
1da177e4
LT
2614 release_sock(sk);
2615 }
2616 break;
e905a9ed 2617
1da177e4
LT
2618 case UDP_ENCAP:
2619 switch (val) {
2620 case 0:
fd1ac07f 2621#ifdef CONFIG_XFRM
1da177e4
LT
2622 case UDP_ENCAP_ESPINUDP:
2623 case UDP_ENCAP_ESPINUDP_NON_IKE:
0146dca7
SD
2624#if IS_ENABLED(CONFIG_IPV6)
2625 if (sk->sk_family == AF_INET6)
2626 up->encap_rcv = ipv6_stub->xfrm6_udp_encap_rcv;
2627 else
2628#endif
2629 up->encap_rcv = xfrm4_udp_encap_rcv;
fd1ac07f 2630#endif
a8eceea8 2631 fallthrough;
342f0234 2632 case UDP_ENCAP_L2TPINUDP:
1da177e4 2633 up->encap_type = val;
60fb9567
PA
2634 lock_sock(sk);
2635 udp_tunnel_encap_enable(sk->sk_socket);
2636 release_sock(sk);
1da177e4
LT
2637 break;
2638 default:
2639 err = -ENOPROTOOPT;
2640 break;
2641 }
2642 break;
2643
1c19448c
TH
2644 case UDP_NO_CHECK6_TX:
2645 up->no_check6_tx = valbool;
2646 break;
2647
2648 case UDP_NO_CHECK6_RX:
2649 up->no_check6_rx = valbool;
2650 break;
2651
bec1f6f6
WB
2652 case UDP_SEGMENT:
2653 if (val < 0 || val > USHRT_MAX)
2654 return -EINVAL;
2655 up->gso_size = val;
2656 break;
2657
e20cf8d3
PA
2658 case UDP_GRO:
2659 lock_sock(sk);
2660 if (valbool)
2661 udp_tunnel_encap_enable(sk->sk_socket);
2662 up->gro_enabled = valbool;
2663 release_sock(sk);
2664 break;
2665
ba4e58ec
GR
2666 /*
2667 * UDP-Lite's partial checksum coverage (RFC 3828).
2668 */
2669 /* The sender sets actual checksum coverage length via this option.
2670 * The case coverage > packet length is handled by send module. */
2671 case UDPLITE_SEND_CSCOV:
b2bf1e26 2672 if (!is_udplite) /* Disable the option on UDP sockets */
ba4e58ec
GR
2673 return -ENOPROTOOPT;
2674 if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
2675 val = 8;
4be929be
AD
2676 else if (val > USHRT_MAX)
2677 val = USHRT_MAX;
ba4e58ec
GR
2678 up->pcslen = val;
2679 up->pcflag |= UDPLITE_SEND_CC;
2680 break;
2681
e905a9ed
YH
2682 /* The receiver specifies a minimum checksum coverage value. To make
2683 * sense, this should be set to at least 8 (as done below). If zero is
ba4e58ec
GR
2684 * used, this again means full checksum coverage. */
2685 case UDPLITE_RECV_CSCOV:
b2bf1e26 2686 if (!is_udplite) /* Disable the option on UDP sockets */
ba4e58ec
GR
2687 return -ENOPROTOOPT;
2688 if (val != 0 && val < 8) /* Avoid silly minimal values. */
2689 val = 8;
4be929be
AD
2690 else if (val > USHRT_MAX)
2691 val = USHRT_MAX;
ba4e58ec
GR
2692 up->pcrlen = val;
2693 up->pcflag |= UDPLITE_RECV_CC;
2694 break;
2695
1da177e4
LT
2696 default:
2697 err = -ENOPROTOOPT;
2698 break;
6516c655 2699 }
1da177e4
LT
2700
2701 return err;
2702}
c482c568 2703EXPORT_SYMBOL(udp_lib_setsockopt);
1da177e4 2704
db8dac20 2705int udp_setsockopt(struct sock *sk, int level, int optname,
b7058842 2706 char __user *optval, unsigned int optlen)
db8dac20
DM
2707{
2708 if (level == SOL_UDP || level == SOL_UDPLITE)
2709 return udp_lib_setsockopt(sk, level, optname, optval, optlen,
2710 udp_push_pending_frames);
2711 return ip_setsockopt(sk, level, optname, optval, optlen);
2712}
2713
2714#ifdef CONFIG_COMPAT
2715int compat_udp_setsockopt(struct sock *sk, int level, int optname,
b7058842 2716 char __user *optval, unsigned int optlen)
db8dac20
DM
2717{
2718 if (level == SOL_UDP || level == SOL_UDPLITE)
2719 return udp_lib_setsockopt(sk, level, optname, optval, optlen,
2720 udp_push_pending_frames);
2721 return compat_ip_setsockopt(sk, level, optname, optval, optlen);
2722}
2723#endif
2724
4c0a6cb0
GR
2725int udp_lib_getsockopt(struct sock *sk, int level, int optname,
2726 char __user *optval, int __user *optlen)
1da177e4
LT
2727{
2728 struct udp_sock *up = udp_sk(sk);
2729 int val, len;
2730
c482c568 2731 if (get_user(len, optlen))
1da177e4
LT
2732 return -EFAULT;
2733
2734 len = min_t(unsigned int, len, sizeof(int));
e905a9ed 2735
6516c655 2736 if (len < 0)
1da177e4
LT
2737 return -EINVAL;
2738
6516c655 2739 switch (optname) {
1da177e4
LT
2740 case UDP_CORK:
2741 val = up->corkflag;
2742 break;
2743
2744 case UDP_ENCAP:
2745 val = up->encap_type;
2746 break;
2747
1c19448c
TH
2748 case UDP_NO_CHECK6_TX:
2749 val = up->no_check6_tx;
2750 break;
2751
2752 case UDP_NO_CHECK6_RX:
2753 val = up->no_check6_rx;
2754 break;
2755
bec1f6f6
WB
2756 case UDP_SEGMENT:
2757 val = up->gso_size;
2758 break;
2759
ba4e58ec
GR
2760 /* The following two cannot be changed on UDP sockets, the return is
2761 * always 0 (which corresponds to the full checksum coverage of UDP). */
2762 case UDPLITE_SEND_CSCOV:
2763 val = up->pcslen;
2764 break;
2765
2766 case UDPLITE_RECV_CSCOV:
2767 val = up->pcrlen;
2768 break;
2769
1da177e4
LT
2770 default:
2771 return -ENOPROTOOPT;
6516c655 2772 }
1da177e4 2773
6516c655 2774 if (put_user(len, optlen))
e905a9ed 2775 return -EFAULT;
c482c568 2776 if (copy_to_user(optval, &val, len))
1da177e4 2777 return -EFAULT;
e905a9ed 2778 return 0;
1da177e4 2779}
c482c568 2780EXPORT_SYMBOL(udp_lib_getsockopt);
1da177e4 2781
db8dac20
DM
2782int udp_getsockopt(struct sock *sk, int level, int optname,
2783 char __user *optval, int __user *optlen)
2784{
2785 if (level == SOL_UDP || level == SOL_UDPLITE)
2786 return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2787 return ip_getsockopt(sk, level, optname, optval, optlen);
2788}
2789
2790#ifdef CONFIG_COMPAT
2791int compat_udp_getsockopt(struct sock *sk, int level, int optname,
2792 char __user *optval, int __user *optlen)
2793{
2794 if (level == SOL_UDP || level == SOL_UDPLITE)
2795 return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2796 return compat_ip_getsockopt(sk, level, optname, optval, optlen);
2797}
2798#endif
1da177e4
LT
2799/**
2800 * udp_poll - wait for a UDP event.
3628e3cb
AL
2801 * @file: - file struct
2802 * @sock: - socket
2803 * @wait: - poll table
1da177e4 2804 *
e905a9ed 2805 * This is same as datagram poll, except for the special case of
1da177e4
LT
2806 * blocking sockets. If application is using a blocking fd
2807 * and a packet with checksum error is in the queue;
2808 * then it could get return from select indicating data available
2809 * but then block when reading it. Add special case code
2810 * to work around these arguably broken applications.
2811 */
a11e1d43 2812__poll_t udp_poll(struct file *file, struct socket *sock, poll_table *wait)
1da177e4 2813{
a11e1d43 2814 __poll_t mask = datagram_poll(file, sock, wait);
1da177e4 2815 struct sock *sk = sock->sk;
ba4e58ec 2816
3ef7cf57 2817 if (!skb_queue_empty_lockless(&udp_sk(sk)->reader_queue))
a9a08845 2818 mask |= EPOLLIN | EPOLLRDNORM;
2276f58a 2819
1da177e4 2820 /* Check for false positives due to checksum errors */
a11e1d43 2821 if ((mask & EPOLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
e83c6744 2822 !(sk->sk_shutdown & RCV_SHUTDOWN) && first_packet_length(sk) == -1)
a9a08845 2823 mask &= ~(EPOLLIN | EPOLLRDNORM);
1da177e4
LT
2824
2825 return mask;
e905a9ed 2826
1da177e4 2827}
a11e1d43 2828EXPORT_SYMBOL(udp_poll);
1da177e4 2829
5d77dca8
DA
2830int udp_abort(struct sock *sk, int err)
2831{
2832 lock_sock(sk);
2833
2834 sk->sk_err = err;
2835 sk->sk_error_report(sk);
286c72de 2836 __udp_disconnect(sk, 0);
5d77dca8
DA
2837
2838 release_sock(sk);
2839
2840 return 0;
2841}
2842EXPORT_SYMBOL_GPL(udp_abort);
2843
db8dac20 2844struct proto udp_prot = {
1e802951
TZ
2845 .name = "UDP",
2846 .owner = THIS_MODULE,
2847 .close = udp_lib_close,
d74bad4e 2848 .pre_connect = udp_pre_connect,
1e802951
TZ
2849 .connect = ip4_datagram_connect,
2850 .disconnect = udp_disconnect,
2851 .ioctl = udp_ioctl,
2852 .init = udp_init_sock,
2853 .destroy = udp_destroy_sock,
2854 .setsockopt = udp_setsockopt,
2855 .getsockopt = udp_getsockopt,
2856 .sendmsg = udp_sendmsg,
2857 .recvmsg = udp_recvmsg,
2858 .sendpage = udp_sendpage,
2859 .release_cb = ip4_datagram_release_cb,
2860 .hash = udp_lib_hash,
2861 .unhash = udp_lib_unhash,
2862 .rehash = udp_v4_rehash,
2863 .get_port = udp_v4_get_port,
2864 .memory_allocated = &udp_memory_allocated,
2865 .sysctl_mem = sysctl_udp_mem,
2866 .sysctl_wmem_offset = offsetof(struct net, ipv4.sysctl_udp_wmem_min),
2867 .sysctl_rmem_offset = offsetof(struct net, ipv4.sysctl_udp_rmem_min),
2868 .obj_size = sizeof(struct udp_sock),
2869 .h.udp_table = &udp_table,
db8dac20 2870#ifdef CONFIG_COMPAT
1e802951
TZ
2871 .compat_setsockopt = compat_udp_setsockopt,
2872 .compat_getsockopt = compat_udp_getsockopt,
db8dac20 2873#endif
1e802951 2874 .diag_destroy = udp_abort,
db8dac20 2875};
c482c568 2876EXPORT_SYMBOL(udp_prot);
1da177e4
LT
2877
2878/* ------------------------------------------------------------------------ */
2879#ifdef CONFIG_PROC_FS
2880
645ca708 2881static struct sock *udp_get_first(struct seq_file *seq, int start)
1da177e4
LT
2882{
2883 struct sock *sk;
9e8ca27a 2884 struct udp_seq_afinfo *afinfo;
1da177e4 2885 struct udp_iter_state *state = seq->private;
6f191efe 2886 struct net *net = seq_file_net(seq);
1da177e4 2887
9e8ca27a
YS
2888 if (state->bpf_seq_afinfo)
2889 afinfo = state->bpf_seq_afinfo;
2890 else
2891 afinfo = PDE_DATA(file_inode(seq->file));
2892
a3d2599b 2893 for (state->bucket = start; state->bucket <= afinfo->udp_table->mask;
f86dcc5a 2894 ++state->bucket) {
a3d2599b 2895 struct udp_hslot *hslot = &afinfo->udp_table->hash[state->bucket];
f86dcc5a 2896
ca065d0c 2897 if (hlist_empty(&hslot->head))
f86dcc5a
ED
2898 continue;
2899
645ca708 2900 spin_lock_bh(&hslot->lock);
ca065d0c 2901 sk_for_each(sk, &hslot->head) {
878628fb 2902 if (!net_eq(sock_net(sk), net))
a91275ef 2903 continue;
9e8ca27a
YS
2904 if (afinfo->family == AF_UNSPEC ||
2905 sk->sk_family == afinfo->family)
1da177e4
LT
2906 goto found;
2907 }
645ca708 2908 spin_unlock_bh(&hslot->lock);
1da177e4
LT
2909 }
2910 sk = NULL;
2911found:
2912 return sk;
2913}
2914
2915static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
2916{
9e8ca27a 2917 struct udp_seq_afinfo *afinfo;
1da177e4 2918 struct udp_iter_state *state = seq->private;
6f191efe 2919 struct net *net = seq_file_net(seq);
1da177e4 2920
9e8ca27a
YS
2921 if (state->bpf_seq_afinfo)
2922 afinfo = state->bpf_seq_afinfo;
2923 else
2924 afinfo = PDE_DATA(file_inode(seq->file));
2925
1da177e4 2926 do {
ca065d0c 2927 sk = sk_next(sk);
9e8ca27a
YS
2928 } while (sk && (!net_eq(sock_net(sk), net) ||
2929 (afinfo->family != AF_UNSPEC &&
2930 sk->sk_family != afinfo->family)));
1da177e4 2931
645ca708 2932 if (!sk) {
a3d2599b
CH
2933 if (state->bucket <= afinfo->udp_table->mask)
2934 spin_unlock_bh(&afinfo->udp_table->hash[state->bucket].lock);
645ca708 2935 return udp_get_first(seq, state->bucket + 1);
1da177e4
LT
2936 }
2937 return sk;
2938}
2939
2940static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
2941{
645ca708 2942 struct sock *sk = udp_get_first(seq, 0);
1da177e4
LT
2943
2944 if (sk)
6516c655 2945 while (pos && (sk = udp_get_next(seq, sk)) != NULL)
1da177e4
LT
2946 --pos;
2947 return pos ? NULL : sk;
2948}
2949
a3d2599b 2950void *udp_seq_start(struct seq_file *seq, loff_t *pos)
1da177e4 2951{
30842f29 2952 struct udp_iter_state *state = seq->private;
f86dcc5a 2953 state->bucket = MAX_UDP_PORTS;
30842f29 2954
b50660f1 2955 return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
1da177e4 2956}
a3d2599b 2957EXPORT_SYMBOL(udp_seq_start);
1da177e4 2958
a3d2599b 2959void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1da177e4
LT
2960{
2961 struct sock *sk;
2962
b50660f1 2963 if (v == SEQ_START_TOKEN)
1da177e4
LT
2964 sk = udp_get_idx(seq, 0);
2965 else
2966 sk = udp_get_next(seq, v);
2967
2968 ++*pos;
2969 return sk;
2970}
a3d2599b 2971EXPORT_SYMBOL(udp_seq_next);
1da177e4 2972
a3d2599b 2973void udp_seq_stop(struct seq_file *seq, void *v)
1da177e4 2974{
9e8ca27a 2975 struct udp_seq_afinfo *afinfo;
645ca708
ED
2976 struct udp_iter_state *state = seq->private;
2977
9e8ca27a
YS
2978 if (state->bpf_seq_afinfo)
2979 afinfo = state->bpf_seq_afinfo;
2980 else
2981 afinfo = PDE_DATA(file_inode(seq->file));
2982
a3d2599b
CH
2983 if (state->bucket <= afinfo->udp_table->mask)
2984 spin_unlock_bh(&afinfo->udp_table->hash[state->bucket].lock);
1da177e4 2985}
a3d2599b 2986EXPORT_SYMBOL(udp_seq_stop);
db8dac20
DM
2987
2988/* ------------------------------------------------------------------------ */
5e659e4c 2989static void udp4_format_sock(struct sock *sp, struct seq_file *f,
652586df 2990 int bucket)
db8dac20
DM
2991{
2992 struct inet_sock *inet = inet_sk(sp);
c720c7e8
ED
2993 __be32 dest = inet->inet_daddr;
2994 __be32 src = inet->inet_rcv_saddr;
2995 __u16 destp = ntohs(inet->inet_dport);
2996 __u16 srcp = ntohs(inet->inet_sport);
db8dac20 2997
f86dcc5a 2998 seq_printf(f, "%5d: %08X:%04X %08X:%04X"
ea9a0379 2999 " %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %u",
db8dac20 3000 bucket, src, srcp, dest, destp, sp->sk_state,
31e6d363 3001 sk_wmem_alloc_get(sp),
6c206b20 3002 udp_rqueue_get(sp),
a7cb5a49
EB
3003 0, 0L, 0,
3004 from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
3005 0, sock_i_ino(sp),
41c6d650 3006 refcount_read(&sp->sk_refcnt), sp,
652586df 3007 atomic_read(&sp->sk_drops));
db8dac20
DM
3008}
3009
3010int udp4_seq_show(struct seq_file *seq, void *v)
3011{
652586df 3012 seq_setwidth(seq, 127);
db8dac20 3013 if (v == SEQ_START_TOKEN)
652586df 3014 seq_puts(seq, " sl local_address rem_address st tx_queue "
db8dac20 3015 "rx_queue tr tm->when retrnsmt uid timeout "
cb61cb9b 3016 "inode ref pointer drops");
db8dac20 3017 else {
db8dac20
DM
3018 struct udp_iter_state *state = seq->private;
3019
652586df 3020 udp4_format_sock(v, seq, state->bucket);
db8dac20 3021 }
652586df 3022 seq_pad(seq, '\n');
db8dac20
DM
3023 return 0;
3024}
3025
5788b3a0
YS
3026#ifdef CONFIG_BPF_SYSCALL
3027struct bpf_iter__udp {
3028 __bpf_md_ptr(struct bpf_iter_meta *, meta);
3029 __bpf_md_ptr(struct udp_sock *, udp_sk);
3030 uid_t uid __aligned(8);
3031 int bucket __aligned(8);
3032};
3033
3034static int udp_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
3035 struct udp_sock *udp_sk, uid_t uid, int bucket)
3036{
3037 struct bpf_iter__udp ctx;
3038
3039 meta->seq_num--; /* skip SEQ_START_TOKEN */
3040 ctx.meta = meta;
3041 ctx.udp_sk = udp_sk;
3042 ctx.uid = uid;
3043 ctx.bucket = bucket;
3044 return bpf_iter_run_prog(prog, &ctx);
3045}
3046
3047static int bpf_iter_udp_seq_show(struct seq_file *seq, void *v)
3048{
3049 struct udp_iter_state *state = seq->private;
3050 struct bpf_iter_meta meta;
3051 struct bpf_prog *prog;
3052 struct sock *sk = v;
3053 uid_t uid;
3054
3055 if (v == SEQ_START_TOKEN)
3056 return 0;
3057
3058 uid = from_kuid_munged(seq_user_ns(seq), sock_i_uid(sk));
3059 meta.seq = seq;
3060 prog = bpf_iter_get_info(&meta, false);
3061 return udp_prog_seq_show(prog, &meta, v, uid, state->bucket);
3062}
3063
3064static void bpf_iter_udp_seq_stop(struct seq_file *seq, void *v)
3065{
3066 struct bpf_iter_meta meta;
3067 struct bpf_prog *prog;
3068
3069 if (!v) {
3070 meta.seq = seq;
3071 prog = bpf_iter_get_info(&meta, true);
3072 if (prog)
3073 (void)udp_prog_seq_show(prog, &meta, v, 0, 0);
3074 }
3075
3076 udp_seq_stop(seq, v);
3077}
3078
3079static const struct seq_operations bpf_iter_udp_seq_ops = {
3080 .start = udp_seq_start,
3081 .next = udp_seq_next,
3082 .stop = bpf_iter_udp_seq_stop,
3083 .show = bpf_iter_udp_seq_show,
3084};
3085#endif
3086
c3506372 3087const struct seq_operations udp_seq_ops = {
a3d2599b
CH
3088 .start = udp_seq_start,
3089 .next = udp_seq_next,
3090 .stop = udp_seq_stop,
3091 .show = udp4_seq_show,
3092};
c3506372 3093EXPORT_SYMBOL(udp_seq_ops);
73cb88ec 3094
db8dac20 3095static struct udp_seq_afinfo udp4_seq_afinfo = {
db8dac20 3096 .family = AF_INET,
645ca708 3097 .udp_table = &udp_table,
db8dac20
DM
3098};
3099
2c8c1e72 3100static int __net_init udp4_proc_init_net(struct net *net)
15439feb 3101{
c3506372
CH
3102 if (!proc_create_net_data("udp", 0444, net->proc_net, &udp_seq_ops,
3103 sizeof(struct udp_iter_state), &udp4_seq_afinfo))
a3d2599b
CH
3104 return -ENOMEM;
3105 return 0;
15439feb
PE
3106}
3107
2c8c1e72 3108static void __net_exit udp4_proc_exit_net(struct net *net)
15439feb 3109{
a3d2599b 3110 remove_proc_entry("udp", net->proc_net);
15439feb
PE
3111}
3112
3113static struct pernet_operations udp4_net_ops = {
3114 .init = udp4_proc_init_net,
3115 .exit = udp4_proc_exit_net,
3116};
3117
db8dac20
DM
3118int __init udp4_proc_init(void)
3119{
15439feb 3120 return register_pernet_subsys(&udp4_net_ops);
db8dac20
DM
3121}
3122
3123void udp4_proc_exit(void)
3124{
15439feb 3125 unregister_pernet_subsys(&udp4_net_ops);
db8dac20 3126}
1da177e4
LT
3127#endif /* CONFIG_PROC_FS */
3128
f86dcc5a
ED
3129static __initdata unsigned long uhash_entries;
3130static int __init set_uhash_entries(char *str)
645ca708 3131{
413c27d8
EZ
3132 ssize_t ret;
3133
f86dcc5a
ED
3134 if (!str)
3135 return 0;
413c27d8
EZ
3136
3137 ret = kstrtoul(str, 0, &uhash_entries);
3138 if (ret)
3139 return 0;
3140
f86dcc5a
ED
3141 if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
3142 uhash_entries = UDP_HTABLE_SIZE_MIN;
3143 return 1;
3144}
3145__setup("uhash_entries=", set_uhash_entries);
645ca708 3146
f86dcc5a
ED
3147void __init udp_table_init(struct udp_table *table, const char *name)
3148{
3149 unsigned int i;
3150
31fe62b9
TB
3151 table->hash = alloc_large_system_hash(name,
3152 2 * sizeof(struct udp_hslot),
3153 uhash_entries,
3154 21, /* one slot per 2 MB */
3155 0,
3156 &table->log,
3157 &table->mask,
3158 UDP_HTABLE_SIZE_MIN,
3159 64 * 1024);
3160
512615b6 3161 table->hash2 = table->hash + (table->mask + 1);
f86dcc5a 3162 for (i = 0; i <= table->mask; i++) {
ca065d0c 3163 INIT_HLIST_HEAD(&table->hash[i].head);
fdcc8aa9 3164 table->hash[i].count = 0;
645ca708
ED
3165 spin_lock_init(&table->hash[i].lock);
3166 }
512615b6 3167 for (i = 0; i <= table->mask; i++) {
ca065d0c 3168 INIT_HLIST_HEAD(&table->hash2[i].head);
512615b6
ED
3169 table->hash2[i].count = 0;
3170 spin_lock_init(&table->hash2[i].lock);
3171 }
645ca708
ED
3172}
3173
723b8e46
TH
3174u32 udp_flow_hashrnd(void)
3175{
3176 static u32 hashrnd __read_mostly;
3177
3178 net_get_random_once(&hashrnd, sizeof(hashrnd));
3179
3180 return hashrnd;
3181}
3182EXPORT_SYMBOL(udp_flow_hashrnd);
3183
1e802951
TZ
3184static void __udp_sysctl_init(struct net *net)
3185{
3186 net->ipv4.sysctl_udp_rmem_min = SK_MEM_QUANTUM;
3187 net->ipv4.sysctl_udp_wmem_min = SK_MEM_QUANTUM;
3188
3189#ifdef CONFIG_NET_L3_MASTER_DEV
3190 net->ipv4.sysctl_udp_l3mdev_accept = 0;
3191#endif
3192}
3193
3194static int __net_init udp_sysctl_init(struct net *net)
3195{
3196 __udp_sysctl_init(net);
3197 return 0;
3198}
3199
3200static struct pernet_operations __net_initdata udp_sysctl_ops = {
fc18999e 3201 .init = udp_sysctl_init,
1e802951
TZ
3202};
3203
5788b3a0
YS
3204#if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
3205DEFINE_BPF_ITER_FUNC(udp, struct bpf_iter_meta *meta,
3206 struct udp_sock *udp_sk, uid_t uid, int bucket)
3207
3208static int bpf_iter_init_udp(void *priv_data)
3209{
3210 struct udp_iter_state *st = priv_data;
3211 struct udp_seq_afinfo *afinfo;
3212 int ret;
3213
3214 afinfo = kmalloc(sizeof(*afinfo), GFP_USER | __GFP_NOWARN);
3215 if (!afinfo)
3216 return -ENOMEM;
3217
3218 afinfo->family = AF_UNSPEC;
3219 afinfo->udp_table = &udp_table;
3220 st->bpf_seq_afinfo = afinfo;
3221 ret = bpf_iter_init_seq_net(priv_data);
3222 if (ret)
3223 kfree(afinfo);
3224 return ret;
3225}
3226
3227static void bpf_iter_fini_udp(void *priv_data)
3228{
3229 struct udp_iter_state *st = priv_data;
3230
3231 kfree(st->bpf_seq_afinfo);
3232 bpf_iter_fini_seq_net(priv_data);
3233}
3234
3235static const struct bpf_iter_reg udp_reg_info = {
3236 .target = "udp",
3237 .seq_ops = &bpf_iter_udp_seq_ops,
3238 .init_seq_private = bpf_iter_init_udp,
3239 .fini_seq_private = bpf_iter_fini_udp,
3240 .seq_priv_size = sizeof(struct udp_iter_state),
3241 .ctx_arg_info_size = 1,
3242 .ctx_arg_info = {
3243 { offsetof(struct bpf_iter__udp, udp_sk),
3244 PTR_TO_BTF_ID_OR_NULL },
3245 },
3246};
3247
3248static void __init bpf_iter_register(void)
3249{
3250 if (bpf_iter_reg_target(&udp_reg_info))
3251 pr_warn("Warning: could not register bpf iterator udp\n");
3252}
3253#endif
3254
95766fff
HA
3255void __init udp_init(void)
3256{
f03d78db 3257 unsigned long limit;
4b272750 3258 unsigned int i;
95766fff 3259
f86dcc5a 3260 udp_table_init(&udp_table, "UDP");
f03d78db 3261 limit = nr_free_buffer_pages() / 8;
95766fff
HA
3262 limit = max(limit, 128UL);
3263 sysctl_udp_mem[0] = limit / 4 * 3;
3264 sysctl_udp_mem[1] = limit;
3265 sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
3266
1e802951 3267 __udp_sysctl_init(&init_net);
4b272750
ED
3268
3269 /* 16 spinlocks per cpu */
3270 udp_busylocks_log = ilog2(nr_cpu_ids) + 4;
3271 udp_busylocks = kmalloc(sizeof(spinlock_t) << udp_busylocks_log,
3272 GFP_KERNEL);
3273 if (!udp_busylocks)
3274 panic("UDP: failed to alloc udp_busylocks\n");
3275 for (i = 0; i < (1U << udp_busylocks_log); i++)
3276 spin_lock_init(udp_busylocks + i);
1e802951
TZ
3277
3278 if (register_pernet_subsys(&udp_sysctl_ops))
3279 panic("UDP: failed to init sysctl parameters.\n");
5788b3a0
YS
3280
3281#if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
3282 bpf_iter_register();
3283#endif
95766fff 3284}