]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - net/ipv4/udp.c
udp: inuse checks can quit early for reuseport
[mirror_ubuntu-bionic-kernel.git] / net / ipv4 / udp.c
CommitLineData
1da177e4
LT
1/*
2 * INET An implementation of the TCP/IP protocol suite for the LINUX
3 * operating system. INET is implemented using the BSD Socket
4 * interface as the means of communication with the user level.
5 *
6 * The User Datagram Protocol (UDP).
7 *
02c30a84 8 * Authors: Ross Biro
1da177e4
LT
9 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
10 * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
113aa838 11 * Alan Cox, <alan@lxorguk.ukuu.org.uk>
1da177e4
LT
12 * Hirokazu Takahashi, <taka@valinux.co.jp>
13 *
14 * Fixes:
15 * Alan Cox : verify_area() calls
16 * Alan Cox : stopped close while in use off icmp
17 * messages. Not a fix but a botch that
18 * for udp at least is 'valid'.
19 * Alan Cox : Fixed icmp handling properly
20 * Alan Cox : Correct error for oversized datagrams
e905a9ed
YH
21 * Alan Cox : Tidied select() semantics.
22 * Alan Cox : udp_err() fixed properly, also now
1da177e4
LT
23 * select and read wake correctly on errors
24 * Alan Cox : udp_send verify_area moved to avoid mem leak
25 * Alan Cox : UDP can count its memory
26 * Alan Cox : send to an unknown connection causes
27 * an ECONNREFUSED off the icmp, but
28 * does NOT close.
29 * Alan Cox : Switched to new sk_buff handlers. No more backlog!
30 * Alan Cox : Using generic datagram code. Even smaller and the PEEK
31 * bug no longer crashes it.
32 * Fred Van Kempen : Net2e support for sk->broadcast.
33 * Alan Cox : Uses skb_free_datagram
34 * Alan Cox : Added get/set sockopt support.
35 * Alan Cox : Broadcasting without option set returns EACCES.
36 * Alan Cox : No wakeup calls. Instead we now use the callbacks.
37 * Alan Cox : Use ip_tos and ip_ttl
38 * Alan Cox : SNMP Mibs
39 * Alan Cox : MSG_DONTROUTE, and 0.0.0.0 support.
40 * Matt Dillon : UDP length checks.
41 * Alan Cox : Smarter af_inet used properly.
42 * Alan Cox : Use new kernel side addressing.
43 * Alan Cox : Incorrect return on truncated datagram receive.
44 * Arnt Gulbrandsen : New udp_send and stuff
45 * Alan Cox : Cache last socket
46 * Alan Cox : Route cache
47 * Jon Peatfield : Minor efficiency fix to sendto().
48 * Mike Shaver : RFC1122 checks.
49 * Alan Cox : Nonblocking error fix.
50 * Willy Konynenberg : Transparent proxying support.
51 * Mike McLagan : Routing by source
52 * David S. Miller : New socket lookup architecture.
53 * Last socket cache retained as it
54 * does have a high hit rate.
55 * Olaf Kirch : Don't linearise iovec on sendmsg.
56 * Andi Kleen : Some cleanups, cache destination entry
e905a9ed 57 * for connect.
1da177e4
LT
58 * Vitaly E. Lavrov : Transparent proxy revived after year coma.
59 * Melvin Smith : Check msg_name not msg_namelen in sendto(),
60 * return ENOTCONN for unconnected sockets (POSIX)
61 * Janos Farkas : don't deliver multi/broadcasts to a different
62 * bound-to-device socket
63 * Hirokazu Takahashi : HW checksumming for outgoing UDP
64 * datagrams.
65 * Hirokazu Takahashi : sendfile() on UDP works now.
66 * Arnaldo C. Melo : convert /proc/net/udp to seq_file
67 * YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which
68 * Alexey Kuznetsov: allow both IPv4 and IPv6 sockets to bind
69 * a single port at the same time.
70 * Derek Atkins <derek@ihtfp.com>: Add Encapulation Support
342f0234 71 * James Chapman : Add L2TP encapsulation type.
1da177e4
LT
72 *
73 *
74 * This program is free software; you can redistribute it and/or
75 * modify it under the terms of the GNU General Public License
76 * as published by the Free Software Foundation; either version
77 * 2 of the License, or (at your option) any later version.
78 */
e905a9ed 79
afd46503
JP
80#define pr_fmt(fmt) "UDP: " fmt
81
7c0f6ba6 82#include <linux/uaccess.h>
1da177e4 83#include <asm/ioctls.h>
95766fff 84#include <linux/bootmem.h>
8203efb3
ED
85#include <linux/highmem.h>
86#include <linux/swap.h>
1da177e4
LT
87#include <linux/types.h>
88#include <linux/fcntl.h>
89#include <linux/module.h>
90#include <linux/socket.h>
91#include <linux/sockios.h>
14c85021 92#include <linux/igmp.h>
6e540309 93#include <linux/inetdevice.h>
1da177e4
LT
94#include <linux/in.h>
95#include <linux/errno.h>
96#include <linux/timer.h>
97#include <linux/mm.h>
1da177e4 98#include <linux/inet.h>
1da177e4 99#include <linux/netdevice.h>
5a0e3ad6 100#include <linux/slab.h>
c752f073 101#include <net/tcp_states.h>
1da177e4
LT
102#include <linux/skbuff.h>
103#include <linux/proc_fs.h>
104#include <linux/seq_file.h>
457c4cbc 105#include <net/net_namespace.h>
1da177e4 106#include <net/icmp.h>
421b3885 107#include <net/inet_hashtables.h>
1da177e4 108#include <net/route.h>
1da177e4
LT
109#include <net/checksum.h>
110#include <net/xfrm.h>
296f7ea7 111#include <trace/events/udp.h>
447167bf 112#include <linux/static_key.h>
22911fc5 113#include <trace/events/skb.h>
076bb0c8 114#include <net/busy_poll.h>
ba4e58ec 115#include "udp_impl.h"
e32ea7e7 116#include <net/sock_reuseport.h>
217375a0 117#include <net/addrconf.h>
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
ED
124
125int sysctl_udp_rmem_min __read_mostly;
95766fff 126EXPORT_SYMBOL(sysctl_udp_rmem_min);
c482c568
ED
127
128int sysctl_udp_wmem_min __read_mostly;
95766fff
HA
129EXPORT_SYMBOL(sysctl_udp_wmem_min);
130
8d987e5c 131atomic_long_t udp_memory_allocated;
95766fff
HA
132EXPORT_SYMBOL(udp_memory_allocated);
133
f86dcc5a
ED
134#define MAX_UDP_PORTS 65536
135#define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN)
98322f22 136
f24d43c0 137static int udp_lib_lport_inuse(struct net *net, __u16 num,
645ca708 138 const struct udp_hslot *hslot,
98322f22 139 unsigned long *bitmap,
f24d43c0
ED
140 struct sock *sk,
141 int (*saddr_comp)(const struct sock *sk1,
e32ea7e7
CG
142 const struct sock *sk2,
143 bool match_wildcard),
f86dcc5a 144 unsigned int log)
1da177e4 145{
f24d43c0 146 struct sock *sk2;
ba418fa3 147 kuid_t uid = sock_i_uid(sk);
25030a7f 148
ca065d0c 149 sk_for_each(sk2, &hslot->head) {
9d4fb27d
JP
150 if (net_eq(sock_net(sk2), net) &&
151 sk2 != sk &&
d4cada4a 152 (bitmap || udp_sk(sk2)->udp_port_hash == num) &&
9d4fb27d
JP
153 (!sk2->sk_reuse || !sk->sk_reuse) &&
154 (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
155 sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
e32ea7e7 156 saddr_comp(sk, sk2, true)) {
df560056
EG
157 if (sk2->sk_reuseport && sk->sk_reuseport &&
158 !rcu_access_pointer(sk->sk_reuseport_cb) &&
159 uid_eq(uid, sock_i_uid(sk2))) {
160 if (!bitmap)
161 return 0;
162 } else {
163 if (!bitmap)
164 return 1;
165 __set_bit(udp_sk(sk2)->udp_port_hash >> log,
166 bitmap);
167 }
98322f22 168 }
4243cdc2 169 }
25030a7f
GR
170 return 0;
171}
172
30fff923
ED
173/*
174 * Note: we still hold spinlock of primary hash chain, so no other writer
175 * can insert/delete a socket with local_port == num
176 */
177static int udp_lib_lport_inuse2(struct net *net, __u16 num,
4243cdc2
JP
178 struct udp_hslot *hslot2,
179 struct sock *sk,
180 int (*saddr_comp)(const struct sock *sk1,
e32ea7e7
CG
181 const struct sock *sk2,
182 bool match_wildcard))
30fff923
ED
183{
184 struct sock *sk2;
ba418fa3 185 kuid_t uid = sock_i_uid(sk);
30fff923
ED
186 int res = 0;
187
188 spin_lock(&hslot2->lock);
ca065d0c 189 udp_portaddr_for_each_entry(sk2, &hslot2->head) {
9d4fb27d
JP
190 if (net_eq(sock_net(sk2), net) &&
191 sk2 != sk &&
192 (udp_sk(sk2)->udp_port_hash == num) &&
193 (!sk2->sk_reuse || !sk->sk_reuse) &&
194 (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
195 sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
e32ea7e7 196 saddr_comp(sk, sk2, true)) {
df560056
EG
197 if (sk2->sk_reuseport && sk->sk_reuseport &&
198 !rcu_access_pointer(sk->sk_reuseport_cb) &&
199 uid_eq(uid, sock_i_uid(sk2))) {
200 res = 0;
201 } else {
202 res = 1;
203 }
30fff923
ED
204 break;
205 }
4243cdc2 206 }
30fff923
ED
207 spin_unlock(&hslot2->lock);
208 return res;
209}
210
e32ea7e7
CG
211static int udp_reuseport_add_sock(struct sock *sk, struct udp_hslot *hslot,
212 int (*saddr_same)(const struct sock *sk1,
213 const struct sock *sk2,
214 bool match_wildcard))
215{
216 struct net *net = sock_net(sk);
e32ea7e7
CG
217 kuid_t uid = sock_i_uid(sk);
218 struct sock *sk2;
219
ca065d0c 220 sk_for_each(sk2, &hslot->head) {
e32ea7e7
CG
221 if (net_eq(sock_net(sk2), net) &&
222 sk2 != sk &&
223 sk2->sk_family == sk->sk_family &&
224 ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
225 (udp_sk(sk2)->udp_port_hash == udp_sk(sk)->udp_port_hash) &&
226 (sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
227 sk2->sk_reuseport && uid_eq(uid, sock_i_uid(sk2)) &&
228 (*saddr_same)(sk, sk2, false)) {
229 return reuseport_add_sock(sk, sk2);
230 }
231 }
232
233 /* Initial allocation may have already happened via setsockopt */
234 if (!rcu_access_pointer(sk->sk_reuseport_cb))
235 return reuseport_alloc(sk);
236 return 0;
237}
238
25030a7f 239/**
6ba5a3c5 240 * udp_lib_get_port - UDP/-Lite port lookup for IPv4 and IPv6
25030a7f
GR
241 *
242 * @sk: socket struct in question
243 * @snum: port number to look up
df2bc459 244 * @saddr_comp: AF-dependent comparison of bound local IP addresses
25985edc 245 * @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
30fff923 246 * with NULL address
25030a7f 247 */
6ba5a3c5 248int udp_lib_get_port(struct sock *sk, unsigned short snum,
4243cdc2 249 int (*saddr_comp)(const struct sock *sk1,
e32ea7e7
CG
250 const struct sock *sk2,
251 bool match_wildcard),
30fff923 252 unsigned int hash2_nulladdr)
25030a7f 253{
512615b6 254 struct udp_hslot *hslot, *hslot2;
645ca708 255 struct udp_table *udptable = sk->sk_prot->h.udp_table;
25030a7f 256 int error = 1;
3b1e0a65 257 struct net *net = sock_net(sk);
1da177e4 258
32c1da70 259 if (!snum) {
9088c560 260 int low, high, remaining;
95c96174 261 unsigned int rand;
98322f22
ED
262 unsigned short first, last;
263 DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
32c1da70 264
0bbf87d8 265 inet_get_local_port_range(net, &low, &high);
a25de534 266 remaining = (high - low) + 1;
227b60f5 267
63862b5b 268 rand = prandom_u32();
8fc54f68 269 first = reciprocal_scale(rand, remaining) + low;
98322f22
ED
270 /*
271 * force rand to be an odd multiple of UDP_HTABLE_SIZE
272 */
f86dcc5a 273 rand = (rand | 1) * (udptable->mask + 1);
5781b235
ED
274 last = first + udptable->mask + 1;
275 do {
f86dcc5a 276 hslot = udp_hashslot(udptable, net, first);
98322f22 277 bitmap_zero(bitmap, PORTS_PER_CHAIN);
645ca708 278 spin_lock_bh(&hslot->lock);
98322f22 279 udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
f86dcc5a 280 saddr_comp, udptable->log);
98322f22
ED
281
282 snum = first;
283 /*
284 * Iterate on all possible values of snum for this hash.
285 * Using steps of an odd multiple of UDP_HTABLE_SIZE
286 * give us randomization and full range coverage.
287 */
9088c560 288 do {
98322f22 289 if (low <= snum && snum <= high &&
e3826f1e 290 !test_bit(snum >> udptable->log, bitmap) &&
122ff243 291 !inet_is_local_reserved_port(net, snum))
98322f22
ED
292 goto found;
293 snum += rand;
294 } while (snum != first);
295 spin_unlock_bh(&hslot->lock);
df560056 296 cond_resched();
5781b235 297 } while (++first != last);
98322f22 298 goto fail;
645ca708 299 } else {
f86dcc5a 300 hslot = udp_hashslot(udptable, net, snum);
645ca708 301 spin_lock_bh(&hslot->lock);
30fff923
ED
302 if (hslot->count > 10) {
303 int exist;
304 unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
305
306 slot2 &= udptable->mask;
307 hash2_nulladdr &= udptable->mask;
308
309 hslot2 = udp_hashslot2(udptable, slot2);
310 if (hslot->count < hslot2->count)
311 goto scan_primary_hash;
312
313 exist = udp_lib_lport_inuse2(net, snum, hslot2,
314 sk, saddr_comp);
315 if (!exist && (hash2_nulladdr != slot2)) {
316 hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
317 exist = udp_lib_lport_inuse2(net, snum, hslot2,
318 sk, saddr_comp);
319 }
320 if (exist)
321 goto fail_unlock;
322 else
323 goto found;
324 }
325scan_primary_hash:
f86dcc5a
ED
326 if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk,
327 saddr_comp, 0))
645ca708
ED
328 goto fail_unlock;
329 }
98322f22 330found:
c720c7e8 331 inet_sk(sk)->inet_num = snum;
d4cada4a
ED
332 udp_sk(sk)->udp_port_hash = snum;
333 udp_sk(sk)->udp_portaddr_hash ^= snum;
1da177e4 334 if (sk_unhashed(sk)) {
e32ea7e7
CG
335 if (sk->sk_reuseport &&
336 udp_reuseport_add_sock(sk, hslot, saddr_comp)) {
337 inet_sk(sk)->inet_num = 0;
338 udp_sk(sk)->udp_port_hash = 0;
339 udp_sk(sk)->udp_portaddr_hash ^= snum;
340 goto fail_unlock;
341 }
342
ca065d0c 343 sk_add_node_rcu(sk, &hslot->head);
fdcc8aa9 344 hslot->count++;
c29a0bc4 345 sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
512615b6
ED
346
347 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
348 spin_lock(&hslot2->lock);
d894ba18 349 if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
1602f49b
DM
350 sk->sk_family == AF_INET6)
351 hlist_add_tail_rcu(&udp_sk(sk)->udp_portaddr_node,
352 &hslot2->head);
d894ba18 353 else
1602f49b
DM
354 hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
355 &hslot2->head);
512615b6
ED
356 hslot2->count++;
357 spin_unlock(&hslot2->lock);
1da177e4 358 }
ca065d0c 359 sock_set_flag(sk, SOCK_RCU_FREE);
25030a7f 360 error = 0;
645ca708
ED
361fail_unlock:
362 spin_unlock_bh(&hslot->lock);
1da177e4 363fail:
25030a7f
GR
364 return error;
365}
c482c568 366EXPORT_SYMBOL(udp_lib_get_port);
25030a7f 367
e32ea7e7
CG
368/* match_wildcard == true: 0.0.0.0 equals to any IPv4 addresses
369 * match_wildcard == false: addresses must be exactly the same, i.e.
370 * 0.0.0.0 only equals to 0.0.0.0
371 */
c125e80b
CG
372int ipv4_rcv_saddr_equal(const struct sock *sk1, const struct sock *sk2,
373 bool match_wildcard)
db8dac20
DM
374{
375 struct inet_sock *inet1 = inet_sk(sk1), *inet2 = inet_sk(sk2);
376
e32ea7e7
CG
377 if (!ipv6_only_sock(sk2)) {
378 if (inet1->inet_rcv_saddr == inet2->inet_rcv_saddr)
379 return 1;
380 if (!inet1->inet_rcv_saddr || !inet2->inet_rcv_saddr)
381 return match_wildcard;
382 }
383 return 0;
db8dac20
DM
384}
385
6eada011
ED
386static u32 udp4_portaddr_hash(const struct net *net, __be32 saddr,
387 unsigned int port)
d4cada4a 388{
0eae88f3 389 return jhash_1word((__force u32)saddr, net_hash_mix(net)) ^ port;
d4cada4a
ED
390}
391
6ba5a3c5 392int udp_v4_get_port(struct sock *sk, unsigned short snum)
db8dac20 393{
30fff923 394 unsigned int hash2_nulladdr =
0eae88f3 395 udp4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
30fff923
ED
396 unsigned int hash2_partial =
397 udp4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
398
d4cada4a 399 /* precompute partial secondary hash */
30fff923
ED
400 udp_sk(sk)->udp_portaddr_hash = hash2_partial;
401 return udp_lib_get_port(sk, snum, ipv4_rcv_saddr_equal, hash2_nulladdr);
db8dac20
DM
402}
403
d1e37288
SX
404static int compute_score(struct sock *sk, struct net *net,
405 __be32 saddr, __be16 sport,
406 __be32 daddr, unsigned short hnum, int dif)
645ca708 407{
60c04aec
JP
408 int score;
409 struct inet_sock *inet;
645ca708 410
60c04aec
JP
411 if (!net_eq(sock_net(sk), net) ||
412 udp_sk(sk)->udp_port_hash != hnum ||
413 ipv6_only_sock(sk))
414 return -1;
645ca708 415
60c04aec
JP
416 score = (sk->sk_family == PF_INET) ? 2 : 1;
417 inet = inet_sk(sk);
418
419 if (inet->inet_rcv_saddr) {
420 if (inet->inet_rcv_saddr != daddr)
421 return -1;
422 score += 4;
645ca708 423 }
60c04aec
JP
424
425 if (inet->inet_daddr) {
426 if (inet->inet_daddr != saddr)
427 return -1;
428 score += 4;
429 }
430
431 if (inet->inet_dport) {
432 if (inet->inet_dport != sport)
433 return -1;
434 score += 4;
435 }
436
437 if (sk->sk_bound_dev_if) {
438 if (sk->sk_bound_dev_if != dif)
439 return -1;
440 score += 4;
441 }
70da268b
ED
442 if (sk->sk_incoming_cpu == raw_smp_processor_id())
443 score++;
645ca708
ED
444 return score;
445}
446
6eada011
ED
447static u32 udp_ehashfn(const struct net *net, const __be32 laddr,
448 const __u16 lport, const __be32 faddr,
449 const __be16 fport)
65cd8033 450{
1bbdceef
HFS
451 static u32 udp_ehash_secret __read_mostly;
452
453 net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret));
454
65cd8033 455 return __inet_ehashfn(laddr, lport, faddr, fport,
1bbdceef 456 udp_ehash_secret + net_hash_mix(net));
65cd8033
HFS
457}
458
d1e37288 459/* called with rcu_read_lock() */
5051ebd2
ED
460static struct sock *udp4_lib_lookup2(struct net *net,
461 __be32 saddr, __be16 sport,
462 __be32 daddr, unsigned int hnum, int dif,
d1e37288 463 struct udp_hslot *hslot2,
1134158b 464 struct sk_buff *skb)
5051ebd2
ED
465{
466 struct sock *sk, *result;
ba418fa3
TH
467 int score, badness, matches = 0, reuseport = 0;
468 u32 hash = 0;
5051ebd2 469
5051ebd2 470 result = NULL;
ba418fa3 471 badness = 0;
ca065d0c 472 udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
d1e37288 473 score = compute_score(sk, net, saddr, sport,
5051ebd2
ED
474 daddr, hnum, dif);
475 if (score > badness) {
ba418fa3
TH
476 reuseport = sk->sk_reuseport;
477 if (reuseport) {
65cd8033
HFS
478 hash = udp_ehashfn(net, daddr, hnum,
479 saddr, sport);
ca065d0c 480 result = reuseport_select_sock(sk, hash, skb,
ed0dfffd 481 sizeof(struct udphdr));
ca065d0c
ED
482 if (result)
483 return result;
ba418fa3
TH
484 matches = 1;
485 }
ca065d0c
ED
486 badness = score;
487 result = sk;
ba418fa3
TH
488 } else if (score == badness && reuseport) {
489 matches++;
8fc54f68 490 if (reciprocal_scale(hash, matches) == 0)
ba418fa3
TH
491 result = sk;
492 hash = next_pseudo_random32(hash);
5051ebd2
ED
493 }
494 }
5051ebd2
ED
495 return result;
496}
497
db8dac20
DM
498/* UDP is nearly always wildcards out the wazoo, it makes no sense to try
499 * harder than this. -DaveM
500 */
fce82338 501struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
db8dac20 502 __be16 sport, __be32 daddr, __be16 dport,
538950a1 503 int dif, struct udp_table *udptable, struct sk_buff *skb)
db8dac20 504{
271b72c7 505 struct sock *sk, *result;
db8dac20 506 unsigned short hnum = ntohs(dport);
5051ebd2
ED
507 unsigned int hash2, slot2, slot = udp_hashfn(net, hnum, udptable->mask);
508 struct udp_hslot *hslot2, *hslot = &udptable->hash[slot];
ba418fa3
TH
509 int score, badness, matches = 0, reuseport = 0;
510 u32 hash = 0;
645ca708 511
5051ebd2
ED
512 if (hslot->count > 10) {
513 hash2 = udp4_portaddr_hash(net, daddr, hnum);
514 slot2 = hash2 & udptable->mask;
515 hslot2 = &udptable->hash2[slot2];
516 if (hslot->count < hslot2->count)
517 goto begin;
518
519 result = udp4_lib_lookup2(net, saddr, sport,
520 daddr, hnum, dif,
d1e37288 521 hslot2, skb);
5051ebd2 522 if (!result) {
d1e37288 523 unsigned int old_slot2 = slot2;
0eae88f3 524 hash2 = udp4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
5051ebd2 525 slot2 = hash2 & udptable->mask;
d1e37288
SX
526 /* avoid searching the same slot again. */
527 if (unlikely(slot2 == old_slot2))
528 return result;
529
5051ebd2
ED
530 hslot2 = &udptable->hash2[slot2];
531 if (hslot->count < hslot2->count)
532 goto begin;
533
1223c67c 534 result = udp4_lib_lookup2(net, saddr, sport,
d1e37288
SX
535 daddr, hnum, dif,
536 hslot2, skb);
5051ebd2 537 }
5051ebd2
ED
538 return result;
539 }
271b72c7
ED
540begin:
541 result = NULL;
ba418fa3 542 badness = 0;
ca065d0c 543 sk_for_each_rcu(sk, &hslot->head) {
d1e37288
SX
544 score = compute_score(sk, net, saddr, sport,
545 daddr, hnum, dif);
645ca708 546 if (score > badness) {
ba418fa3
TH
547 reuseport = sk->sk_reuseport;
548 if (reuseport) {
65cd8033
HFS
549 hash = udp_ehashfn(net, daddr, hnum,
550 saddr, sport);
ca065d0c 551 result = reuseport_select_sock(sk, hash, skb,
538950a1 552 sizeof(struct udphdr));
ca065d0c
ED
553 if (result)
554 return result;
ba418fa3
TH
555 matches = 1;
556 }
ca065d0c
ED
557 result = sk;
558 badness = score;
ba418fa3
TH
559 } else if (score == badness && reuseport) {
560 matches++;
8fc54f68 561 if (reciprocal_scale(hash, matches) == 0)
ba418fa3
TH
562 result = sk;
563 hash = next_pseudo_random32(hash);
db8dac20
DM
564 }
565 }
db8dac20
DM
566 return result;
567}
fce82338 568EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
db8dac20 569
607c4aaf
KK
570static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
571 __be16 sport, __be16 dport,
645ca708 572 struct udp_table *udptable)
607c4aaf
KK
573{
574 const struct iphdr *iph = ip_hdr(skb);
575
ed7cbbce 576 return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
8afdd99a 577 iph->daddr, dport, inet_iif(skb),
538950a1 578 udptable, skb);
607c4aaf
KK
579}
580
63058308
TH
581struct sock *udp4_lib_lookup_skb(struct sk_buff *skb,
582 __be16 sport, __be16 dport)
583{
ed7cbbce 584 return __udp4_lib_lookup_skb(skb, sport, dport, &udp_table);
63058308
TH
585}
586EXPORT_SYMBOL_GPL(udp4_lib_lookup_skb);
587
ca065d0c
ED
588/* Must be called under rcu_read_lock().
589 * Does increment socket refcount.
590 */
591#if IS_ENABLED(CONFIG_NETFILTER_XT_MATCH_SOCKET) || \
30f58158
AB
592 IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TPROXY) || \
593 IS_ENABLED(CONFIG_NF_SOCKET_IPV4)
bcd41303
KK
594struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
595 __be32 daddr, __be16 dport, int dif)
596{
ca065d0c
ED
597 struct sock *sk;
598
599 sk = __udp4_lib_lookup(net, saddr, sport, daddr, dport,
600 dif, &udp_table, NULL);
601 if (sk && !atomic_inc_not_zero(&sk->sk_refcnt))
602 sk = NULL;
603 return sk;
bcd41303
KK
604}
605EXPORT_SYMBOL_GPL(udp4_lib_lookup);
ca065d0c 606#endif
bcd41303 607
421b3885
SB
608static inline bool __udp_is_mcast_sock(struct net *net, struct sock *sk,
609 __be16 loc_port, __be32 loc_addr,
610 __be16 rmt_port, __be32 rmt_addr,
611 int dif, unsigned short hnum)
612{
613 struct inet_sock *inet = inet_sk(sk);
614
615 if (!net_eq(sock_net(sk), net) ||
616 udp_sk(sk)->udp_port_hash != hnum ||
617 (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
618 (inet->inet_dport != rmt_port && inet->inet_dport) ||
619 (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) ||
620 ipv6_only_sock(sk) ||
621 (sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif))
622 return false;
623 if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif))
624 return false;
625 return true;
626}
627
db8dac20
DM
628/*
629 * This routine is called by the ICMP module when it gets some
630 * sort of error condition. If err < 0 then the socket should
631 * be closed and the error returned to the user. If err > 0
632 * it's just the icmp type << 8 | icmp code.
633 * Header points to the ip header of the error packet. We move
634 * on past this. Then (as it used to claim before adjustment)
635 * header points to the first 8 bytes of the udp header. We need
636 * to find the appropriate port.
637 */
638
645ca708 639void __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
db8dac20
DM
640{
641 struct inet_sock *inet;
b71d1d42 642 const struct iphdr *iph = (const struct iphdr *)skb->data;
c482c568 643 struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
db8dac20
DM
644 const int type = icmp_hdr(skb)->type;
645 const int code = icmp_hdr(skb)->code;
646 struct sock *sk;
647 int harderr;
648 int err;
fd54d716 649 struct net *net = dev_net(skb->dev);
db8dac20 650
fd54d716 651 sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
538950a1
CG
652 iph->saddr, uh->source, skb->dev->ifindex, udptable,
653 NULL);
51456b29 654 if (!sk) {
5d3848bc 655 __ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
db8dac20
DM
656 return; /* No socket for error */
657 }
658
659 err = 0;
660 harderr = 0;
661 inet = inet_sk(sk);
662
663 switch (type) {
664 default:
665 case ICMP_TIME_EXCEEDED:
666 err = EHOSTUNREACH;
667 break;
668 case ICMP_SOURCE_QUENCH:
669 goto out;
670 case ICMP_PARAMETERPROB:
671 err = EPROTO;
672 harderr = 1;
673 break;
674 case ICMP_DEST_UNREACH:
675 if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
36393395 676 ipv4_sk_update_pmtu(skb, sk, info);
db8dac20
DM
677 if (inet->pmtudisc != IP_PMTUDISC_DONT) {
678 err = EMSGSIZE;
679 harderr = 1;
680 break;
681 }
682 goto out;
683 }
684 err = EHOSTUNREACH;
685 if (code <= NR_ICMP_UNREACH) {
686 harderr = icmp_err_convert[code].fatal;
687 err = icmp_err_convert[code].errno;
688 }
689 break;
55be7a9c
DM
690 case ICMP_REDIRECT:
691 ipv4_sk_redirect(skb, sk);
1a462d18 692 goto out;
db8dac20
DM
693 }
694
695 /*
696 * RFC1122: OK. Passes ICMP errors back to application, as per
697 * 4.1.3.3.
698 */
699 if (!inet->recverr) {
700 if (!harderr || sk->sk_state != TCP_ESTABLISHED)
701 goto out;
b1faf566 702 } else
c482c568 703 ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
b1faf566 704
db8dac20
DM
705 sk->sk_err = err;
706 sk->sk_error_report(sk);
707out:
ca065d0c 708 return;
db8dac20
DM
709}
710
711void udp_err(struct sk_buff *skb, u32 info)
712{
645ca708 713 __udp4_lib_err(skb, info, &udp_table);
db8dac20
DM
714}
715
716/*
717 * Throw away all pending data and cancel the corking. Socket is locked.
718 */
36d926b9 719void udp_flush_pending_frames(struct sock *sk)
db8dac20
DM
720{
721 struct udp_sock *up = udp_sk(sk);
722
723 if (up->pending) {
724 up->len = 0;
725 up->pending = 0;
726 ip_flush_pending_frames(sk);
727 }
728}
36d926b9 729EXPORT_SYMBOL(udp_flush_pending_frames);
db8dac20
DM
730
731/**
f6b9664f 732 * udp4_hwcsum - handle outgoing HW checksumming
db8dac20
DM
733 * @skb: sk_buff containing the filled-in UDP header
734 * (checksum field must be zeroed out)
f6b9664f
HX
735 * @src: source IP address
736 * @dst: destination IP address
db8dac20 737 */
c26bf4a5 738void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
db8dac20 739{
db8dac20 740 struct udphdr *uh = udp_hdr(skb);
f6b9664f
HX
741 int offset = skb_transport_offset(skb);
742 int len = skb->len - offset;
743 int hlen = len;
db8dac20
DM
744 __wsum csum = 0;
745
ebbe495f 746 if (!skb_has_frag_list(skb)) {
db8dac20
DM
747 /*
748 * Only one fragment on the socket.
749 */
750 skb->csum_start = skb_transport_header(skb) - skb->head;
751 skb->csum_offset = offsetof(struct udphdr, check);
f6b9664f
HX
752 uh->check = ~csum_tcpudp_magic(src, dst, len,
753 IPPROTO_UDP, 0);
db8dac20 754 } else {
ebbe495f
WC
755 struct sk_buff *frags;
756
db8dac20
DM
757 /*
758 * HW-checksum won't work as there are two or more
759 * fragments on the socket so that all csums of sk_buffs
760 * should be together
761 */
ebbe495f 762 skb_walk_frags(skb, frags) {
f6b9664f
HX
763 csum = csum_add(csum, frags->csum);
764 hlen -= frags->len;
ebbe495f 765 }
db8dac20 766
f6b9664f 767 csum = skb_checksum(skb, offset, hlen, csum);
db8dac20
DM
768 skb->ip_summed = CHECKSUM_NONE;
769
db8dac20
DM
770 uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
771 if (uh->check == 0)
772 uh->check = CSUM_MANGLED_0;
773 }
774}
c26bf4a5 775EXPORT_SYMBOL_GPL(udp4_hwcsum);
db8dac20 776
af5fcba7
TH
777/* Function to set UDP checksum for an IPv4 UDP packet. This is intended
778 * for the simple case like when setting the checksum for a UDP tunnel.
779 */
780void udp_set_csum(bool nocheck, struct sk_buff *skb,
781 __be32 saddr, __be32 daddr, int len)
782{
783 struct udphdr *uh = udp_hdr(skb);
784
179bc67f 785 if (nocheck) {
af5fcba7 786 uh->check = 0;
179bc67f 787 } else if (skb_is_gso(skb)) {
af5fcba7 788 uh->check = ~udp_v4_check(len, saddr, daddr, 0);
179bc67f
EC
789 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
790 uh->check = 0;
791 uh->check = udp_v4_check(len, saddr, daddr, lco_csum(skb));
792 if (uh->check == 0)
793 uh->check = CSUM_MANGLED_0;
d75f1306 794 } else {
af5fcba7
TH
795 skb->ip_summed = CHECKSUM_PARTIAL;
796 skb->csum_start = skb_transport_header(skb) - skb->head;
797 skb->csum_offset = offsetof(struct udphdr, check);
798 uh->check = ~udp_v4_check(len, saddr, daddr, 0);
af5fcba7
TH
799 }
800}
801EXPORT_SYMBOL(udp_set_csum);
802
79ab0531 803static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4)
db8dac20 804{
f6b9664f 805 struct sock *sk = skb->sk;
db8dac20 806 struct inet_sock *inet = inet_sk(sk);
db8dac20
DM
807 struct udphdr *uh;
808 int err = 0;
809 int is_udplite = IS_UDPLITE(sk);
f6b9664f
HX
810 int offset = skb_transport_offset(skb);
811 int len = skb->len - offset;
db8dac20
DM
812 __wsum csum = 0;
813
db8dac20
DM
814 /*
815 * Create a UDP header
816 */
817 uh = udp_hdr(skb);
f6b9664f 818 uh->source = inet->inet_sport;
79ab0531 819 uh->dest = fl4->fl4_dport;
f6b9664f 820 uh->len = htons(len);
db8dac20
DM
821 uh->check = 0;
822
823 if (is_udplite) /* UDP-Lite */
f6b9664f 824 csum = udplite_csum(skb);
db8dac20 825
28448b80 826 else if (sk->sk_no_check_tx) { /* UDP csum disabled */
db8dac20
DM
827
828 skb->ip_summed = CHECKSUM_NONE;
829 goto send;
830
831 } else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
832
79ab0531 833 udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
db8dac20
DM
834 goto send;
835
f6b9664f
HX
836 } else
837 csum = udp_csum(skb);
db8dac20
DM
838
839 /* add protocol-dependent pseudo-header */
79ab0531 840 uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
c482c568 841 sk->sk_protocol, csum);
db8dac20
DM
842 if (uh->check == 0)
843 uh->check = CSUM_MANGLED_0;
844
845send:
b5ec8eea 846 err = ip_send_skb(sock_net(sk), skb);
6ce9e7b5
ED
847 if (err) {
848 if (err == -ENOBUFS && !inet->recverr) {
6aef70a8
ED
849 UDP_INC_STATS(sock_net(sk),
850 UDP_MIB_SNDBUFERRORS, is_udplite);
6ce9e7b5
ED
851 err = 0;
852 }
853 } else
6aef70a8
ED
854 UDP_INC_STATS(sock_net(sk),
855 UDP_MIB_OUTDATAGRAMS, is_udplite);
f6b9664f
HX
856 return err;
857}
858
859/*
860 * Push out all pending data as one UDP datagram. Socket is locked.
861 */
8822b64a 862int udp_push_pending_frames(struct sock *sk)
f6b9664f
HX
863{
864 struct udp_sock *up = udp_sk(sk);
865 struct inet_sock *inet = inet_sk(sk);
b6f21b26 866 struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
f6b9664f
HX
867 struct sk_buff *skb;
868 int err = 0;
869
77968b78 870 skb = ip_finish_skb(sk, fl4);
f6b9664f
HX
871 if (!skb)
872 goto out;
873
79ab0531 874 err = udp_send_skb(skb, fl4);
f6b9664f 875
db8dac20
DM
876out:
877 up->len = 0;
878 up->pending = 0;
db8dac20
DM
879 return err;
880}
8822b64a 881EXPORT_SYMBOL(udp_push_pending_frames);
db8dac20 882
1b784140 883int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
db8dac20
DM
884{
885 struct inet_sock *inet = inet_sk(sk);
886 struct udp_sock *up = udp_sk(sk);
e474995f 887 struct flowi4 fl4_stack;
b6f21b26 888 struct flowi4 *fl4;
db8dac20
DM
889 int ulen = len;
890 struct ipcm_cookie ipc;
891 struct rtable *rt = NULL;
892 int free = 0;
893 int connected = 0;
894 __be32 daddr, faddr, saddr;
895 __be16 dport;
896 u8 tos;
897 int err, is_udplite = IS_UDPLITE(sk);
898 int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
899 int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
903ab86d 900 struct sk_buff *skb;
f6d8bd05 901 struct ip_options_data opt_copy;
db8dac20
DM
902
903 if (len > 0xFFFF)
904 return -EMSGSIZE;
905
906 /*
907 * Check the flags.
908 */
909
c482c568 910 if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
db8dac20
DM
911 return -EOPNOTSUPP;
912
913 ipc.opt = NULL;
2244d07b 914 ipc.tx_flags = 0;
aa661581
FF
915 ipc.ttl = 0;
916 ipc.tos = -1;
db8dac20 917
903ab86d
HX
918 getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
919
f5fca608 920 fl4 = &inet->cork.fl.u.ip4;
db8dac20
DM
921 if (up->pending) {
922 /*
923 * There are pending frames.
924 * The socket lock must be held while it's corked.
925 */
926 lock_sock(sk);
927 if (likely(up->pending)) {
928 if (unlikely(up->pending != AF_INET)) {
929 release_sock(sk);
930 return -EINVAL;
931 }
932 goto do_append_data;
933 }
934 release_sock(sk);
935 }
936 ulen += sizeof(struct udphdr);
937
938 /*
939 * Get and verify the address.
940 */
941 if (msg->msg_name) {
342dfc30 942 DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
db8dac20
DM
943 if (msg->msg_namelen < sizeof(*usin))
944 return -EINVAL;
945 if (usin->sin_family != AF_INET) {
946 if (usin->sin_family != AF_UNSPEC)
947 return -EAFNOSUPPORT;
948 }
949
950 daddr = usin->sin_addr.s_addr;
951 dport = usin->sin_port;
952 if (dport == 0)
953 return -EINVAL;
954 } else {
955 if (sk->sk_state != TCP_ESTABLISHED)
956 return -EDESTADDRREQ;
c720c7e8
ED
957 daddr = inet->inet_daddr;
958 dport = inet->inet_dport;
db8dac20
DM
959 /* Open fast path for connected socket.
960 Route will not be used, if at least one option is set.
961 */
962 connected = 1;
963 }
db8dac20 964
c14ac945
SHY
965 ipc.sockc.tsflags = sk->sk_tsflags;
966 ipc.addr = inet->inet_saddr;
db8dac20 967 ipc.oif = sk->sk_bound_dev_if;
bf84a010 968
db8dac20 969 if (msg->msg_controllen) {
24025c46 970 err = ip_cmsg_send(sk, msg, &ipc, sk->sk_family == AF_INET6);
91948309
ED
971 if (unlikely(err)) {
972 kfree(ipc.opt);
db8dac20 973 return err;
91948309 974 }
db8dac20
DM
975 if (ipc.opt)
976 free = 1;
977 connected = 0;
978 }
f6d8bd05
ED
979 if (!ipc.opt) {
980 struct ip_options_rcu *inet_opt;
981
982 rcu_read_lock();
983 inet_opt = rcu_dereference(inet->inet_opt);
984 if (inet_opt) {
985 memcpy(&opt_copy, inet_opt,
986 sizeof(*inet_opt) + inet_opt->opt.optlen);
987 ipc.opt = &opt_copy.opt;
988 }
989 rcu_read_unlock();
990 }
db8dac20
DM
991
992 saddr = ipc.addr;
993 ipc.addr = faddr = daddr;
994
c14ac945
SHY
995 sock_tx_timestamp(sk, ipc.sockc.tsflags, &ipc.tx_flags);
996
f6d8bd05 997 if (ipc.opt && ipc.opt->opt.srr) {
db8dac20
DM
998 if (!daddr)
999 return -EINVAL;
f6d8bd05 1000 faddr = ipc.opt->opt.faddr;
db8dac20
DM
1001 connected = 0;
1002 }
aa661581 1003 tos = get_rttos(&ipc, inet);
db8dac20
DM
1004 if (sock_flag(sk, SOCK_LOCALROUTE) ||
1005 (msg->msg_flags & MSG_DONTROUTE) ||
f6d8bd05 1006 (ipc.opt && ipc.opt->opt.is_strictroute)) {
db8dac20
DM
1007 tos |= RTO_ONLINK;
1008 connected = 0;
1009 }
1010
1011 if (ipv4_is_multicast(daddr)) {
1012 if (!ipc.oif)
1013 ipc.oif = inet->mc_index;
1014 if (!saddr)
1015 saddr = inet->mc_addr;
1016 connected = 0;
76e21053
EH
1017 } else if (!ipc.oif)
1018 ipc.oif = inet->uc_index;
db8dac20
DM
1019
1020 if (connected)
c482c568 1021 rt = (struct rtable *)sk_dst_check(sk, 0);
db8dac20 1022
51456b29 1023 if (!rt) {
84a3aa00 1024 struct net *net = sock_net(sk);
9a24abfa 1025 __u8 flow_flags = inet_sk_flowi_flags(sk);
84a3aa00 1026
e474995f 1027 fl4 = &fl4_stack;
9a24abfa 1028
e474995f 1029 flowi4_init_output(fl4, ipc.oif, sk->sk_mark, tos,
c0951cbc 1030 RT_SCOPE_UNIVERSE, sk->sk_protocol,
9a24abfa 1031 flow_flags,
e2d118a1
LC
1032 faddr, saddr, dport, inet->inet_sport,
1033 sk->sk_uid);
c0951cbc 1034
e474995f
DM
1035 security_sk_classify_flow(sk, flowi4_to_flowi(fl4));
1036 rt = ip_route_output_flow(net, fl4, sk);
b23dd4fe
DM
1037 if (IS_ERR(rt)) {
1038 err = PTR_ERR(rt);
06dc94b1 1039 rt = NULL;
db8dac20 1040 if (err == -ENETUNREACH)
f1d8cba6 1041 IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
db8dac20
DM
1042 goto out;
1043 }
1044
1045 err = -EACCES;
1046 if ((rt->rt_flags & RTCF_BROADCAST) &&
1047 !sock_flag(sk, SOCK_BROADCAST))
1048 goto out;
1049 if (connected)
d8d1f30b 1050 sk_dst_set(sk, dst_clone(&rt->dst));
db8dac20
DM
1051 }
1052
1053 if (msg->msg_flags&MSG_CONFIRM)
1054 goto do_confirm;
1055back_from_confirm:
1056
e474995f 1057 saddr = fl4->saddr;
db8dac20 1058 if (!ipc.addr)
e474995f 1059 daddr = ipc.addr = fl4->daddr;
db8dac20 1060
903ab86d
HX
1061 /* Lockless fast path for the non-corking case. */
1062 if (!corkreq) {
f69e6d13 1063 skb = ip_make_skb(sk, fl4, getfrag, msg, ulen,
903ab86d
HX
1064 sizeof(struct udphdr), &ipc, &rt,
1065 msg->msg_flags);
1066 err = PTR_ERR(skb);
50c3a487 1067 if (!IS_ERR_OR_NULL(skb))
79ab0531 1068 err = udp_send_skb(skb, fl4);
903ab86d
HX
1069 goto out;
1070 }
1071
db8dac20
DM
1072 lock_sock(sk);
1073 if (unlikely(up->pending)) {
1074 /* The socket is already corked while preparing it. */
1075 /* ... which is an evident application bug. --ANK */
1076 release_sock(sk);
1077
ba7a46f1 1078 net_dbg_ratelimited("cork app bug 2\n");
db8dac20
DM
1079 err = -EINVAL;
1080 goto out;
1081 }
1082 /*
1083 * Now cork the socket to pend data.
1084 */
b6f21b26
DM
1085 fl4 = &inet->cork.fl.u.ip4;
1086 fl4->daddr = daddr;
1087 fl4->saddr = saddr;
9cce96df
DM
1088 fl4->fl4_dport = dport;
1089 fl4->fl4_sport = inet->inet_sport;
db8dac20
DM
1090 up->pending = AF_INET;
1091
1092do_append_data:
1093 up->len += ulen;
f69e6d13 1094 err = ip_append_data(sk, fl4, getfrag, msg, ulen,
f5fca608
DM
1095 sizeof(struct udphdr), &ipc, &rt,
1096 corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
db8dac20
DM
1097 if (err)
1098 udp_flush_pending_frames(sk);
1099 else if (!corkreq)
1100 err = udp_push_pending_frames(sk);
1101 else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
1102 up->pending = 0;
1103 release_sock(sk);
1104
1105out:
1106 ip_rt_put(rt);
1107 if (free)
1108 kfree(ipc.opt);
1109 if (!err)
1110 return len;
1111 /*
1112 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting
1113 * ENOBUFS might not be good (it's not tunable per se), but otherwise
1114 * we don't have a good statistic (IpOutDiscards but it can be too many
1115 * things). We could add another new stat but at least for now that
1116 * seems like overkill.
1117 */
1118 if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
6aef70a8
ED
1119 UDP_INC_STATS(sock_net(sk),
1120 UDP_MIB_SNDBUFERRORS, is_udplite);
db8dac20
DM
1121 }
1122 return err;
1123
1124do_confirm:
d8d1f30b 1125 dst_confirm(&rt->dst);
db8dac20
DM
1126 if (!(msg->msg_flags&MSG_PROBE) || len)
1127 goto back_from_confirm;
1128 err = 0;
1129 goto out;
1130}
c482c568 1131EXPORT_SYMBOL(udp_sendmsg);
db8dac20
DM
1132
1133int udp_sendpage(struct sock *sk, struct page *page, int offset,
1134 size_t size, int flags)
1135{
f5fca608 1136 struct inet_sock *inet = inet_sk(sk);
db8dac20
DM
1137 struct udp_sock *up = udp_sk(sk);
1138 int ret;
1139
d3f7d56a
SL
1140 if (flags & MSG_SENDPAGE_NOTLAST)
1141 flags |= MSG_MORE;
1142
db8dac20
DM
1143 if (!up->pending) {
1144 struct msghdr msg = { .msg_flags = flags|MSG_MORE };
1145
1146 /* Call udp_sendmsg to specify destination address which
1147 * sendpage interface can't pass.
1148 * This will succeed only when the socket is connected.
1149 */
1b784140 1150 ret = udp_sendmsg(sk, &msg, 0);
db8dac20
DM
1151 if (ret < 0)
1152 return ret;
1153 }
1154
1155 lock_sock(sk);
1156
1157 if (unlikely(!up->pending)) {
1158 release_sock(sk);
1159
ba7a46f1 1160 net_dbg_ratelimited("udp cork app bug 3\n");
db8dac20
DM
1161 return -EINVAL;
1162 }
1163
f5fca608
DM
1164 ret = ip_append_page(sk, &inet->cork.fl.u.ip4,
1165 page, offset, size, flags);
db8dac20
DM
1166 if (ret == -EOPNOTSUPP) {
1167 release_sock(sk);
1168 return sock_no_sendpage(sk->sk_socket, page, offset,
1169 size, flags);
1170 }
1171 if (ret < 0) {
1172 udp_flush_pending_frames(sk);
1173 goto out;
1174 }
1175
1176 up->len += size;
1177 if (!(up->corkflag || (flags&MSG_MORE)))
1178 ret = udp_push_pending_frames(sk);
1179 if (!ret)
1180 ret = size;
1181out:
1182 release_sock(sk);
1183 return ret;
1184}
1185
7c13f97f 1186/* fully reclaim rmem/fwd memory allocated for skb */
f970bd9e
PA
1187static void udp_rmem_release(struct sock *sk, int size, int partial)
1188{
6b229cf7 1189 struct udp_sock *up = udp_sk(sk);
f970bd9e
PA
1190 int amt;
1191
6b229cf7
ED
1192 if (likely(partial)) {
1193 up->forward_deficit += size;
1194 size = up->forward_deficit;
1195 if (size < (sk->sk_rcvbuf >> 2) &&
1196 !skb_queue_empty(&sk->sk_receive_queue))
1197 return;
1198 } else {
1199 size += up->forward_deficit;
1200 }
1201 up->forward_deficit = 0;
1202
f970bd9e
PA
1203 sk->sk_forward_alloc += size;
1204 amt = (sk->sk_forward_alloc - partial) & ~(SK_MEM_QUANTUM - 1);
1205 sk->sk_forward_alloc -= amt;
f970bd9e
PA
1206
1207 if (amt)
1208 __sk_mem_reduce_allocated(sk, amt >> SK_MEM_QUANTUM_SHIFT);
02ab0d13
ED
1209
1210 atomic_sub(size, &sk->sk_rmem_alloc);
f970bd9e
PA
1211}
1212
c84d9490
ED
1213/* Note: called with sk_receive_queue.lock held.
1214 * Instead of using skb->truesize here, find a copy of it in skb->dev_scratch
1215 * This avoids a cache line miss while receive_queue lock is held.
1216 * Look at __udp_enqueue_schedule_skb() to find where this copy is done.
1217 */
7c13f97f 1218void udp_skb_destructor(struct sock *sk, struct sk_buff *skb)
f970bd9e 1219{
c84d9490 1220 udp_rmem_release(sk, skb->dev_scratch, 1);
f970bd9e 1221}
7c13f97f 1222EXPORT_SYMBOL(udp_skb_destructor);
f970bd9e 1223
4b272750
ED
1224/* Idea of busylocks is to let producers grab an extra spinlock
1225 * to relieve pressure on the receive_queue spinlock shared by consumer.
1226 * Under flood, this means that only one producer can be in line
1227 * trying to acquire the receive_queue spinlock.
1228 * These busylock can be allocated on a per cpu manner, instead of a
1229 * per socket one (that would consume a cache line per socket)
1230 */
1231static int udp_busylocks_log __read_mostly;
1232static spinlock_t *udp_busylocks __read_mostly;
1233
1234static spinlock_t *busylock_acquire(void *ptr)
1235{
1236 spinlock_t *busy;
1237
1238 busy = udp_busylocks + hash_ptr(ptr, udp_busylocks_log);
1239 spin_lock(busy);
1240 return busy;
1241}
1242
1243static void busylock_release(spinlock_t *busy)
1244{
1245 if (busy)
1246 spin_unlock(busy);
1247}
1248
f970bd9e
PA
1249int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb)
1250{
1251 struct sk_buff_head *list = &sk->sk_receive_queue;
1252 int rmem, delta, amt, err = -ENOMEM;
4b272750 1253 spinlock_t *busy = NULL;
c8c8b127 1254 int size;
f970bd9e
PA
1255
1256 /* try to avoid the costly atomic add/sub pair when the receive
1257 * queue is full; always allow at least a packet
1258 */
1259 rmem = atomic_read(&sk->sk_rmem_alloc);
363dc73a 1260 if (rmem > sk->sk_rcvbuf)
f970bd9e
PA
1261 goto drop;
1262
c8c8b127
ED
1263 /* Under mem pressure, it might be helpful to help udp_recvmsg()
1264 * having linear skbs :
1265 * - Reduce memory overhead and thus increase receive queue capacity
1266 * - Less cache line misses at copyout() time
1267 * - Less work at consume_skb() (less alien page frag freeing)
1268 */
4b272750 1269 if (rmem > (sk->sk_rcvbuf >> 1)) {
c8c8b127 1270 skb_condense(skb);
4b272750
ED
1271
1272 busy = busylock_acquire(sk);
1273 }
c8c8b127 1274 size = skb->truesize;
c84d9490
ED
1275 /* Copy skb->truesize into skb->dev_scratch to avoid a cache line miss
1276 * in udp_skb_destructor()
1277 */
1278 skb->dev_scratch = size;
c8c8b127 1279
f970bd9e
PA
1280 /* we drop only if the receive buf is full and the receive
1281 * queue contains some other skb
1282 */
1283 rmem = atomic_add_return(size, &sk->sk_rmem_alloc);
363dc73a 1284 if (rmem > (size + sk->sk_rcvbuf))
f970bd9e
PA
1285 goto uncharge_drop;
1286
1287 spin_lock(&list->lock);
1288 if (size >= sk->sk_forward_alloc) {
1289 amt = sk_mem_pages(size);
1290 delta = amt << SK_MEM_QUANTUM_SHIFT;
1291 if (!__sk_mem_raise_allocated(sk, delta, amt, SK_MEM_RECV)) {
1292 err = -ENOBUFS;
1293 spin_unlock(&list->lock);
1294 goto uncharge_drop;
1295 }
1296
1297 sk->sk_forward_alloc += delta;
1298 }
1299
1300 sk->sk_forward_alloc -= size;
1301
7c13f97f
PA
1302 /* no need to setup a destructor, we will explicitly release the
1303 * forward allocated memory on dequeue
1304 */
f970bd9e
PA
1305 sock_skb_set_dropcount(sk, skb);
1306
1307 __skb_queue_tail(list, skb);
1308 spin_unlock(&list->lock);
1309
1310 if (!sock_flag(sk, SOCK_DEAD))
1311 sk->sk_data_ready(sk);
1312
4b272750 1313 busylock_release(busy);
f970bd9e
PA
1314 return 0;
1315
1316uncharge_drop:
1317 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
1318
1319drop:
1320 atomic_inc(&sk->sk_drops);
4b272750 1321 busylock_release(busy);
f970bd9e
PA
1322 return err;
1323}
1324EXPORT_SYMBOL_GPL(__udp_enqueue_schedule_skb);
1325
c915fe13 1326void udp_destruct_sock(struct sock *sk)
f970bd9e
PA
1327{
1328 /* reclaim completely the forward allocated memory */
7c13f97f
PA
1329 unsigned int total = 0;
1330 struct sk_buff *skb;
1331
1332 while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
1333 total += skb->truesize;
1334 kfree_skb(skb);
1335 }
1336 udp_rmem_release(sk, total, 0);
1337
f970bd9e
PA
1338 inet_sock_destruct(sk);
1339}
c915fe13 1340EXPORT_SYMBOL_GPL(udp_destruct_sock);
f970bd9e
PA
1341
1342int udp_init_sock(struct sock *sk)
1343{
1344 sk->sk_destruct = udp_destruct_sock;
1345 return 0;
1346}
1347EXPORT_SYMBOL_GPL(udp_init_sock);
1348
1349void skb_consume_udp(struct sock *sk, struct sk_buff *skb, int len)
1350{
1351 if (unlikely(READ_ONCE(sk->sk_peek_off) >= 0)) {
1352 bool slow = lock_sock_fast(sk);
1353
1354 sk_peek_offset_bwd(sk, len);
1355 unlock_sock_fast(sk, slow);
1356 }
1357 consume_skb(skb);
1358}
1359EXPORT_SYMBOL_GPL(skb_consume_udp);
1360
85584672
ED
1361/**
1362 * first_packet_length - return length of first packet in receive queue
1363 * @sk: socket
1364 *
1365 * Drops all bad checksum frames, until a valid one is found.
e83c6744 1366 * Returns the length of found skb, or -1 if none is found.
85584672 1367 */
e83c6744 1368static int first_packet_length(struct sock *sk)
85584672 1369{
7c13f97f 1370 struct sk_buff_head *rcvq = &sk->sk_receive_queue;
85584672 1371 struct sk_buff *skb;
7c13f97f 1372 int total = 0;
e83c6744 1373 int res;
85584672 1374
85584672
ED
1375 spin_lock_bh(&rcvq->lock);
1376 while ((skb = skb_peek(rcvq)) != NULL &&
1377 udp_lib_checksum_complete(skb)) {
02c22347
ED
1378 __UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS,
1379 IS_UDPLITE(sk));
1380 __UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS,
1381 IS_UDPLITE(sk));
8edf19c2 1382 atomic_inc(&sk->sk_drops);
85584672 1383 __skb_unlink(skb, rcvq);
7c13f97f
PA
1384 total += skb->truesize;
1385 kfree_skb(skb);
85584672 1386 }
e83c6744 1387 res = skb ? skb->len : -1;
7c13f97f
PA
1388 if (total)
1389 udp_rmem_release(sk, total, 1);
85584672 1390 spin_unlock_bh(&rcvq->lock);
85584672
ED
1391 return res;
1392}
1393
1da177e4
LT
1394/*
1395 * IOCTL requests applicable to the UDP protocol
1396 */
e905a9ed 1397
1da177e4
LT
1398int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
1399{
6516c655
SH
1400 switch (cmd) {
1401 case SIOCOUTQ:
1da177e4 1402 {
31e6d363
ED
1403 int amount = sk_wmem_alloc_get(sk);
1404
6516c655
SH
1405 return put_user(amount, (int __user *)arg);
1406 }
1da177e4 1407
6516c655
SH
1408 case SIOCINQ:
1409 {
e83c6744 1410 int amount = max_t(int, 0, first_packet_length(sk));
6516c655 1411
6516c655
SH
1412 return put_user(amount, (int __user *)arg);
1413 }
1da177e4 1414
6516c655
SH
1415 default:
1416 return -ENOIOCTLCMD;
1da177e4 1417 }
6516c655
SH
1418
1419 return 0;
1da177e4 1420}
c482c568 1421EXPORT_SYMBOL(udp_ioctl);
1da177e4 1422
db8dac20
DM
1423/*
1424 * This should be easy, if there is something there we
1425 * return it, otherwise we block.
1426 */
1427
1b784140
YX
1428int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock,
1429 int flags, int *addr_len)
db8dac20
DM
1430{
1431 struct inet_sock *inet = inet_sk(sk);
342dfc30 1432 DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
db8dac20 1433 struct sk_buff *skb;
59c2cdae 1434 unsigned int ulen, copied;
627d2d6b 1435 int peeked, peeking, off;
db8dac20
DM
1436 int err;
1437 int is_udplite = IS_UDPLITE(sk);
197c949e 1438 bool checksum_valid = false;
db8dac20 1439
db8dac20 1440 if (flags & MSG_ERRQUEUE)
85fbaa75 1441 return ip_recv_error(sk, msg, len, addr_len);
db8dac20
DM
1442
1443try_again:
627d2d6b 1444 peeking = off = sk_peek_offset(sk, flags);
7c13f97f 1445 skb = __skb_recv_udp(sk, flags, noblock, &peeked, &off, &err);
db8dac20 1446 if (!skb)
627d2d6b 1447 return err;
db8dac20 1448
e6afc8ac 1449 ulen = skb->len;
59c2cdae 1450 copied = len;
627d2d6b 1451 if (copied > ulen - off)
1452 copied = ulen - off;
59c2cdae 1453 else if (copied < ulen)
db8dac20
DM
1454 msg->msg_flags |= MSG_TRUNC;
1455
1456 /*
1457 * If checksum is needed at all, try to do it while copying the
1458 * data. If the data is truncated, or if we only want a partial
1459 * coverage checksum (UDP-Lite), do it before the copy.
1460 */
1461
d21dbdfe
ED
1462 if (copied < ulen || peeking ||
1463 (is_udplite && UDP_SKB_CB(skb)->partial_cov)) {
197c949e
ED
1464 checksum_valid = !udp_lib_checksum_complete(skb);
1465 if (!checksum_valid)
db8dac20
DM
1466 goto csum_copy_err;
1467 }
1468
197c949e 1469 if (checksum_valid || skb_csum_unnecessary(skb))
627d2d6b 1470 err = skb_copy_datagram_msg(skb, off, msg, copied);
db8dac20 1471 else {
627d2d6b 1472 err = skb_copy_and_csum_datagram_msg(skb, off, msg);
db8dac20
DM
1473
1474 if (err == -EINVAL)
1475 goto csum_copy_err;
1476 }
1477
22911fc5 1478 if (unlikely(err)) {
979402b1
ED
1479 if (!peeked) {
1480 atomic_inc(&sk->sk_drops);
6aef70a8
ED
1481 UDP_INC_STATS(sock_net(sk),
1482 UDP_MIB_INERRORS, is_udplite);
979402b1 1483 }
850cbadd 1484 kfree_skb(skb);
627d2d6b 1485 return err;
22911fc5 1486 }
db8dac20
DM
1487
1488 if (!peeked)
6aef70a8
ED
1489 UDP_INC_STATS(sock_net(sk),
1490 UDP_MIB_INDATAGRAMS, is_udplite);
db8dac20 1491
3b885787 1492 sock_recv_ts_and_drops(msg, sk, skb);
db8dac20
DM
1493
1494 /* Copy the address. */
c482c568 1495 if (sin) {
db8dac20
DM
1496 sin->sin_family = AF_INET;
1497 sin->sin_port = udp_hdr(skb)->source;
1498 sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
1499 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
bceaa902 1500 *addr_len = sizeof(*sin);
db8dac20
DM
1501 }
1502 if (inet->cmsg_flags)
ad959036 1503 ip_cmsg_recv_offset(msg, sk, skb, sizeof(struct udphdr), off);
db8dac20 1504
59c2cdae 1505 err = copied;
db8dac20
DM
1506 if (flags & MSG_TRUNC)
1507 err = ulen;
1508
850cbadd 1509 skb_consume_udp(sk, skb, peeking ? -err : err);
db8dac20
DM
1510 return err;
1511
1512csum_copy_err:
850cbadd 1513 if (!__sk_queue_drop_skb(sk, skb, flags)) {
6aef70a8
ED
1514 UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
1515 UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
6a5dc9e5 1516 }
850cbadd 1517 kfree_skb(skb);
db8dac20 1518
beb39db5
ED
1519 /* starting over for a new packet, but check if we need to yield */
1520 cond_resched();
9cfaa8de 1521 msg->msg_flags &= ~MSG_TRUNC;
db8dac20
DM
1522 goto try_again;
1523}
1524
286c72de 1525int __udp_disconnect(struct sock *sk, int flags)
1da177e4
LT
1526{
1527 struct inet_sock *inet = inet_sk(sk);
1528 /*
1529 * 1003.1g - break association.
1530 */
e905a9ed 1531
1da177e4 1532 sk->sk_state = TCP_CLOSE;
c720c7e8
ED
1533 inet->inet_daddr = 0;
1534 inet->inet_dport = 0;
bdeab991 1535 sock_rps_reset_rxhash(sk);
1da177e4
LT
1536 sk->sk_bound_dev_if = 0;
1537 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
1538 inet_reset_saddr(sk);
1539
1540 if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
1541 sk->sk_prot->unhash(sk);
c720c7e8 1542 inet->inet_sport = 0;
1da177e4
LT
1543 }
1544 sk_dst_reset(sk);
1545 return 0;
1546}
286c72de
ED
1547EXPORT_SYMBOL(__udp_disconnect);
1548
1549int udp_disconnect(struct sock *sk, int flags)
1550{
1551 lock_sock(sk);
1552 __udp_disconnect(sk, flags);
1553 release_sock(sk);
1554 return 0;
1555}
c482c568 1556EXPORT_SYMBOL(udp_disconnect);
1da177e4 1557
645ca708
ED
1558void udp_lib_unhash(struct sock *sk)
1559{
723b4610
ED
1560 if (sk_hashed(sk)) {
1561 struct udp_table *udptable = sk->sk_prot->h.udp_table;
512615b6
ED
1562 struct udp_hslot *hslot, *hslot2;
1563
1564 hslot = udp_hashslot(udptable, sock_net(sk),
1565 udp_sk(sk)->udp_port_hash);
1566 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
645ca708 1567
723b4610 1568 spin_lock_bh(&hslot->lock);
e32ea7e7
CG
1569 if (rcu_access_pointer(sk->sk_reuseport_cb))
1570 reuseport_detach_sock(sk);
ca065d0c 1571 if (sk_del_node_init_rcu(sk)) {
fdcc8aa9 1572 hslot->count--;
c720c7e8 1573 inet_sk(sk)->inet_num = 0;
723b4610 1574 sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
512615b6
ED
1575
1576 spin_lock(&hslot2->lock);
ca065d0c 1577 hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
512615b6
ED
1578 hslot2->count--;
1579 spin_unlock(&hslot2->lock);
723b4610
ED
1580 }
1581 spin_unlock_bh(&hslot->lock);
645ca708 1582 }
645ca708
ED
1583}
1584EXPORT_SYMBOL(udp_lib_unhash);
1585
719f8358
ED
1586/*
1587 * inet_rcv_saddr was changed, we must rehash secondary hash
1588 */
1589void udp_lib_rehash(struct sock *sk, u16 newhash)
1590{
1591 if (sk_hashed(sk)) {
1592 struct udp_table *udptable = sk->sk_prot->h.udp_table;
1593 struct udp_hslot *hslot, *hslot2, *nhslot2;
1594
1595 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
1596 nhslot2 = udp_hashslot2(udptable, newhash);
1597 udp_sk(sk)->udp_portaddr_hash = newhash;
e32ea7e7
CG
1598
1599 if (hslot2 != nhslot2 ||
1600 rcu_access_pointer(sk->sk_reuseport_cb)) {
719f8358
ED
1601 hslot = udp_hashslot(udptable, sock_net(sk),
1602 udp_sk(sk)->udp_port_hash);
1603 /* we must lock primary chain too */
1604 spin_lock_bh(&hslot->lock);
e32ea7e7
CG
1605 if (rcu_access_pointer(sk->sk_reuseport_cb))
1606 reuseport_detach_sock(sk);
1607
1608 if (hslot2 != nhslot2) {
1609 spin_lock(&hslot2->lock);
ca065d0c 1610 hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
e32ea7e7
CG
1611 hslot2->count--;
1612 spin_unlock(&hslot2->lock);
1613
1614 spin_lock(&nhslot2->lock);
ca065d0c 1615 hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
e32ea7e7
CG
1616 &nhslot2->head);
1617 nhslot2->count++;
1618 spin_unlock(&nhslot2->lock);
1619 }
719f8358
ED
1620
1621 spin_unlock_bh(&hslot->lock);
1622 }
1623 }
1624}
1625EXPORT_SYMBOL(udp_lib_rehash);
1626
1627static void udp_v4_rehash(struct sock *sk)
1628{
1629 u16 new_hash = udp4_portaddr_hash(sock_net(sk),
1630 inet_sk(sk)->inet_rcv_saddr,
1631 inet_sk(sk)->inet_num);
1632 udp_lib_rehash(sk, new_hash);
1633}
1634
30c7be26 1635int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
93821778 1636{
fec5e652 1637 int rc;
766e9037 1638
005ec974 1639 if (inet_sk(sk)->inet_daddr) {
bdeab991 1640 sock_rps_save_rxhash(sk, skb);
005ec974 1641 sk_mark_napi_id(sk, skb);
2c8c56e1 1642 sk_incoming_cpu_update(sk);
e68b6e50
ED
1643 } else {
1644 sk_mark_napi_id_once(sk, skb);
005ec974 1645 }
fec5e652 1646
850cbadd 1647 rc = __udp_enqueue_schedule_skb(sk, skb);
766e9037
ED
1648 if (rc < 0) {
1649 int is_udplite = IS_UDPLITE(sk);
93821778 1650
93821778 1651 /* Note that an ENOMEM error is charged twice */
766e9037 1652 if (rc == -ENOMEM)
e61da9e2 1653 UDP_INC_STATS(sock_net(sk), UDP_MIB_RCVBUFERRORS,
02c22347 1654 is_udplite);
e61da9e2 1655 UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
766e9037 1656 kfree_skb(skb);
296f7ea7 1657 trace_udp_fail_queue_rcv_skb(rc, sk);
766e9037 1658 return -1;
93821778
HX
1659 }
1660
1661 return 0;
93821778
HX
1662}
1663
447167bf
ED
1664static struct static_key udp_encap_needed __read_mostly;
1665void udp_encap_enable(void)
1666{
1667 if (!static_key_enabled(&udp_encap_needed))
1668 static_key_slow_inc(&udp_encap_needed);
1669}
1670EXPORT_SYMBOL(udp_encap_enable);
1671
db8dac20
DM
1672/* returns:
1673 * -1: error
1674 * 0: success
1675 * >0: "udp encap" protocol resubmission
1676 *
1677 * Note that in the success and error cases, the skb is assumed to
1678 * have either been requeued or freed.
1679 */
c482c568 1680int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
db8dac20
DM
1681{
1682 struct udp_sock *up = udp_sk(sk);
db8dac20
DM
1683 int is_udplite = IS_UDPLITE(sk);
1684
1685 /*
1686 * Charge it to the socket, dropping if the queue is full.
1687 */
1688 if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
1689 goto drop;
1690 nf_reset(skb);
1691
447167bf 1692 if (static_key_false(&udp_encap_needed) && up->encap_type) {
0ad92ad0
ED
1693 int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
1694
db8dac20
DM
1695 /*
1696 * This is an encapsulation socket so pass the skb to
1697 * the socket's udp_encap_rcv() hook. Otherwise, just
1698 * fall through and pass this up the UDP socket.
1699 * up->encap_rcv() returns the following value:
1700 * =0 if skb was successfully passed to the encap
1701 * handler or was discarded by it.
1702 * >0 if skb should be passed on to UDP.
1703 * <0 if skb should be resubmitted as proto -N
1704 */
1705
1706 /* if we're overly short, let UDP handle it */
0ad92ad0 1707 encap_rcv = ACCESS_ONCE(up->encap_rcv);
e5aed006 1708 if (encap_rcv) {
db8dac20
DM
1709 int ret;
1710
0a80966b
TH
1711 /* Verify checksum before giving to encap */
1712 if (udp_lib_checksum_complete(skb))
1713 goto csum_error;
1714
0ad92ad0 1715 ret = encap_rcv(sk, skb);
db8dac20 1716 if (ret <= 0) {
02c22347
ED
1717 __UDP_INC_STATS(sock_net(sk),
1718 UDP_MIB_INDATAGRAMS,
1719 is_udplite);
db8dac20
DM
1720 return -ret;
1721 }
1722 }
1723
1724 /* FALLTHROUGH -- it's a UDP Packet */
1725 }
1726
1727 /*
1728 * UDP-Lite specific tests, ignored on UDP sockets
1729 */
1730 if ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) {
1731
1732 /*
1733 * MIB statistics other than incrementing the error count are
1734 * disabled for the following two types of errors: these depend
1735 * on the application settings, not on the functioning of the
1736 * protocol stack as such.
1737 *
1738 * RFC 3828 here recommends (sec 3.3): "There should also be a
1739 * way ... to ... at least let the receiving application block
1740 * delivery of packets with coverage values less than a value
1741 * provided by the application."
1742 */
1743 if (up->pcrlen == 0) { /* full coverage was set */
ba7a46f1
JP
1744 net_dbg_ratelimited("UDPLite: partial coverage %d while full coverage %d requested\n",
1745 UDP_SKB_CB(skb)->cscov, skb->len);
db8dac20
DM
1746 goto drop;
1747 }
1748 /* The next case involves violating the min. coverage requested
1749 * by the receiver. This is subtle: if receiver wants x and x is
1750 * greater than the buffersize/MTU then receiver will complain
1751 * that it wants x while sender emits packets of smaller size y.
1752 * Therefore the above ...()->partial_cov statement is essential.
1753 */
1754 if (UDP_SKB_CB(skb)->cscov < up->pcrlen) {
ba7a46f1
JP
1755 net_dbg_ratelimited("UDPLite: coverage %d too small, need min %d\n",
1756 UDP_SKB_CB(skb)->cscov, up->pcrlen);
db8dac20
DM
1757 goto drop;
1758 }
1759 }
1760
ce25d66a
ED
1761 if (rcu_access_pointer(sk->sk_filter) &&
1762 udp_lib_checksum_complete(skb))
e6afc8ac 1763 goto csum_error;
ce25d66a 1764
ba66bbe5 1765 if (sk_filter_trim_cap(sk, skb, sizeof(struct udphdr)))
a6127697 1766 goto drop;
db8dac20 1767
e6afc8ac 1768 udp_csum_pull_header(skb);
db8dac20 1769
fbf8866d 1770 ipv4_pktinfo_prepare(sk, skb);
850cbadd 1771 return __udp_queue_rcv_skb(sk, skb);
db8dac20 1772
6a5dc9e5 1773csum_error:
02c22347 1774 __UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
db8dac20 1775drop:
02c22347 1776 __UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
8edf19c2 1777 atomic_inc(&sk->sk_drops);
db8dac20
DM
1778 kfree_skb(skb);
1779 return -1;
1780}
1781
97502231 1782/* For TCP sockets, sk_rx_dst is protected by socket lock
e47eb5df 1783 * For UDP, we use xchg() to guard against concurrent changes.
97502231
ED
1784 */
1785static void udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
421b3885 1786{
97502231
ED
1787 struct dst_entry *old;
1788
e47eb5df
ED
1789 dst_hold(dst);
1790 old = xchg(&sk->sk_rx_dst, dst);
1791 dst_release(old);
421b3885
SB
1792}
1793
db8dac20
DM
1794/*
1795 * Multicasts and broadcasts go to each listener.
1796 *
1240d137 1797 * Note: called only from the BH handler context.
db8dac20 1798 */
e3163493 1799static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
db8dac20
DM
1800 struct udphdr *uh,
1801 __be32 saddr, __be32 daddr,
36cbb245
RJ
1802 struct udp_table *udptable,
1803 int proto)
db8dac20 1804{
ca065d0c 1805 struct sock *sk, *first = NULL;
5cf3d461
DH
1806 unsigned short hnum = ntohs(uh->dest);
1807 struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum);
2dc41cff 1808 unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10);
ca065d0c
ED
1809 unsigned int offset = offsetof(typeof(*sk), sk_node);
1810 int dif = skb->dev->ifindex;
1811 struct hlist_node *node;
1812 struct sk_buff *nskb;
2dc41cff
DH
1813
1814 if (use_hash2) {
1815 hash2_any = udp4_portaddr_hash(net, htonl(INADDR_ANY), hnum) &
73e2d5e3
PN
1816 udptable->mask;
1817 hash2 = udp4_portaddr_hash(net, daddr, hnum) & udptable->mask;
2dc41cff 1818start_lookup:
73e2d5e3 1819 hslot = &udptable->hash2[hash2];
2dc41cff
DH
1820 offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
1821 }
db8dac20 1822
ca065d0c
ED
1823 sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
1824 if (!__udp_is_mcast_sock(net, sk, uh->dest, daddr,
1825 uh->source, saddr, dif, hnum))
1826 continue;
1827
1828 if (!first) {
1829 first = sk;
1830 continue;
1240d137 1831 }
ca065d0c 1832 nskb = skb_clone(skb, GFP_ATOMIC);
1240d137 1833
ca065d0c
ED
1834 if (unlikely(!nskb)) {
1835 atomic_inc(&sk->sk_drops);
02c22347
ED
1836 __UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS,
1837 IS_UDPLITE(sk));
1838 __UDP_INC_STATS(net, UDP_MIB_INERRORS,
1839 IS_UDPLITE(sk));
ca065d0c
ED
1840 continue;
1841 }
1842 if (udp_queue_rcv_skb(sk, nskb) > 0)
1843 consume_skb(nskb);
1844 }
1240d137 1845
2dc41cff
DH
1846 /* Also lookup *:port if we are using hash2 and haven't done so yet. */
1847 if (use_hash2 && hash2 != hash2_any) {
1848 hash2 = hash2_any;
1849 goto start_lookup;
1850 }
1851
ca065d0c
ED
1852 if (first) {
1853 if (udp_queue_rcv_skb(first, skb) > 0)
1854 consume_skb(skb);
1240d137 1855 } else {
ca065d0c 1856 kfree_skb(skb);
02c22347
ED
1857 __UDP_INC_STATS(net, UDP_MIB_IGNOREDMULTI,
1858 proto == IPPROTO_UDPLITE);
1240d137 1859 }
db8dac20
DM
1860 return 0;
1861}
1862
1863/* Initialize UDP checksum. If exited with zero value (success),
1864 * CHECKSUM_UNNECESSARY means, that no more checks are required.
1865 * Otherwise, csum completion requires chacksumming packet body,
1866 * including udp header and folding it to skb->csum.
1867 */
1868static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
1869 int proto)
1870{
db8dac20
DM
1871 int err;
1872
1873 UDP_SKB_CB(skb)->partial_cov = 0;
1874 UDP_SKB_CB(skb)->cscov = skb->len;
1875
1876 if (proto == IPPROTO_UDPLITE) {
1877 err = udplite_checksum_init(skb, uh);
1878 if (err)
1879 return err;
1880 }
1881
b46d9f62
HFS
1882 /* Note, we are only interested in != 0 or == 0, thus the
1883 * force to int.
1884 */
1885 return (__force int)skb_checksum_init_zero_check(skb, proto, uh->check,
1886 inet_compute_pseudo);
db8dac20
DM
1887}
1888
1889/*
1890 * All we need to do is get the socket, and then do a checksum.
1891 */
1892
645ca708 1893int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
db8dac20
DM
1894 int proto)
1895{
1896 struct sock *sk;
7b5e56f9 1897 struct udphdr *uh;
db8dac20 1898 unsigned short ulen;
adf30907 1899 struct rtable *rt = skb_rtable(skb);
2783ef23 1900 __be32 saddr, daddr;
0283328e 1901 struct net *net = dev_net(skb->dev);
db8dac20
DM
1902
1903 /*
1904 * Validate the packet.
1905 */
1906 if (!pskb_may_pull(skb, sizeof(struct udphdr)))
1907 goto drop; /* No space for header. */
1908
7b5e56f9 1909 uh = udp_hdr(skb);
db8dac20 1910 ulen = ntohs(uh->len);
ccc2d97c
BM
1911 saddr = ip_hdr(skb)->saddr;
1912 daddr = ip_hdr(skb)->daddr;
1913
db8dac20
DM
1914 if (ulen > skb->len)
1915 goto short_packet;
1916
1917 if (proto == IPPROTO_UDP) {
1918 /* UDP validates ulen. */
1919 if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
1920 goto short_packet;
1921 uh = udp_hdr(skb);
1922 }
1923
1924 if (udp4_csum_init(skb, uh, proto))
1925 goto csum_error;
1926
8afdd99a
ED
1927 sk = skb_steal_sock(skb);
1928 if (sk) {
97502231 1929 struct dst_entry *dst = skb_dst(skb);
421b3885 1930 int ret;
421b3885 1931
97502231
ED
1932 if (unlikely(sk->sk_rx_dst != dst))
1933 udp_sk_rx_dst_set(sk, dst);
db8dac20 1934
421b3885 1935 ret = udp_queue_rcv_skb(sk, skb);
8afdd99a 1936 sock_put(sk);
421b3885
SB
1937 /* a return value > 0 means to resubmit the input, but
1938 * it wants the return to be -protocol, or 0
1939 */
1940 if (ret > 0)
1941 return -ret;
1942 return 0;
421b3885 1943 }
db8dac20 1944
c18450a5
FF
1945 if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
1946 return __udp4_lib_mcast_deliver(net, skb, uh,
36cbb245 1947 saddr, daddr, udptable, proto);
c18450a5
FF
1948
1949 sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
00db4124 1950 if (sk) {
a5b50476
ET
1951 int ret;
1952
224d019c 1953 if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk))
2abb7cdc
TH
1954 skb_checksum_try_convert(skb, IPPROTO_UDP, uh->check,
1955 inet_compute_pseudo);
1956
a5b50476 1957 ret = udp_queue_rcv_skb(sk, skb);
db8dac20
DM
1958
1959 /* a return value > 0 means to resubmit the input, but
1960 * it wants the return to be -protocol, or 0
1961 */
1962 if (ret > 0)
1963 return -ret;
1964 return 0;
1965 }
1966
1967 if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
1968 goto drop;
1969 nf_reset(skb);
1970
1971 /* No socket. Drop packet silently, if checksum is wrong */
1972 if (udp_lib_checksum_complete(skb))
1973 goto csum_error;
1974
02c22347 1975 __UDP_INC_STATS(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
db8dac20
DM
1976 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
1977
1978 /*
1979 * Hmm. We got an UDP packet to a port to which we
1980 * don't wanna listen. Ignore it.
1981 */
1982 kfree_skb(skb);
1983 return 0;
1984
1985short_packet:
ba7a46f1
JP
1986 net_dbg_ratelimited("UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
1987 proto == IPPROTO_UDPLITE ? "Lite" : "",
1988 &saddr, ntohs(uh->source),
1989 ulen, skb->len,
1990 &daddr, ntohs(uh->dest));
db8dac20
DM
1991 goto drop;
1992
1993csum_error:
1994 /*
1995 * RFC1122: OK. Discards the bad packet silently (as far as
1996 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
1997 */
ba7a46f1
JP
1998 net_dbg_ratelimited("UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
1999 proto == IPPROTO_UDPLITE ? "Lite" : "",
2000 &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
2001 ulen);
02c22347 2002 __UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
db8dac20 2003drop:
02c22347 2004 __UDP_INC_STATS(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
db8dac20
DM
2005 kfree_skb(skb);
2006 return 0;
2007}
2008
421b3885
SB
2009/* We can only early demux multicast if there is a single matching socket.
2010 * If more than one socket found returns NULL
2011 */
2012static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net,
2013 __be16 loc_port, __be32 loc_addr,
2014 __be16 rmt_port, __be32 rmt_addr,
2015 int dif)
2016{
2017 struct sock *sk, *result;
421b3885 2018 unsigned short hnum = ntohs(loc_port);
ca065d0c 2019 unsigned int slot = udp_hashfn(net, hnum, udp_table.mask);
421b3885
SB
2020 struct udp_hslot *hslot = &udp_table.hash[slot];
2021
63c6f81c
ED
2022 /* Do not bother scanning a too big list */
2023 if (hslot->count > 10)
2024 return NULL;
2025
421b3885 2026 result = NULL;
ca065d0c
ED
2027 sk_for_each_rcu(sk, &hslot->head) {
2028 if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr,
2029 rmt_port, rmt_addr, dif, hnum)) {
2030 if (result)
2031 return NULL;
421b3885 2032 result = sk;
421b3885
SB
2033 }
2034 }
ca065d0c 2035
421b3885
SB
2036 return result;
2037}
2038
2039/* For unicast we should only early demux connected sockets or we can
2040 * break forwarding setups. The chains here can be long so only check
2041 * if the first socket is an exact match and if not move on.
2042 */
2043static struct sock *__udp4_lib_demux_lookup(struct net *net,
2044 __be16 loc_port, __be32 loc_addr,
2045 __be16 rmt_port, __be32 rmt_addr,
2046 int dif)
2047{
421b3885
SB
2048 unsigned short hnum = ntohs(loc_port);
2049 unsigned int hash2 = udp4_portaddr_hash(net, loc_addr, hnum);
2050 unsigned int slot2 = hash2 & udp_table.mask;
2051 struct udp_hslot *hslot2 = &udp_table.hash2[slot2];
c7228317 2052 INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr);
421b3885 2053 const __portpair ports = INET_COMBINED_PORTS(rmt_port, hnum);
ca065d0c 2054 struct sock *sk;
421b3885 2055
ca065d0c
ED
2056 udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
2057 if (INET_MATCH(sk, net, acookie, rmt_addr,
2058 loc_addr, ports, dif))
2059 return sk;
421b3885
SB
2060 /* Only check first socket in chain */
2061 break;
2062 }
ca065d0c 2063 return NULL;
421b3885
SB
2064}
2065
2066void udp_v4_early_demux(struct sk_buff *skb)
2067{
610438b7
ED
2068 struct net *net = dev_net(skb->dev);
2069 const struct iphdr *iph;
2070 const struct udphdr *uh;
ca065d0c 2071 struct sock *sk = NULL;
421b3885 2072 struct dst_entry *dst;
421b3885 2073 int dif = skb->dev->ifindex;
6e540309 2074 int ours;
421b3885
SB
2075
2076 /* validate the packet */
2077 if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)))
2078 return;
2079
610438b7
ED
2080 iph = ip_hdr(skb);
2081 uh = udp_hdr(skb);
2082
421b3885 2083 if (skb->pkt_type == PACKET_BROADCAST ||
6e540309
SB
2084 skb->pkt_type == PACKET_MULTICAST) {
2085 struct in_device *in_dev = __in_dev_get_rcu(skb->dev);
2086
2087 if (!in_dev)
2088 return;
2089
ad0ea198
PA
2090 /* we are supposed to accept bcast packets */
2091 if (skb->pkt_type == PACKET_MULTICAST) {
2092 ours = ip_check_mc_rcu(in_dev, iph->daddr, iph->saddr,
2093 iph->protocol);
2094 if (!ours)
2095 return;
2096 }
2097
421b3885
SB
2098 sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr,
2099 uh->source, iph->saddr, dif);
6e540309 2100 } else if (skb->pkt_type == PACKET_HOST) {
421b3885
SB
2101 sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr,
2102 uh->source, iph->saddr, dif);
6e540309 2103 }
421b3885 2104
ca065d0c 2105 if (!sk || !atomic_inc_not_zero_hint(&sk->sk_refcnt, 2))
421b3885
SB
2106 return;
2107
2108 skb->sk = sk;
82eabd9e 2109 skb->destructor = sock_efree;
10e2eb87 2110 dst = READ_ONCE(sk->sk_rx_dst);
421b3885
SB
2111
2112 if (dst)
2113 dst = dst_check(dst, 0);
10e2eb87
ED
2114 if (dst) {
2115 /* DST_NOCACHE can not be used without taking a reference */
2116 if (dst->flags & DST_NOCACHE) {
2117 if (likely(atomic_inc_not_zero(&dst->__refcnt)))
2118 skb_dst_set(skb, dst);
2119 } else {
2120 skb_dst_set_noref(skb, dst);
2121 }
2122 }
421b3885
SB
2123}
2124
db8dac20
DM
2125int udp_rcv(struct sk_buff *skb)
2126{
645ca708 2127 return __udp4_lib_rcv(skb, &udp_table, IPPROTO_UDP);
db8dac20
DM
2128}
2129
7d06b2e0 2130void udp_destroy_sock(struct sock *sk)
db8dac20 2131{
44046a59 2132 struct udp_sock *up = udp_sk(sk);
8a74ad60 2133 bool slow = lock_sock_fast(sk);
db8dac20 2134 udp_flush_pending_frames(sk);
8a74ad60 2135 unlock_sock_fast(sk, slow);
44046a59
TP
2136 if (static_key_false(&udp_encap_needed) && up->encap_type) {
2137 void (*encap_destroy)(struct sock *sk);
2138 encap_destroy = ACCESS_ONCE(up->encap_destroy);
2139 if (encap_destroy)
2140 encap_destroy(sk);
2141 }
db8dac20
DM
2142}
2143
1da177e4
LT
2144/*
2145 * Socket option code for UDP
2146 */
4c0a6cb0 2147int udp_lib_setsockopt(struct sock *sk, int level, int optname,
b7058842 2148 char __user *optval, unsigned int optlen,
4c0a6cb0 2149 int (*push_pending_frames)(struct sock *))
1da177e4
LT
2150{
2151 struct udp_sock *up = udp_sk(sk);
1c19448c 2152 int val, valbool;
1da177e4 2153 int err = 0;
b2bf1e26 2154 int is_udplite = IS_UDPLITE(sk);
1da177e4 2155
c482c568 2156 if (optlen < sizeof(int))
1da177e4
LT
2157 return -EINVAL;
2158
2159 if (get_user(val, (int __user *)optval))
2160 return -EFAULT;
2161
1c19448c
TH
2162 valbool = val ? 1 : 0;
2163
6516c655 2164 switch (optname) {
1da177e4
LT
2165 case UDP_CORK:
2166 if (val != 0) {
2167 up->corkflag = 1;
2168 } else {
2169 up->corkflag = 0;
2170 lock_sock(sk);
4243cdc2 2171 push_pending_frames(sk);
1da177e4
LT
2172 release_sock(sk);
2173 }
2174 break;
e905a9ed 2175
1da177e4
LT
2176 case UDP_ENCAP:
2177 switch (val) {
2178 case 0:
2179 case UDP_ENCAP_ESPINUDP:
2180 case UDP_ENCAP_ESPINUDP_NON_IKE:
067b207b
JC
2181 up->encap_rcv = xfrm4_udp_encap_rcv;
2182 /* FALLTHROUGH */
342f0234 2183 case UDP_ENCAP_L2TPINUDP:
1da177e4 2184 up->encap_type = val;
447167bf 2185 udp_encap_enable();
1da177e4
LT
2186 break;
2187 default:
2188 err = -ENOPROTOOPT;
2189 break;
2190 }
2191 break;
2192
1c19448c
TH
2193 case UDP_NO_CHECK6_TX:
2194 up->no_check6_tx = valbool;
2195 break;
2196
2197 case UDP_NO_CHECK6_RX:
2198 up->no_check6_rx = valbool;
2199 break;
2200
ba4e58ec
GR
2201 /*
2202 * UDP-Lite's partial checksum coverage (RFC 3828).
2203 */
2204 /* The sender sets actual checksum coverage length via this option.
2205 * The case coverage > packet length is handled by send module. */
2206 case UDPLITE_SEND_CSCOV:
b2bf1e26 2207 if (!is_udplite) /* Disable the option on UDP sockets */
ba4e58ec
GR
2208 return -ENOPROTOOPT;
2209 if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
2210 val = 8;
4be929be
AD
2211 else if (val > USHRT_MAX)
2212 val = USHRT_MAX;
ba4e58ec
GR
2213 up->pcslen = val;
2214 up->pcflag |= UDPLITE_SEND_CC;
2215 break;
2216
e905a9ed
YH
2217 /* The receiver specifies a minimum checksum coverage value. To make
2218 * sense, this should be set to at least 8 (as done below). If zero is
ba4e58ec
GR
2219 * used, this again means full checksum coverage. */
2220 case UDPLITE_RECV_CSCOV:
b2bf1e26 2221 if (!is_udplite) /* Disable the option on UDP sockets */
ba4e58ec
GR
2222 return -ENOPROTOOPT;
2223 if (val != 0 && val < 8) /* Avoid silly minimal values. */
2224 val = 8;
4be929be
AD
2225 else if (val > USHRT_MAX)
2226 val = USHRT_MAX;
ba4e58ec
GR
2227 up->pcrlen = val;
2228 up->pcflag |= UDPLITE_RECV_CC;
2229 break;
2230
1da177e4
LT
2231 default:
2232 err = -ENOPROTOOPT;
2233 break;
6516c655 2234 }
1da177e4
LT
2235
2236 return err;
2237}
c482c568 2238EXPORT_SYMBOL(udp_lib_setsockopt);
1da177e4 2239
db8dac20 2240int udp_setsockopt(struct sock *sk, int level, int optname,
b7058842 2241 char __user *optval, unsigned int optlen)
db8dac20
DM
2242{
2243 if (level == SOL_UDP || level == SOL_UDPLITE)
2244 return udp_lib_setsockopt(sk, level, optname, optval, optlen,
2245 udp_push_pending_frames);
2246 return ip_setsockopt(sk, level, optname, optval, optlen);
2247}
2248
2249#ifdef CONFIG_COMPAT
2250int compat_udp_setsockopt(struct sock *sk, int level, int optname,
b7058842 2251 char __user *optval, unsigned int optlen)
db8dac20
DM
2252{
2253 if (level == SOL_UDP || level == SOL_UDPLITE)
2254 return udp_lib_setsockopt(sk, level, optname, optval, optlen,
2255 udp_push_pending_frames);
2256 return compat_ip_setsockopt(sk, level, optname, optval, optlen);
2257}
2258#endif
2259
4c0a6cb0
GR
2260int udp_lib_getsockopt(struct sock *sk, int level, int optname,
2261 char __user *optval, int __user *optlen)
1da177e4
LT
2262{
2263 struct udp_sock *up = udp_sk(sk);
2264 int val, len;
2265
c482c568 2266 if (get_user(len, optlen))
1da177e4
LT
2267 return -EFAULT;
2268
2269 len = min_t(unsigned int, len, sizeof(int));
e905a9ed 2270
6516c655 2271 if (len < 0)
1da177e4
LT
2272 return -EINVAL;
2273
6516c655 2274 switch (optname) {
1da177e4
LT
2275 case UDP_CORK:
2276 val = up->corkflag;
2277 break;
2278
2279 case UDP_ENCAP:
2280 val = up->encap_type;
2281 break;
2282
1c19448c
TH
2283 case UDP_NO_CHECK6_TX:
2284 val = up->no_check6_tx;
2285 break;
2286
2287 case UDP_NO_CHECK6_RX:
2288 val = up->no_check6_rx;
2289 break;
2290
ba4e58ec
GR
2291 /* The following two cannot be changed on UDP sockets, the return is
2292 * always 0 (which corresponds to the full checksum coverage of UDP). */
2293 case UDPLITE_SEND_CSCOV:
2294 val = up->pcslen;
2295 break;
2296
2297 case UDPLITE_RECV_CSCOV:
2298 val = up->pcrlen;
2299 break;
2300
1da177e4
LT
2301 default:
2302 return -ENOPROTOOPT;
6516c655 2303 }
1da177e4 2304
6516c655 2305 if (put_user(len, optlen))
e905a9ed 2306 return -EFAULT;
c482c568 2307 if (copy_to_user(optval, &val, len))
1da177e4 2308 return -EFAULT;
e905a9ed 2309 return 0;
1da177e4 2310}
c482c568 2311EXPORT_SYMBOL(udp_lib_getsockopt);
1da177e4 2312
db8dac20
DM
2313int udp_getsockopt(struct sock *sk, int level, int optname,
2314 char __user *optval, int __user *optlen)
2315{
2316 if (level == SOL_UDP || level == SOL_UDPLITE)
2317 return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2318 return ip_getsockopt(sk, level, optname, optval, optlen);
2319}
2320
2321#ifdef CONFIG_COMPAT
2322int compat_udp_getsockopt(struct sock *sk, int level, int optname,
2323 char __user *optval, int __user *optlen)
2324{
2325 if (level == SOL_UDP || level == SOL_UDPLITE)
2326 return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2327 return compat_ip_getsockopt(sk, level, optname, optval, optlen);
2328}
2329#endif
1da177e4
LT
2330/**
2331 * udp_poll - wait for a UDP event.
2332 * @file - file struct
2333 * @sock - socket
2334 * @wait - poll table
2335 *
e905a9ed 2336 * This is same as datagram poll, except for the special case of
1da177e4
LT
2337 * blocking sockets. If application is using a blocking fd
2338 * and a packet with checksum error is in the queue;
2339 * then it could get return from select indicating data available
2340 * but then block when reading it. Add special case code
2341 * to work around these arguably broken applications.
2342 */
2343unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait)
2344{
2345 unsigned int mask = datagram_poll(file, sock, wait);
2346 struct sock *sk = sock->sk;
ba4e58ec 2347
c3f1dbaf
DM
2348 sock_rps_record_flow(sk);
2349
1da177e4 2350 /* Check for false positives due to checksum errors */
85584672 2351 if ((mask & POLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
e83c6744 2352 !(sk->sk_shutdown & RCV_SHUTDOWN) && first_packet_length(sk) == -1)
85584672 2353 mask &= ~(POLLIN | POLLRDNORM);
1da177e4
LT
2354
2355 return mask;
e905a9ed 2356
1da177e4 2357}
c482c568 2358EXPORT_SYMBOL(udp_poll);
1da177e4 2359
5d77dca8
DA
2360int udp_abort(struct sock *sk, int err)
2361{
2362 lock_sock(sk);
2363
2364 sk->sk_err = err;
2365 sk->sk_error_report(sk);
286c72de 2366 __udp_disconnect(sk, 0);
5d77dca8
DA
2367
2368 release_sock(sk);
2369
2370 return 0;
2371}
2372EXPORT_SYMBOL_GPL(udp_abort);
2373
db8dac20
DM
2374struct proto udp_prot = {
2375 .name = "UDP",
2376 .owner = THIS_MODULE,
2377 .close = udp_lib_close,
2378 .connect = ip4_datagram_connect,
2379 .disconnect = udp_disconnect,
2380 .ioctl = udp_ioctl,
850cbadd 2381 .init = udp_init_sock,
db8dac20
DM
2382 .destroy = udp_destroy_sock,
2383 .setsockopt = udp_setsockopt,
2384 .getsockopt = udp_getsockopt,
2385 .sendmsg = udp_sendmsg,
2386 .recvmsg = udp_recvmsg,
2387 .sendpage = udp_sendpage,
8141ed9f 2388 .release_cb = ip4_datagram_release_cb,
db8dac20
DM
2389 .hash = udp_lib_hash,
2390 .unhash = udp_lib_unhash,
719f8358 2391 .rehash = udp_v4_rehash,
db8dac20
DM
2392 .get_port = udp_v4_get_port,
2393 .memory_allocated = &udp_memory_allocated,
2394 .sysctl_mem = sysctl_udp_mem,
2395 .sysctl_wmem = &sysctl_udp_wmem_min,
2396 .sysctl_rmem = &sysctl_udp_rmem_min,
2397 .obj_size = sizeof(struct udp_sock),
645ca708 2398 .h.udp_table = &udp_table,
db8dac20
DM
2399#ifdef CONFIG_COMPAT
2400 .compat_setsockopt = compat_udp_setsockopt,
2401 .compat_getsockopt = compat_udp_getsockopt,
2402#endif
5d77dca8 2403 .diag_destroy = udp_abort,
db8dac20 2404};
c482c568 2405EXPORT_SYMBOL(udp_prot);
1da177e4
LT
2406
2407/* ------------------------------------------------------------------------ */
2408#ifdef CONFIG_PROC_FS
2409
645ca708 2410static struct sock *udp_get_first(struct seq_file *seq, int start)
1da177e4
LT
2411{
2412 struct sock *sk;
2413 struct udp_iter_state *state = seq->private;
6f191efe 2414 struct net *net = seq_file_net(seq);
1da177e4 2415
f86dcc5a
ED
2416 for (state->bucket = start; state->bucket <= state->udp_table->mask;
2417 ++state->bucket) {
645ca708 2418 struct udp_hslot *hslot = &state->udp_table->hash[state->bucket];
f86dcc5a 2419
ca065d0c 2420 if (hlist_empty(&hslot->head))
f86dcc5a
ED
2421 continue;
2422
645ca708 2423 spin_lock_bh(&hslot->lock);
ca065d0c 2424 sk_for_each(sk, &hslot->head) {
878628fb 2425 if (!net_eq(sock_net(sk), net))
a91275ef 2426 continue;
1da177e4
LT
2427 if (sk->sk_family == state->family)
2428 goto found;
2429 }
645ca708 2430 spin_unlock_bh(&hslot->lock);
1da177e4
LT
2431 }
2432 sk = NULL;
2433found:
2434 return sk;
2435}
2436
2437static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
2438{
2439 struct udp_iter_state *state = seq->private;
6f191efe 2440 struct net *net = seq_file_net(seq);
1da177e4
LT
2441
2442 do {
ca065d0c 2443 sk = sk_next(sk);
878628fb 2444 } while (sk && (!net_eq(sock_net(sk), net) || sk->sk_family != state->family));
1da177e4 2445
645ca708 2446 if (!sk) {
f86dcc5a 2447 if (state->bucket <= state->udp_table->mask)
30842f29 2448 spin_unlock_bh(&state->udp_table->hash[state->bucket].lock);
645ca708 2449 return udp_get_first(seq, state->bucket + 1);
1da177e4
LT
2450 }
2451 return sk;
2452}
2453
2454static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
2455{
645ca708 2456 struct sock *sk = udp_get_first(seq, 0);
1da177e4
LT
2457
2458 if (sk)
6516c655 2459 while (pos && (sk = udp_get_next(seq, sk)) != NULL)
1da177e4
LT
2460 --pos;
2461 return pos ? NULL : sk;
2462}
2463
2464static void *udp_seq_start(struct seq_file *seq, loff_t *pos)
2465{
30842f29 2466 struct udp_iter_state *state = seq->private;
f86dcc5a 2467 state->bucket = MAX_UDP_PORTS;
30842f29 2468
b50660f1 2469 return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
1da177e4
LT
2470}
2471
2472static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2473{
2474 struct sock *sk;
2475
b50660f1 2476 if (v == SEQ_START_TOKEN)
1da177e4
LT
2477 sk = udp_get_idx(seq, 0);
2478 else
2479 sk = udp_get_next(seq, v);
2480
2481 ++*pos;
2482 return sk;
2483}
2484
2485static void udp_seq_stop(struct seq_file *seq, void *v)
2486{
645ca708
ED
2487 struct udp_iter_state *state = seq->private;
2488
f86dcc5a 2489 if (state->bucket <= state->udp_table->mask)
645ca708 2490 spin_unlock_bh(&state->udp_table->hash[state->bucket].lock);
1da177e4
LT
2491}
2492
73cb88ec 2493int udp_seq_open(struct inode *inode, struct file *file)
1da177e4 2494{
d9dda78b 2495 struct udp_seq_afinfo *afinfo = PDE_DATA(inode);
a2be75c1
DL
2496 struct udp_iter_state *s;
2497 int err;
a91275ef 2498
a2be75c1
DL
2499 err = seq_open_net(inode, file, &afinfo->seq_ops,
2500 sizeof(struct udp_iter_state));
2501 if (err < 0)
2502 return err;
a91275ef 2503
a2be75c1 2504 s = ((struct seq_file *)file->private_data)->private;
1da177e4 2505 s->family = afinfo->family;
645ca708 2506 s->udp_table = afinfo->udp_table;
a2be75c1 2507 return err;
a91275ef 2508}
73cb88ec 2509EXPORT_SYMBOL(udp_seq_open);
a91275ef 2510
1da177e4 2511/* ------------------------------------------------------------------------ */
0c96d8c5 2512int udp_proc_register(struct net *net, struct udp_seq_afinfo *afinfo)
1da177e4
LT
2513{
2514 struct proc_dir_entry *p;
2515 int rc = 0;
2516
dda61925
DL
2517 afinfo->seq_ops.start = udp_seq_start;
2518 afinfo->seq_ops.next = udp_seq_next;
2519 afinfo->seq_ops.stop = udp_seq_stop;
2520
84841c3c 2521 p = proc_create_data(afinfo->name, S_IRUGO, net->proc_net,
73cb88ec 2522 afinfo->seq_fops, afinfo);
84841c3c 2523 if (!p)
1da177e4
LT
2524 rc = -ENOMEM;
2525 return rc;
2526}
c482c568 2527EXPORT_SYMBOL(udp_proc_register);
1da177e4 2528
0c96d8c5 2529void udp_proc_unregister(struct net *net, struct udp_seq_afinfo *afinfo)
1da177e4 2530{
ece31ffd 2531 remove_proc_entry(afinfo->name, net->proc_net);
1da177e4 2532}
c482c568 2533EXPORT_SYMBOL(udp_proc_unregister);
db8dac20
DM
2534
2535/* ------------------------------------------------------------------------ */
5e659e4c 2536static void udp4_format_sock(struct sock *sp, struct seq_file *f,
652586df 2537 int bucket)
db8dac20
DM
2538{
2539 struct inet_sock *inet = inet_sk(sp);
c720c7e8
ED
2540 __be32 dest = inet->inet_daddr;
2541 __be32 src = inet->inet_rcv_saddr;
2542 __u16 destp = ntohs(inet->inet_dport);
2543 __u16 srcp = ntohs(inet->inet_sport);
db8dac20 2544
f86dcc5a 2545 seq_printf(f, "%5d: %08X:%04X %08X:%04X"
652586df 2546 " %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %d",
db8dac20 2547 bucket, src, srcp, dest, destp, sp->sk_state,
31e6d363
ED
2548 sk_wmem_alloc_get(sp),
2549 sk_rmem_alloc_get(sp),
a7cb5a49
EB
2550 0, 0L, 0,
2551 from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
2552 0, sock_i_ino(sp),
cb61cb9b 2553 atomic_read(&sp->sk_refcnt), sp,
652586df 2554 atomic_read(&sp->sk_drops));
db8dac20
DM
2555}
2556
2557int udp4_seq_show(struct seq_file *seq, void *v)
2558{
652586df 2559 seq_setwidth(seq, 127);
db8dac20 2560 if (v == SEQ_START_TOKEN)
652586df 2561 seq_puts(seq, " sl local_address rem_address st tx_queue "
db8dac20 2562 "rx_queue tr tm->when retrnsmt uid timeout "
cb61cb9b 2563 "inode ref pointer drops");
db8dac20 2564 else {
db8dac20
DM
2565 struct udp_iter_state *state = seq->private;
2566
652586df 2567 udp4_format_sock(v, seq, state->bucket);
db8dac20 2568 }
652586df 2569 seq_pad(seq, '\n');
db8dac20
DM
2570 return 0;
2571}
2572
73cb88ec
AV
2573static const struct file_operations udp_afinfo_seq_fops = {
2574 .owner = THIS_MODULE,
2575 .open = udp_seq_open,
2576 .read = seq_read,
2577 .llseek = seq_lseek,
2578 .release = seq_release_net
2579};
2580
db8dac20 2581/* ------------------------------------------------------------------------ */
db8dac20 2582static struct udp_seq_afinfo udp4_seq_afinfo = {
db8dac20
DM
2583 .name = "udp",
2584 .family = AF_INET,
645ca708 2585 .udp_table = &udp_table,
73cb88ec 2586 .seq_fops = &udp_afinfo_seq_fops,
dda61925
DL
2587 .seq_ops = {
2588 .show = udp4_seq_show,
2589 },
db8dac20
DM
2590};
2591
2c8c1e72 2592static int __net_init udp4_proc_init_net(struct net *net)
15439feb
PE
2593{
2594 return udp_proc_register(net, &udp4_seq_afinfo);
2595}
2596
2c8c1e72 2597static void __net_exit udp4_proc_exit_net(struct net *net)
15439feb
PE
2598{
2599 udp_proc_unregister(net, &udp4_seq_afinfo);
2600}
2601
2602static struct pernet_operations udp4_net_ops = {
2603 .init = udp4_proc_init_net,
2604 .exit = udp4_proc_exit_net,
2605};
2606
db8dac20
DM
2607int __init udp4_proc_init(void)
2608{
15439feb 2609 return register_pernet_subsys(&udp4_net_ops);
db8dac20
DM
2610}
2611
2612void udp4_proc_exit(void)
2613{
15439feb 2614 unregister_pernet_subsys(&udp4_net_ops);
db8dac20 2615}
1da177e4
LT
2616#endif /* CONFIG_PROC_FS */
2617
f86dcc5a
ED
2618static __initdata unsigned long uhash_entries;
2619static int __init set_uhash_entries(char *str)
645ca708 2620{
413c27d8
EZ
2621 ssize_t ret;
2622
f86dcc5a
ED
2623 if (!str)
2624 return 0;
413c27d8
EZ
2625
2626 ret = kstrtoul(str, 0, &uhash_entries);
2627 if (ret)
2628 return 0;
2629
f86dcc5a
ED
2630 if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
2631 uhash_entries = UDP_HTABLE_SIZE_MIN;
2632 return 1;
2633}
2634__setup("uhash_entries=", set_uhash_entries);
645ca708 2635
f86dcc5a
ED
2636void __init udp_table_init(struct udp_table *table, const char *name)
2637{
2638 unsigned int i;
2639
31fe62b9
TB
2640 table->hash = alloc_large_system_hash(name,
2641 2 * sizeof(struct udp_hslot),
2642 uhash_entries,
2643 21, /* one slot per 2 MB */
2644 0,
2645 &table->log,
2646 &table->mask,
2647 UDP_HTABLE_SIZE_MIN,
2648 64 * 1024);
2649
512615b6 2650 table->hash2 = table->hash + (table->mask + 1);
f86dcc5a 2651 for (i = 0; i <= table->mask; i++) {
ca065d0c 2652 INIT_HLIST_HEAD(&table->hash[i].head);
fdcc8aa9 2653 table->hash[i].count = 0;
645ca708
ED
2654 spin_lock_init(&table->hash[i].lock);
2655 }
512615b6 2656 for (i = 0; i <= table->mask; i++) {
ca065d0c 2657 INIT_HLIST_HEAD(&table->hash2[i].head);
512615b6
ED
2658 table->hash2[i].count = 0;
2659 spin_lock_init(&table->hash2[i].lock);
2660 }
645ca708
ED
2661}
2662
723b8e46
TH
2663u32 udp_flow_hashrnd(void)
2664{
2665 static u32 hashrnd __read_mostly;
2666
2667 net_get_random_once(&hashrnd, sizeof(hashrnd));
2668
2669 return hashrnd;
2670}
2671EXPORT_SYMBOL(udp_flow_hashrnd);
2672
95766fff
HA
2673void __init udp_init(void)
2674{
f03d78db 2675 unsigned long limit;
4b272750 2676 unsigned int i;
95766fff 2677
f86dcc5a 2678 udp_table_init(&udp_table, "UDP");
f03d78db 2679 limit = nr_free_buffer_pages() / 8;
95766fff
HA
2680 limit = max(limit, 128UL);
2681 sysctl_udp_mem[0] = limit / 4 * 3;
2682 sysctl_udp_mem[1] = limit;
2683 sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
2684
2685 sysctl_udp_rmem_min = SK_MEM_QUANTUM;
2686 sysctl_udp_wmem_min = SK_MEM_QUANTUM;
4b272750
ED
2687
2688 /* 16 spinlocks per cpu */
2689 udp_busylocks_log = ilog2(nr_cpu_ids) + 4;
2690 udp_busylocks = kmalloc(sizeof(spinlock_t) << udp_busylocks_log,
2691 GFP_KERNEL);
2692 if (!udp_busylocks)
2693 panic("UDP: failed to alloc udp_busylocks\n");
2694 for (i = 0; i < (1U << udp_busylocks_log); i++)
2695 spin_lock_init(udp_busylocks + i);
95766fff 2696}