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