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