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