1 // SPDX-License-Identifier: GPL-2.0-or-later
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.
7 * The User Datagram Protocol (UDP).
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>
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
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
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
66 * Hirokazu Takahashi : sendfile() on UDP works now.
67 * Arnaldo C. Melo : convert /proc/net/udp to seq_file
68 * YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which
69 * Alexey Kuznetsov: allow both IPv4 and IPv6 sockets to bind
70 * a single port at the same time.
71 * Derek Atkins <derek@ihtfp.com>: Add Encapulation Support
72 * James Chapman : Add L2TP encapsulation type.
75 #define pr_fmt(fmt) "UDP: " fmt
77 #include <linux/bpf-cgroup.h>
78 #include <linux/uaccess.h>
79 #include <asm/ioctls.h>
80 #include <linux/memblock.h>
81 #include <linux/highmem.h>
82 #include <linux/types.h>
83 #include <linux/fcntl.h>
84 #include <linux/module.h>
85 #include <linux/socket.h>
86 #include <linux/sockios.h>
87 #include <linux/igmp.h>
88 #include <linux/inetdevice.h>
90 #include <linux/errno.h>
91 #include <linux/timer.h>
93 #include <linux/inet.h>
94 #include <linux/netdevice.h>
95 #include <linux/slab.h>
96 #include <net/tcp_states.h>
97 #include <linux/skbuff.h>
98 #include <linux/proc_fs.h>
99 #include <linux/seq_file.h>
100 #include <net/net_namespace.h>
101 #include <net/icmp.h>
102 #include <net/inet_hashtables.h>
103 #include <net/ip_tunnels.h>
104 #include <net/route.h>
105 #include <net/checksum.h>
106 #include <net/xfrm.h>
107 #include <trace/events/udp.h>
108 #include <linux/static_key.h>
109 #include <linux/btf_ids.h>
110 #include <trace/events/skb.h>
111 #include <net/busy_poll.h>
112 #include "udp_impl.h"
113 #include <net/sock_reuseport.h>
114 #include <net/addrconf.h>
115 #include <net/udp_tunnel.h>
116 #if IS_ENABLED(CONFIG_IPV6)
117 #include <net/ipv6_stubs.h>
120 struct udp_table udp_table __read_mostly;
121 EXPORT_SYMBOL(udp_table);
123 long sysctl_udp_mem[3] __read_mostly;
124 EXPORT_SYMBOL(sysctl_udp_mem);
126 atomic_long_t udp_memory_allocated ____cacheline_aligned_in_smp;
127 EXPORT_SYMBOL(udp_memory_allocated);
128 DEFINE_PER_CPU(int, udp_memory_per_cpu_fw_alloc);
129 EXPORT_PER_CPU_SYMBOL_GPL(udp_memory_per_cpu_fw_alloc);
131 #define MAX_UDP_PORTS 65536
132 #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN)
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)
140 kuid_t uid = sock_i_uid(sk);
142 sk_for_each(sk2, &hslot->head) {
143 if (net_eq(sock_net(sk2), net) &&
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, sock_i_uid(sk2))) {
158 __set_bit(udp_sk(sk2)->udp_port_hash >> log,
167 * Note: we still hold spinlock of primary hash chain, so no other writer
168 * can insert/delete a socket with local_port == num
170 static int udp_lib_lport_inuse2(struct net *net, __u16 num,
171 struct udp_hslot *hslot2,
175 kuid_t uid = sock_i_uid(sk);
178 spin_lock(&hslot2->lock);
179 udp_portaddr_for_each_entry(sk2, &hslot2->head) {
180 if (net_eq(sock_net(sk2), net) &&
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, sock_i_uid(sk2))) {
197 spin_unlock(&hslot2->lock);
201 static int udp_reuseport_add_sock(struct sock *sk, struct udp_hslot *hslot)
203 struct net *net = sock_net(sk);
204 kuid_t uid = sock_i_uid(sk);
207 sk_for_each(sk2, &hslot->head) {
208 if (net_eq(sock_net(sk2), net) &&
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, sock_i_uid(sk2)) &&
215 inet_rcv_saddr_equal(sk, sk2, false)) {
216 return reuseport_add_sock(sk, sk2,
217 inet_rcv_saddr_any(sk));
221 return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
225 * udp_lib_get_port - UDP/-Lite port lookup for IPv4 and IPv6
227 * @sk: socket struct in question
228 * @snum: port number to look up
229 * @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
232 int udp_lib_get_port(struct sock *sk, unsigned short snum,
233 unsigned int hash2_nulladdr)
235 struct udp_table *udptable = sk->sk_prot->h.udp_table;
236 struct udp_hslot *hslot, *hslot2;
237 struct net *net = sock_net(sk);
238 int error = -EADDRINUSE;
241 DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
242 unsigned short first, last;
243 int low, high, remaining;
246 inet_sk_get_local_port_range(sk, &low, &high);
247 remaining = (high - low) + 1;
249 rand = get_random_u32();
250 first = reciprocal_scale(rand, remaining) + low;
252 * force rand to be an odd multiple of UDP_HTABLE_SIZE
254 rand = (rand | 1) * (udptable->mask + 1);
255 last = first + udptable->mask + 1;
257 hslot = udp_hashslot(udptable, net, first);
258 bitmap_zero(bitmap, PORTS_PER_CHAIN);
259 spin_lock_bh(&hslot->lock);
260 udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
265 * Iterate on all possible values of snum for this hash.
266 * Using steps of an odd multiple of UDP_HTABLE_SIZE
267 * give us randomization and full range coverage.
270 if (low <= snum && snum <= high &&
271 !test_bit(snum >> udptable->log, bitmap) &&
272 !inet_is_local_reserved_port(net, snum))
275 } while (snum != first);
276 spin_unlock_bh(&hslot->lock);
278 } while (++first != last);
281 hslot = udp_hashslot(udptable, net, snum);
282 spin_lock_bh(&hslot->lock);
283 if (hslot->count > 10) {
285 unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
287 slot2 &= udptable->mask;
288 hash2_nulladdr &= udptable->mask;
290 hslot2 = udp_hashslot2(udptable, slot2);
291 if (hslot->count < hslot2->count)
292 goto scan_primary_hash;
294 exist = udp_lib_lport_inuse2(net, snum, hslot2, sk);
295 if (!exist && (hash2_nulladdr != slot2)) {
296 hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
297 exist = udp_lib_lport_inuse2(net, snum, hslot2,
306 if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, 0))
310 inet_sk(sk)->inet_num = snum;
311 udp_sk(sk)->udp_port_hash = snum;
312 udp_sk(sk)->udp_portaddr_hash ^= snum;
313 if (sk_unhashed(sk)) {
314 if (sk->sk_reuseport &&
315 udp_reuseport_add_sock(sk, hslot)) {
316 inet_sk(sk)->inet_num = 0;
317 udp_sk(sk)->udp_port_hash = 0;
318 udp_sk(sk)->udp_portaddr_hash ^= snum;
322 sk_add_node_rcu(sk, &hslot->head);
324 sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
326 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
327 spin_lock(&hslot2->lock);
328 if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
329 sk->sk_family == AF_INET6)
330 hlist_add_tail_rcu(&udp_sk(sk)->udp_portaddr_node,
333 hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
336 spin_unlock(&hslot2->lock);
338 sock_set_flag(sk, SOCK_RCU_FREE);
341 spin_unlock_bh(&hslot->lock);
345 EXPORT_SYMBOL(udp_lib_get_port);
347 int udp_v4_get_port(struct sock *sk, unsigned short snum)
349 unsigned int hash2_nulladdr =
350 ipv4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
351 unsigned int hash2_partial =
352 ipv4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
354 /* precompute partial secondary hash */
355 udp_sk(sk)->udp_portaddr_hash = hash2_partial;
356 return udp_lib_get_port(sk, snum, hash2_nulladdr);
359 static int compute_score(struct sock *sk, struct net *net,
360 __be32 saddr, __be16 sport,
361 __be32 daddr, unsigned short hnum,
365 struct inet_sock *inet;
368 if (!net_eq(sock_net(sk), net) ||
369 udp_sk(sk)->udp_port_hash != hnum ||
373 if (sk->sk_rcv_saddr != daddr)
376 score = (sk->sk_family == PF_INET) ? 2 : 1;
379 if (inet->inet_daddr) {
380 if (inet->inet_daddr != saddr)
385 if (inet->inet_dport) {
386 if (inet->inet_dport != sport)
391 dev_match = udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if,
395 if (sk->sk_bound_dev_if)
398 if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
403 static u32 udp_ehashfn(const struct net *net, const __be32 laddr,
404 const __u16 lport, const __be32 faddr,
407 static u32 udp_ehash_secret __read_mostly;
409 net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret));
411 return __inet_ehashfn(laddr, lport, faddr, fport,
412 udp_ehash_secret + net_hash_mix(net));
415 static struct sock *lookup_reuseport(struct net *net, struct sock *sk,
417 __be32 saddr, __be16 sport,
418 __be32 daddr, unsigned short hnum)
420 struct sock *reuse_sk = NULL;
423 if (sk->sk_reuseport && sk->sk_state != TCP_ESTABLISHED) {
424 hash = udp_ehashfn(net, daddr, hnum, saddr, sport);
425 reuse_sk = reuseport_select_sock(sk, hash, skb,
426 sizeof(struct udphdr));
431 /* called with rcu_read_lock() */
432 static struct sock *udp4_lib_lookup2(struct net *net,
433 __be32 saddr, __be16 sport,
434 __be32 daddr, unsigned int hnum,
436 struct udp_hslot *hslot2,
439 struct sock *sk, *result;
444 udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
445 score = compute_score(sk, net, saddr, sport,
446 daddr, hnum, dif, sdif);
447 if (score > badness) {
449 result = lookup_reuseport(net, sk, skb, saddr, sport, daddr, hnum);
455 /* Fall back to scoring if group has connections */
456 if (!reuseport_has_conns(sk))
459 /* Reuseport logic returned an error, keep original score. */
463 badness = compute_score(result, net, saddr, sport,
464 daddr, hnum, dif, sdif);
471 static struct sock *udp4_lookup_run_bpf(struct net *net,
472 struct udp_table *udptable,
474 __be32 saddr, __be16 sport,
475 __be32 daddr, u16 hnum, const int dif)
477 struct sock *sk, *reuse_sk;
480 if (udptable != &udp_table)
481 return NULL; /* only UDP is supported */
483 no_reuseport = bpf_sk_lookup_run_v4(net, IPPROTO_UDP, saddr, sport,
484 daddr, hnum, dif, &sk);
485 if (no_reuseport || IS_ERR_OR_NULL(sk))
488 reuse_sk = lookup_reuseport(net, sk, skb, saddr, sport, daddr, hnum);
494 /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
495 * harder than this. -DaveM
497 struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
498 __be16 sport, __be32 daddr, __be16 dport, int dif,
499 int sdif, struct udp_table *udptable, struct sk_buff *skb)
501 unsigned short hnum = ntohs(dport);
502 unsigned int hash2, slot2;
503 struct udp_hslot *hslot2;
504 struct sock *result, *sk;
506 hash2 = ipv4_portaddr_hash(net, daddr, hnum);
507 slot2 = hash2 & udptable->mask;
508 hslot2 = &udptable->hash2[slot2];
510 /* Lookup connected or non-wildcard socket */
511 result = udp4_lib_lookup2(net, saddr, sport,
512 daddr, hnum, dif, sdif,
514 if (!IS_ERR_OR_NULL(result) && result->sk_state == TCP_ESTABLISHED)
517 /* Lookup redirect from BPF */
518 if (static_branch_unlikely(&bpf_sk_lookup_enabled)) {
519 sk = udp4_lookup_run_bpf(net, udptable, skb,
520 saddr, sport, daddr, hnum, dif);
527 /* Got non-wildcard socket or error on first lookup */
531 /* Lookup wildcard sockets */
532 hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
533 slot2 = hash2 & udptable->mask;
534 hslot2 = &udptable->hash2[slot2];
536 result = udp4_lib_lookup2(net, saddr, sport,
537 htonl(INADDR_ANY), hnum, dif, sdif,
544 EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
546 static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
547 __be16 sport, __be16 dport,
548 struct udp_table *udptable)
550 const struct iphdr *iph = ip_hdr(skb);
552 return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
553 iph->daddr, dport, inet_iif(skb),
554 inet_sdif(skb), udptable, skb);
557 struct sock *udp4_lib_lookup_skb(const struct sk_buff *skb,
558 __be16 sport, __be16 dport)
560 const struct iphdr *iph = ip_hdr(skb);
562 return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
563 iph->daddr, dport, inet_iif(skb),
564 inet_sdif(skb), &udp_table, NULL);
567 /* Must be called under rcu_read_lock().
568 * Does increment socket refcount.
570 #if IS_ENABLED(CONFIG_NF_TPROXY_IPV4) || IS_ENABLED(CONFIG_NF_SOCKET_IPV4)
571 struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
572 __be32 daddr, __be16 dport, int dif)
576 sk = __udp4_lib_lookup(net, saddr, sport, daddr, dport,
577 dif, 0, &udp_table, NULL);
578 if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
582 EXPORT_SYMBOL_GPL(udp4_lib_lookup);
585 static inline bool __udp_is_mcast_sock(struct net *net, struct sock *sk,
586 __be16 loc_port, __be32 loc_addr,
587 __be16 rmt_port, __be32 rmt_addr,
588 int dif, int sdif, unsigned short hnum)
590 struct inet_sock *inet = inet_sk(sk);
592 if (!net_eq(sock_net(sk), net) ||
593 udp_sk(sk)->udp_port_hash != hnum ||
594 (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
595 (inet->inet_dport != rmt_port && inet->inet_dport) ||
596 (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) ||
597 ipv6_only_sock(sk) ||
598 !udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif))
600 if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif, sdif))
605 DEFINE_STATIC_KEY_FALSE(udp_encap_needed_key);
606 EXPORT_SYMBOL(udp_encap_needed_key);
608 #if IS_ENABLED(CONFIG_IPV6)
609 DEFINE_STATIC_KEY_FALSE(udpv6_encap_needed_key);
610 EXPORT_SYMBOL(udpv6_encap_needed_key);
613 void udp_encap_enable(void)
615 static_branch_inc(&udp_encap_needed_key);
617 EXPORT_SYMBOL(udp_encap_enable);
619 void udp_encap_disable(void)
621 static_branch_dec(&udp_encap_needed_key);
623 EXPORT_SYMBOL(udp_encap_disable);
625 /* Handler for tunnels with arbitrary destination ports: no socket lookup, go
626 * through error handlers in encapsulations looking for a match.
628 static int __udp4_lib_err_encap_no_sk(struct sk_buff *skb, u32 info)
632 for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) {
633 int (*handler)(struct sk_buff *skb, u32 info);
634 const struct ip_tunnel_encap_ops *encap;
636 encap = rcu_dereference(iptun_encaps[i]);
639 handler = encap->err_handler;
640 if (handler && !handler(skb, info))
647 /* Try to match ICMP errors to UDP tunnels by looking up a socket without
648 * reversing source and destination port: this will match tunnels that force the
649 * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that
650 * lwtunnels might actually break this assumption by being configured with
651 * different destination ports on endpoints, in this case we won't be able to
652 * trace ICMP messages back to them.
654 * If this doesn't match any socket, probe tunnels with arbitrary destination
655 * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port
656 * we've sent packets to won't necessarily match the local destination port.
658 * Then ask the tunnel implementation to match the error against a valid
661 * Return an error if we can't find a match, the socket if we need further
662 * processing, zero otherwise.
664 static struct sock *__udp4_lib_err_encap(struct net *net,
665 const struct iphdr *iph,
667 struct udp_table *udptable,
669 struct sk_buff *skb, u32 info)
671 int (*lookup)(struct sock *sk, struct sk_buff *skb);
672 int network_offset, transport_offset;
675 network_offset = skb_network_offset(skb);
676 transport_offset = skb_transport_offset(skb);
678 /* Network header needs to point to the outer IPv4 header inside ICMP */
679 skb_reset_network_header(skb);
681 /* Transport header needs to point to the UDP header */
682 skb_set_transport_header(skb, iph->ihl << 2);
687 lookup = READ_ONCE(up->encap_err_lookup);
688 if (lookup && lookup(sk, skb))
694 sk = __udp4_lib_lookup(net, iph->daddr, uh->source,
695 iph->saddr, uh->dest, skb->dev->ifindex, 0,
700 lookup = READ_ONCE(up->encap_err_lookup);
701 if (!lookup || lookup(sk, skb))
707 sk = ERR_PTR(__udp4_lib_err_encap_no_sk(skb, info));
709 skb_set_transport_header(skb, transport_offset);
710 skb_set_network_header(skb, network_offset);
716 * This routine is called by the ICMP module when it gets some
717 * sort of error condition. If err < 0 then the socket should
718 * be closed and the error returned to the user. If err > 0
719 * it's just the icmp type << 8 | icmp code.
720 * Header points to the ip header of the error packet. We move
721 * on past this. Then (as it used to claim before adjustment)
722 * header points to the first 8 bytes of the udp header. We need
723 * to find the appropriate port.
726 int __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
728 struct inet_sock *inet;
729 const struct iphdr *iph = (const struct iphdr *)skb->data;
730 struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
731 const int type = icmp_hdr(skb)->type;
732 const int code = icmp_hdr(skb)->code;
737 struct net *net = dev_net(skb->dev);
739 sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
740 iph->saddr, uh->source, skb->dev->ifindex,
741 inet_sdif(skb), udptable, NULL);
743 if (!sk || READ_ONCE(udp_sk(sk)->encap_type)) {
744 /* No socket for error: try tunnels before discarding */
745 if (static_branch_unlikely(&udp_encap_needed_key)) {
746 sk = __udp4_lib_err_encap(net, iph, uh, udptable, sk, skb,
751 sk = ERR_PTR(-ENOENT);
754 __ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
767 case ICMP_TIME_EXCEEDED:
770 case ICMP_SOURCE_QUENCH:
772 case ICMP_PARAMETERPROB:
776 case ICMP_DEST_UNREACH:
777 if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
778 ipv4_sk_update_pmtu(skb, sk, info);
779 if (inet->pmtudisc != IP_PMTUDISC_DONT) {
787 if (code <= NR_ICMP_UNREACH) {
788 harderr = icmp_err_convert[code].fatal;
789 err = icmp_err_convert[code].errno;
793 ipv4_sk_redirect(skb, sk);
798 * RFC1122: OK. Passes ICMP errors back to application, as per
802 /* ...not for tunnels though: we don't have a sending socket */
803 if (udp_sk(sk)->encap_err_rcv)
804 udp_sk(sk)->encap_err_rcv(sk, skb, iph->ihl << 2);
807 if (!inet->recverr) {
808 if (!harderr || sk->sk_state != TCP_ESTABLISHED)
811 ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
819 int udp_err(struct sk_buff *skb, u32 info)
821 return __udp4_lib_err(skb, info, &udp_table);
825 * Throw away all pending data and cancel the corking. Socket is locked.
827 void udp_flush_pending_frames(struct sock *sk)
829 struct udp_sock *up = udp_sk(sk);
833 WRITE_ONCE(up->pending, 0);
834 ip_flush_pending_frames(sk);
837 EXPORT_SYMBOL(udp_flush_pending_frames);
840 * udp4_hwcsum - handle outgoing HW checksumming
841 * @skb: sk_buff containing the filled-in UDP header
842 * (checksum field must be zeroed out)
843 * @src: source IP address
844 * @dst: destination IP address
846 void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
848 struct udphdr *uh = udp_hdr(skb);
849 int offset = skb_transport_offset(skb);
850 int len = skb->len - offset;
854 if (!skb_has_frag_list(skb)) {
856 * Only one fragment on the socket.
858 skb->csum_start = skb_transport_header(skb) - skb->head;
859 skb->csum_offset = offsetof(struct udphdr, check);
860 uh->check = ~csum_tcpudp_magic(src, dst, len,
863 struct sk_buff *frags;
866 * HW-checksum won't work as there are two or more
867 * fragments on the socket so that all csums of sk_buffs
870 skb_walk_frags(skb, frags) {
871 csum = csum_add(csum, frags->csum);
875 csum = skb_checksum(skb, offset, hlen, csum);
876 skb->ip_summed = CHECKSUM_NONE;
878 uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
880 uh->check = CSUM_MANGLED_0;
883 EXPORT_SYMBOL_GPL(udp4_hwcsum);
885 /* Function to set UDP checksum for an IPv4 UDP packet. This is intended
886 * for the simple case like when setting the checksum for a UDP tunnel.
888 void udp_set_csum(bool nocheck, struct sk_buff *skb,
889 __be32 saddr, __be32 daddr, int len)
891 struct udphdr *uh = udp_hdr(skb);
895 } else if (skb_is_gso(skb)) {
896 uh->check = ~udp_v4_check(len, saddr, daddr, 0);
897 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
899 uh->check = udp_v4_check(len, saddr, daddr, lco_csum(skb));
901 uh->check = CSUM_MANGLED_0;
903 skb->ip_summed = CHECKSUM_PARTIAL;
904 skb->csum_start = skb_transport_header(skb) - skb->head;
905 skb->csum_offset = offsetof(struct udphdr, check);
906 uh->check = ~udp_v4_check(len, saddr, daddr, 0);
909 EXPORT_SYMBOL(udp_set_csum);
911 static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4,
912 struct inet_cork *cork)
914 struct sock *sk = skb->sk;
915 struct inet_sock *inet = inet_sk(sk);
918 int is_udplite = IS_UDPLITE(sk);
919 int offset = skb_transport_offset(skb);
920 int len = skb->len - offset;
921 int datalen = len - sizeof(*uh);
925 * Create a UDP header
928 uh->source = inet->inet_sport;
929 uh->dest = fl4->fl4_dport;
930 uh->len = htons(len);
933 if (cork->gso_size) {
934 const int hlen = skb_network_header_len(skb) +
935 sizeof(struct udphdr);
937 if (hlen + cork->gso_size > cork->fragsize) {
941 if (datalen > cork->gso_size * UDP_MAX_SEGMENTS) {
945 if (sk->sk_no_check_tx) {
949 if (skb->ip_summed != CHECKSUM_PARTIAL || is_udplite ||
950 dst_xfrm(skb_dst(skb))) {
955 if (datalen > cork->gso_size) {
956 skb_shinfo(skb)->gso_size = cork->gso_size;
957 skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4;
958 skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(datalen,
964 if (is_udplite) /* UDP-Lite */
965 csum = udplite_csum(skb);
967 else if (sk->sk_no_check_tx) { /* UDP csum off */
969 skb->ip_summed = CHECKSUM_NONE;
972 } else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
975 udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
979 csum = udp_csum(skb);
981 /* add protocol-dependent pseudo-header */
982 uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
983 sk->sk_protocol, csum);
985 uh->check = CSUM_MANGLED_0;
988 err = ip_send_skb(sock_net(sk), skb);
990 if (err == -ENOBUFS && !inet->recverr) {
991 UDP_INC_STATS(sock_net(sk),
992 UDP_MIB_SNDBUFERRORS, is_udplite);
996 UDP_INC_STATS(sock_net(sk),
997 UDP_MIB_OUTDATAGRAMS, is_udplite);
1002 * Push out all pending data as one UDP datagram. Socket is locked.
1004 int udp_push_pending_frames(struct sock *sk)
1006 struct udp_sock *up = udp_sk(sk);
1007 struct inet_sock *inet = inet_sk(sk);
1008 struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
1009 struct sk_buff *skb;
1012 skb = ip_finish_skb(sk, fl4);
1016 err = udp_send_skb(skb, fl4, &inet->cork.base);
1020 WRITE_ONCE(up->pending, 0);
1023 EXPORT_SYMBOL(udp_push_pending_frames);
1025 static int __udp_cmsg_send(struct cmsghdr *cmsg, u16 *gso_size)
1027 switch (cmsg->cmsg_type) {
1029 if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u16)))
1031 *gso_size = *(__u16 *)CMSG_DATA(cmsg);
1038 int udp_cmsg_send(struct sock *sk, struct msghdr *msg, u16 *gso_size)
1040 struct cmsghdr *cmsg;
1041 bool need_ip = false;
1044 for_each_cmsghdr(cmsg, msg) {
1045 if (!CMSG_OK(msg, cmsg))
1048 if (cmsg->cmsg_level != SOL_UDP) {
1053 err = __udp_cmsg_send(cmsg, gso_size);
1060 EXPORT_SYMBOL_GPL(udp_cmsg_send);
1062 int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1064 struct inet_sock *inet = inet_sk(sk);
1065 struct udp_sock *up = udp_sk(sk);
1066 DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
1067 struct flowi4 fl4_stack;
1070 struct ipcm_cookie ipc;
1071 struct rtable *rt = NULL;
1074 __be32 daddr, faddr, saddr;
1077 int err, is_udplite = IS_UDPLITE(sk);
1078 int corkreq = udp_test_bit(CORK, sk) || msg->msg_flags & MSG_MORE;
1079 int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
1080 struct sk_buff *skb;
1081 struct ip_options_data opt_copy;
1090 if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
1093 getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
1095 fl4 = &inet->cork.fl.u.ip4;
1096 if (READ_ONCE(up->pending)) {
1098 * There are pending frames.
1099 * The socket lock must be held while it's corked.
1102 if (likely(up->pending)) {
1103 if (unlikely(up->pending != AF_INET)) {
1107 goto do_append_data;
1111 ulen += sizeof(struct udphdr);
1114 * Get and verify the address.
1117 if (msg->msg_namelen < sizeof(*usin))
1119 if (usin->sin_family != AF_INET) {
1120 if (usin->sin_family != AF_UNSPEC)
1121 return -EAFNOSUPPORT;
1124 daddr = usin->sin_addr.s_addr;
1125 dport = usin->sin_port;
1129 if (sk->sk_state != TCP_ESTABLISHED)
1130 return -EDESTADDRREQ;
1131 daddr = inet->inet_daddr;
1132 dport = inet->inet_dport;
1133 /* Open fast path for connected socket.
1134 Route will not be used, if at least one option is set.
1139 ipcm_init_sk(&ipc, inet);
1140 ipc.gso_size = READ_ONCE(up->gso_size);
1142 if (msg->msg_controllen) {
1143 err = udp_cmsg_send(sk, msg, &ipc.gso_size);
1145 err = ip_cmsg_send(sk, msg, &ipc,
1146 sk->sk_family == AF_INET6);
1149 if (unlikely(err < 0)) {
1157 struct ip_options_rcu *inet_opt;
1160 inet_opt = rcu_dereference(inet->inet_opt);
1162 memcpy(&opt_copy, inet_opt,
1163 sizeof(*inet_opt) + inet_opt->opt.optlen);
1164 ipc.opt = &opt_copy.opt;
1169 if (cgroup_bpf_enabled(CGROUP_UDP4_SENDMSG) && !connected) {
1170 err = BPF_CGROUP_RUN_PROG_UDP4_SENDMSG_LOCK(sk,
1171 (struct sockaddr *)usin, &ipc.addr);
1175 if (usin->sin_port == 0) {
1176 /* BPF program set invalid port. Reject it. */
1180 daddr = usin->sin_addr.s_addr;
1181 dport = usin->sin_port;
1186 ipc.addr = faddr = daddr;
1188 if (ipc.opt && ipc.opt->opt.srr) {
1193 faddr = ipc.opt->opt.faddr;
1196 tos = get_rttos(&ipc, inet);
1197 if (sock_flag(sk, SOCK_LOCALROUTE) ||
1198 (msg->msg_flags & MSG_DONTROUTE) ||
1199 (ipc.opt && ipc.opt->opt.is_strictroute)) {
1204 if (ipv4_is_multicast(daddr)) {
1205 if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif))
1206 ipc.oif = inet->mc_index;
1208 saddr = inet->mc_addr;
1210 } else if (!ipc.oif) {
1211 ipc.oif = inet->uc_index;
1212 } else if (ipv4_is_lbcast(daddr) && inet->uc_index) {
1213 /* oif is set, packet is to local broadcast and
1214 * uc_index is set. oif is most likely set
1215 * by sk_bound_dev_if. If uc_index != oif check if the
1216 * oif is an L3 master and uc_index is an L3 slave.
1217 * If so, we want to allow the send using the uc_index.
1219 if (ipc.oif != inet->uc_index &&
1220 ipc.oif == l3mdev_master_ifindex_by_index(sock_net(sk),
1222 ipc.oif = inet->uc_index;
1227 rt = (struct rtable *)sk_dst_check(sk, 0);
1230 struct net *net = sock_net(sk);
1231 __u8 flow_flags = inet_sk_flowi_flags(sk);
1235 flowi4_init_output(fl4, ipc.oif, ipc.sockc.mark, tos,
1236 RT_SCOPE_UNIVERSE, sk->sk_protocol,
1238 faddr, saddr, dport, inet->inet_sport,
1241 security_sk_classify_flow(sk, flowi4_to_flowi_common(fl4));
1242 rt = ip_route_output_flow(net, fl4, sk);
1246 if (err == -ENETUNREACH)
1247 IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
1252 if ((rt->rt_flags & RTCF_BROADCAST) &&
1253 !sock_flag(sk, SOCK_BROADCAST))
1256 sk_dst_set(sk, dst_clone(&rt->dst));
1259 if (msg->msg_flags&MSG_CONFIRM)
1265 daddr = ipc.addr = fl4->daddr;
1267 /* Lockless fast path for the non-corking case. */
1269 struct inet_cork cork;
1271 skb = ip_make_skb(sk, fl4, getfrag, msg, ulen,
1272 sizeof(struct udphdr), &ipc, &rt,
1273 &cork, msg->msg_flags);
1275 if (!IS_ERR_OR_NULL(skb))
1276 err = udp_send_skb(skb, fl4, &cork);
1281 if (unlikely(up->pending)) {
1282 /* The socket is already corked while preparing it. */
1283 /* ... which is an evident application bug. --ANK */
1286 net_dbg_ratelimited("socket already corked\n");
1291 * Now cork the socket to pend data.
1293 fl4 = &inet->cork.fl.u.ip4;
1296 fl4->fl4_dport = dport;
1297 fl4->fl4_sport = inet->inet_sport;
1298 WRITE_ONCE(up->pending, AF_INET);
1302 err = ip_append_data(sk, fl4, getfrag, msg, ulen,
1303 sizeof(struct udphdr), &ipc, &rt,
1304 corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
1306 udp_flush_pending_frames(sk);
1308 err = udp_push_pending_frames(sk);
1309 else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
1310 WRITE_ONCE(up->pending, 0);
1321 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting
1322 * ENOBUFS might not be good (it's not tunable per se), but otherwise
1323 * we don't have a good statistic (IpOutDiscards but it can be too many
1324 * things). We could add another new stat but at least for now that
1325 * seems like overkill.
1327 if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
1328 UDP_INC_STATS(sock_net(sk),
1329 UDP_MIB_SNDBUFERRORS, is_udplite);
1334 if (msg->msg_flags & MSG_PROBE)
1335 dst_confirm_neigh(&rt->dst, &fl4->daddr);
1336 if (!(msg->msg_flags&MSG_PROBE) || len)
1337 goto back_from_confirm;
1341 EXPORT_SYMBOL(udp_sendmsg);
1343 void udp_splice_eof(struct socket *sock)
1345 struct sock *sk = sock->sk;
1346 struct udp_sock *up = udp_sk(sk);
1348 if (!READ_ONCE(up->pending) || udp_test_bit(CORK, sk))
1352 if (up->pending && !udp_test_bit(CORK, sk))
1353 udp_push_pending_frames(sk);
1356 EXPORT_SYMBOL_GPL(udp_splice_eof);
1358 int udp_sendpage(struct sock *sk, struct page *page, int offset,
1359 size_t size, int flags)
1361 struct bio_vec bvec;
1362 struct msghdr msg = { .msg_flags = flags | MSG_SPLICE_PAGES };
1364 if (flags & MSG_SENDPAGE_NOTLAST)
1365 msg.msg_flags |= MSG_MORE;
1367 bvec_set_page(&bvec, page, size, offset);
1368 iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, &bvec, 1, size);
1369 return udp_sendmsg(sk, &msg, size);
1372 #define UDP_SKB_IS_STATELESS 0x80000000
1374 /* all head states (dst, sk, nf conntrack) except skb extensions are
1375 * cleared by udp_rcv().
1377 * We need to preserve secpath, if present, to eventually process
1378 * IP_CMSG_PASSSEC at recvmsg() time.
1380 * Other extensions can be cleared.
1382 static bool udp_try_make_stateless(struct sk_buff *skb)
1384 if (!skb_has_extensions(skb))
1387 if (!secpath_exists(skb)) {
1395 static void udp_set_dev_scratch(struct sk_buff *skb)
1397 struct udp_dev_scratch *scratch = udp_skb_scratch(skb);
1399 BUILD_BUG_ON(sizeof(struct udp_dev_scratch) > sizeof(long));
1400 scratch->_tsize_state = skb->truesize;
1401 #if BITS_PER_LONG == 64
1402 scratch->len = skb->len;
1403 scratch->csum_unnecessary = !!skb_csum_unnecessary(skb);
1404 scratch->is_linear = !skb_is_nonlinear(skb);
1406 if (udp_try_make_stateless(skb))
1407 scratch->_tsize_state |= UDP_SKB_IS_STATELESS;
1410 static void udp_skb_csum_unnecessary_set(struct sk_buff *skb)
1412 /* We come here after udp_lib_checksum_complete() returned 0.
1413 * This means that __skb_checksum_complete() might have
1414 * set skb->csum_valid to 1.
1415 * On 64bit platforms, we can set csum_unnecessary
1416 * to true, but only if the skb is not shared.
1418 #if BITS_PER_LONG == 64
1419 if (!skb_shared(skb))
1420 udp_skb_scratch(skb)->csum_unnecessary = true;
1424 static int udp_skb_truesize(struct sk_buff *skb)
1426 return udp_skb_scratch(skb)->_tsize_state & ~UDP_SKB_IS_STATELESS;
1429 static bool udp_skb_has_head_state(struct sk_buff *skb)
1431 return !(udp_skb_scratch(skb)->_tsize_state & UDP_SKB_IS_STATELESS);
1434 /* fully reclaim rmem/fwd memory allocated for skb */
1435 static void udp_rmem_release(struct sock *sk, int size, int partial,
1436 bool rx_queue_lock_held)
1438 struct udp_sock *up = udp_sk(sk);
1439 struct sk_buff_head *sk_queue;
1442 if (likely(partial)) {
1443 up->forward_deficit += size;
1444 size = up->forward_deficit;
1445 if (size < (sk->sk_rcvbuf >> 2) &&
1446 !skb_queue_empty(&up->reader_queue))
1449 size += up->forward_deficit;
1451 up->forward_deficit = 0;
1453 /* acquire the sk_receive_queue for fwd allocated memory scheduling,
1454 * if the called don't held it already
1456 sk_queue = &sk->sk_receive_queue;
1457 if (!rx_queue_lock_held)
1458 spin_lock(&sk_queue->lock);
1461 sk_forward_alloc_add(sk, size);
1462 amt = (sk->sk_forward_alloc - partial) & ~(PAGE_SIZE - 1);
1463 sk_forward_alloc_add(sk, -amt);
1466 __sk_mem_reduce_allocated(sk, amt >> PAGE_SHIFT);
1468 atomic_sub(size, &sk->sk_rmem_alloc);
1470 /* this can save us from acquiring the rx queue lock on next receive */
1471 skb_queue_splice_tail_init(sk_queue, &up->reader_queue);
1473 if (!rx_queue_lock_held)
1474 spin_unlock(&sk_queue->lock);
1477 /* Note: called with reader_queue.lock held.
1478 * Instead of using skb->truesize here, find a copy of it in skb->dev_scratch
1479 * This avoids a cache line miss while receive_queue lock is held.
1480 * Look at __udp_enqueue_schedule_skb() to find where this copy is done.
1482 void udp_skb_destructor(struct sock *sk, struct sk_buff *skb)
1484 prefetch(&skb->data);
1485 udp_rmem_release(sk, udp_skb_truesize(skb), 1, false);
1487 EXPORT_SYMBOL(udp_skb_destructor);
1489 /* as above, but the caller held the rx queue lock, too */
1490 static void udp_skb_dtor_locked(struct sock *sk, struct sk_buff *skb)
1492 prefetch(&skb->data);
1493 udp_rmem_release(sk, udp_skb_truesize(skb), 1, true);
1496 /* Idea of busylocks is to let producers grab an extra spinlock
1497 * to relieve pressure on the receive_queue spinlock shared by consumer.
1498 * Under flood, this means that only one producer can be in line
1499 * trying to acquire the receive_queue spinlock.
1500 * These busylock can be allocated on a per cpu manner, instead of a
1501 * per socket one (that would consume a cache line per socket)
1503 static int udp_busylocks_log __read_mostly;
1504 static spinlock_t *udp_busylocks __read_mostly;
1506 static spinlock_t *busylock_acquire(void *ptr)
1510 busy = udp_busylocks + hash_ptr(ptr, udp_busylocks_log);
1515 static void busylock_release(spinlock_t *busy)
1521 int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb)
1523 struct sk_buff_head *list = &sk->sk_receive_queue;
1524 int rmem, delta, amt, err = -ENOMEM;
1525 spinlock_t *busy = NULL;
1528 /* try to avoid the costly atomic add/sub pair when the receive
1529 * queue is full; always allow at least a packet
1531 rmem = atomic_read(&sk->sk_rmem_alloc);
1532 if (rmem > sk->sk_rcvbuf)
1535 /* Under mem pressure, it might be helpful to help udp_recvmsg()
1536 * having linear skbs :
1537 * - Reduce memory overhead and thus increase receive queue capacity
1538 * - Less cache line misses at copyout() time
1539 * - Less work at consume_skb() (less alien page frag freeing)
1541 if (rmem > (sk->sk_rcvbuf >> 1)) {
1544 busy = busylock_acquire(sk);
1546 size = skb->truesize;
1547 udp_set_dev_scratch(skb);
1549 /* we drop only if the receive buf is full and the receive
1550 * queue contains some other skb
1552 rmem = atomic_add_return(size, &sk->sk_rmem_alloc);
1553 if (rmem > (size + (unsigned int)sk->sk_rcvbuf))
1556 spin_lock(&list->lock);
1557 if (size >= sk->sk_forward_alloc) {
1558 amt = sk_mem_pages(size);
1559 delta = amt << PAGE_SHIFT;
1560 if (!__sk_mem_raise_allocated(sk, delta, amt, SK_MEM_RECV)) {
1562 spin_unlock(&list->lock);
1566 sk->sk_forward_alloc += delta;
1569 sk_forward_alloc_add(sk, -size);
1571 /* no need to setup a destructor, we will explicitly release the
1572 * forward allocated memory on dequeue
1574 sock_skb_set_dropcount(sk, skb);
1576 __skb_queue_tail(list, skb);
1577 spin_unlock(&list->lock);
1579 if (!sock_flag(sk, SOCK_DEAD))
1580 sk->sk_data_ready(sk);
1582 busylock_release(busy);
1586 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
1589 atomic_inc(&sk->sk_drops);
1590 busylock_release(busy);
1593 EXPORT_SYMBOL_GPL(__udp_enqueue_schedule_skb);
1595 void udp_destruct_common(struct sock *sk)
1597 /* reclaim completely the forward allocated memory */
1598 struct udp_sock *up = udp_sk(sk);
1599 unsigned int total = 0;
1600 struct sk_buff *skb;
1602 skb_queue_splice_tail_init(&sk->sk_receive_queue, &up->reader_queue);
1603 while ((skb = __skb_dequeue(&up->reader_queue)) != NULL) {
1604 total += skb->truesize;
1607 udp_rmem_release(sk, total, 0, true);
1609 EXPORT_SYMBOL_GPL(udp_destruct_common);
1611 static void udp_destruct_sock(struct sock *sk)
1613 udp_destruct_common(sk);
1614 inet_sock_destruct(sk);
1617 int udp_init_sock(struct sock *sk)
1619 skb_queue_head_init(&udp_sk(sk)->reader_queue);
1620 sk->sk_destruct = udp_destruct_sock;
1621 set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
1625 void skb_consume_udp(struct sock *sk, struct sk_buff *skb, int len)
1627 if (unlikely(READ_ONCE(sk->sk_peek_off) >= 0)) {
1628 bool slow = lock_sock_fast(sk);
1630 sk_peek_offset_bwd(sk, len);
1631 unlock_sock_fast(sk, slow);
1634 if (!skb_unref(skb))
1637 /* In the more common cases we cleared the head states previously,
1638 * see __udp_queue_rcv_skb().
1640 if (unlikely(udp_skb_has_head_state(skb)))
1641 skb_release_head_state(skb);
1642 __consume_stateless_skb(skb);
1644 EXPORT_SYMBOL_GPL(skb_consume_udp);
1646 static struct sk_buff *__first_packet_length(struct sock *sk,
1647 struct sk_buff_head *rcvq,
1650 struct sk_buff *skb;
1652 while ((skb = skb_peek(rcvq)) != NULL) {
1653 if (udp_lib_checksum_complete(skb)) {
1654 __UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS,
1656 __UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS,
1658 atomic_inc(&sk->sk_drops);
1659 __skb_unlink(skb, rcvq);
1660 *total += skb->truesize;
1663 udp_skb_csum_unnecessary_set(skb);
1671 * first_packet_length - return length of first packet in receive queue
1674 * Drops all bad checksum frames, until a valid one is found.
1675 * Returns the length of found skb, or -1 if none is found.
1677 static int first_packet_length(struct sock *sk)
1679 struct sk_buff_head *rcvq = &udp_sk(sk)->reader_queue;
1680 struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
1681 struct sk_buff *skb;
1685 spin_lock_bh(&rcvq->lock);
1686 skb = __first_packet_length(sk, rcvq, &total);
1687 if (!skb && !skb_queue_empty_lockless(sk_queue)) {
1688 spin_lock(&sk_queue->lock);
1689 skb_queue_splice_tail_init(sk_queue, rcvq);
1690 spin_unlock(&sk_queue->lock);
1692 skb = __first_packet_length(sk, rcvq, &total);
1694 res = skb ? skb->len : -1;
1696 udp_rmem_release(sk, total, 1, false);
1697 spin_unlock_bh(&rcvq->lock);
1702 * IOCTL requests applicable to the UDP protocol
1705 int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
1710 int amount = sk_wmem_alloc_get(sk);
1712 return put_user(amount, (int __user *)arg);
1717 int amount = max_t(int, 0, first_packet_length(sk));
1719 return put_user(amount, (int __user *)arg);
1723 return -ENOIOCTLCMD;
1728 EXPORT_SYMBOL(udp_ioctl);
1730 struct sk_buff *__skb_recv_udp(struct sock *sk, unsigned int flags,
1733 struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
1734 struct sk_buff_head *queue;
1735 struct sk_buff *last;
1739 queue = &udp_sk(sk)->reader_queue;
1740 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1742 struct sk_buff *skb;
1744 error = sock_error(sk);
1750 spin_lock_bh(&queue->lock);
1751 skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1754 if (!(flags & MSG_PEEK))
1755 udp_skb_destructor(sk, skb);
1756 spin_unlock_bh(&queue->lock);
1760 if (skb_queue_empty_lockless(sk_queue)) {
1761 spin_unlock_bh(&queue->lock);
1765 /* refill the reader queue and walk it again
1766 * keep both queues locked to avoid re-acquiring
1767 * the sk_receive_queue lock if fwd memory scheduling
1770 spin_lock(&sk_queue->lock);
1771 skb_queue_splice_tail_init(sk_queue, queue);
1773 skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1775 if (skb && !(flags & MSG_PEEK))
1776 udp_skb_dtor_locked(sk, skb);
1777 spin_unlock(&sk_queue->lock);
1778 spin_unlock_bh(&queue->lock);
1783 if (!sk_can_busy_loop(sk))
1786 sk_busy_loop(sk, flags & MSG_DONTWAIT);
1787 } while (!skb_queue_empty_lockless(sk_queue));
1789 /* sk_queue is empty, reader_queue may contain peeked packets */
1791 !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,
1793 (struct sk_buff *)sk_queue));
1798 EXPORT_SYMBOL(__skb_recv_udp);
1800 int udp_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
1802 struct sk_buff *skb;
1806 skb = skb_recv_udp(sk, MSG_DONTWAIT, &err);
1810 if (udp_lib_checksum_complete(skb)) {
1811 int is_udplite = IS_UDPLITE(sk);
1812 struct net *net = sock_net(sk);
1814 __UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, is_udplite);
1815 __UDP_INC_STATS(net, UDP_MIB_INERRORS, is_udplite);
1816 atomic_inc(&sk->sk_drops);
1821 WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk));
1822 return recv_actor(sk, skb);
1824 EXPORT_SYMBOL(udp_read_skb);
1827 * This should be easy, if there is something there we
1828 * return it, otherwise we block.
1831 int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags,
1834 struct inet_sock *inet = inet_sk(sk);
1835 DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
1836 struct sk_buff *skb;
1837 unsigned int ulen, copied;
1838 int off, err, peeking = flags & MSG_PEEK;
1839 int is_udplite = IS_UDPLITE(sk);
1840 bool checksum_valid = false;
1842 if (flags & MSG_ERRQUEUE)
1843 return ip_recv_error(sk, msg, len, addr_len);
1846 off = sk_peek_offset(sk, flags);
1847 skb = __skb_recv_udp(sk, flags, &off, &err);
1851 ulen = udp_skb_len(skb);
1853 if (copied > ulen - off)
1854 copied = ulen - off;
1855 else if (copied < ulen)
1856 msg->msg_flags |= MSG_TRUNC;
1859 * If checksum is needed at all, try to do it while copying the
1860 * data. If the data is truncated, or if we only want a partial
1861 * coverage checksum (UDP-Lite), do it before the copy.
1864 if (copied < ulen || peeking ||
1865 (is_udplite && UDP_SKB_CB(skb)->partial_cov)) {
1866 checksum_valid = udp_skb_csum_unnecessary(skb) ||
1867 !__udp_lib_checksum_complete(skb);
1868 if (!checksum_valid)
1872 if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
1873 if (udp_skb_is_linear(skb))
1874 err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
1876 err = skb_copy_datagram_msg(skb, off, msg, copied);
1878 err = skb_copy_and_csum_datagram_msg(skb, off, msg);
1884 if (unlikely(err)) {
1886 atomic_inc(&sk->sk_drops);
1887 UDP_INC_STATS(sock_net(sk),
1888 UDP_MIB_INERRORS, is_udplite);
1895 UDP_INC_STATS(sock_net(sk),
1896 UDP_MIB_INDATAGRAMS, is_udplite);
1898 sock_recv_cmsgs(msg, sk, skb);
1900 /* Copy the address. */
1902 sin->sin_family = AF_INET;
1903 sin->sin_port = udp_hdr(skb)->source;
1904 sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
1905 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
1906 *addr_len = sizeof(*sin);
1908 BPF_CGROUP_RUN_PROG_UDP4_RECVMSG_LOCK(sk,
1909 (struct sockaddr *)sin);
1912 if (udp_test_bit(GRO_ENABLED, sk))
1913 udp_cmsg_recv(msg, sk, skb);
1915 if (inet->cmsg_flags)
1916 ip_cmsg_recv_offset(msg, sk, skb, sizeof(struct udphdr), off);
1919 if (flags & MSG_TRUNC)
1922 skb_consume_udp(sk, skb, peeking ? -err : err);
1926 if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags,
1927 udp_skb_destructor)) {
1928 UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
1929 UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
1933 /* starting over for a new packet, but check if we need to yield */
1935 msg->msg_flags &= ~MSG_TRUNC;
1939 int udp_pre_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
1941 /* This check is replicated from __ip4_datagram_connect() and
1942 * intended to prevent BPF program called below from accessing bytes
1943 * that are out of the bound specified by user in addr_len.
1945 if (addr_len < sizeof(struct sockaddr_in))
1948 return BPF_CGROUP_RUN_PROG_INET4_CONNECT_LOCK(sk, uaddr);
1950 EXPORT_SYMBOL(udp_pre_connect);
1952 int __udp_disconnect(struct sock *sk, int flags)
1954 struct inet_sock *inet = inet_sk(sk);
1956 * 1003.1g - break association.
1959 sk->sk_state = TCP_CLOSE;
1960 inet->inet_daddr = 0;
1961 inet->inet_dport = 0;
1962 sock_rps_reset_rxhash(sk);
1963 sk->sk_bound_dev_if = 0;
1964 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) {
1965 inet_reset_saddr(sk);
1966 if (sk->sk_prot->rehash &&
1967 (sk->sk_userlocks & SOCK_BINDPORT_LOCK))
1968 sk->sk_prot->rehash(sk);
1971 if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
1972 sk->sk_prot->unhash(sk);
1973 inet->inet_sport = 0;
1978 EXPORT_SYMBOL(__udp_disconnect);
1980 int udp_disconnect(struct sock *sk, int flags)
1983 __udp_disconnect(sk, flags);
1987 EXPORT_SYMBOL(udp_disconnect);
1989 void udp_lib_unhash(struct sock *sk)
1991 if (sk_hashed(sk)) {
1992 struct udp_table *udptable = sk->sk_prot->h.udp_table;
1993 struct udp_hslot *hslot, *hslot2;
1995 hslot = udp_hashslot(udptable, sock_net(sk),
1996 udp_sk(sk)->udp_port_hash);
1997 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
1999 spin_lock_bh(&hslot->lock);
2000 if (rcu_access_pointer(sk->sk_reuseport_cb))
2001 reuseport_detach_sock(sk);
2002 if (sk_del_node_init_rcu(sk)) {
2004 inet_sk(sk)->inet_num = 0;
2005 sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
2007 spin_lock(&hslot2->lock);
2008 hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
2010 spin_unlock(&hslot2->lock);
2012 spin_unlock_bh(&hslot->lock);
2015 EXPORT_SYMBOL(udp_lib_unhash);
2018 * inet_rcv_saddr was changed, we must rehash secondary hash
2020 void udp_lib_rehash(struct sock *sk, u16 newhash)
2022 if (sk_hashed(sk)) {
2023 struct udp_table *udptable = sk->sk_prot->h.udp_table;
2024 struct udp_hslot *hslot, *hslot2, *nhslot2;
2026 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
2027 nhslot2 = udp_hashslot2(udptable, newhash);
2028 udp_sk(sk)->udp_portaddr_hash = newhash;
2030 if (hslot2 != nhslot2 ||
2031 rcu_access_pointer(sk->sk_reuseport_cb)) {
2032 hslot = udp_hashslot(udptable, sock_net(sk),
2033 udp_sk(sk)->udp_port_hash);
2034 /* we must lock primary chain too */
2035 spin_lock_bh(&hslot->lock);
2036 if (rcu_access_pointer(sk->sk_reuseport_cb))
2037 reuseport_detach_sock(sk);
2039 if (hslot2 != nhslot2) {
2040 spin_lock(&hslot2->lock);
2041 hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
2043 spin_unlock(&hslot2->lock);
2045 spin_lock(&nhslot2->lock);
2046 hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
2049 spin_unlock(&nhslot2->lock);
2052 spin_unlock_bh(&hslot->lock);
2056 EXPORT_SYMBOL(udp_lib_rehash);
2058 void udp_v4_rehash(struct sock *sk)
2060 u16 new_hash = ipv4_portaddr_hash(sock_net(sk),
2061 inet_sk(sk)->inet_rcv_saddr,
2062 inet_sk(sk)->inet_num);
2063 udp_lib_rehash(sk, new_hash);
2066 static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2070 if (inet_sk(sk)->inet_daddr) {
2071 sock_rps_save_rxhash(sk, skb);
2072 sk_mark_napi_id(sk, skb);
2073 sk_incoming_cpu_update(sk);
2075 sk_mark_napi_id_once(sk, skb);
2078 rc = __udp_enqueue_schedule_skb(sk, skb);
2080 int is_udplite = IS_UDPLITE(sk);
2083 /* Note that an ENOMEM error is charged twice */
2084 if (rc == -ENOMEM) {
2085 UDP_INC_STATS(sock_net(sk), UDP_MIB_RCVBUFERRORS,
2087 drop_reason = SKB_DROP_REASON_SOCKET_RCVBUFF;
2089 UDP_INC_STATS(sock_net(sk), UDP_MIB_MEMERRORS,
2091 drop_reason = SKB_DROP_REASON_PROTO_MEM;
2093 UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
2094 kfree_skb_reason(skb, drop_reason);
2095 trace_udp_fail_queue_rcv_skb(rc, sk);
2105 * >0: "udp encap" protocol resubmission
2107 * Note that in the success and error cases, the skb is assumed to
2108 * have either been requeued or freed.
2110 static int udp_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
2112 int drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2113 struct udp_sock *up = udp_sk(sk);
2114 int is_udplite = IS_UDPLITE(sk);
2117 * Charge it to the socket, dropping if the queue is full.
2119 if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
2120 drop_reason = SKB_DROP_REASON_XFRM_POLICY;
2125 if (static_branch_unlikely(&udp_encap_needed_key) &&
2126 READ_ONCE(up->encap_type)) {
2127 int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
2130 * This is an encapsulation socket so pass the skb to
2131 * the socket's udp_encap_rcv() hook. Otherwise, just
2132 * fall through and pass this up the UDP socket.
2133 * up->encap_rcv() returns the following value:
2134 * =0 if skb was successfully passed to the encap
2135 * handler or was discarded by it.
2136 * >0 if skb should be passed on to UDP.
2137 * <0 if skb should be resubmitted as proto -N
2140 /* if we're overly short, let UDP handle it */
2141 encap_rcv = READ_ONCE(up->encap_rcv);
2145 /* Verify checksum before giving to encap */
2146 if (udp_lib_checksum_complete(skb))
2149 ret = encap_rcv(sk, skb);
2151 __UDP_INC_STATS(sock_net(sk),
2152 UDP_MIB_INDATAGRAMS,
2158 /* FALLTHROUGH -- it's a UDP Packet */
2162 * UDP-Lite specific tests, ignored on UDP sockets
2164 if ((up->pcflag & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) {
2167 * MIB statistics other than incrementing the error count are
2168 * disabled for the following two types of errors: these depend
2169 * on the application settings, not on the functioning of the
2170 * protocol stack as such.
2172 * RFC 3828 here recommends (sec 3.3): "There should also be a
2173 * way ... to ... at least let the receiving application block
2174 * delivery of packets with coverage values less than a value
2175 * provided by the application."
2177 if (up->pcrlen == 0) { /* full coverage was set */
2178 net_dbg_ratelimited("UDPLite: partial coverage %d while full coverage %d requested\n",
2179 UDP_SKB_CB(skb)->cscov, skb->len);
2182 /* The next case involves violating the min. coverage requested
2183 * by the receiver. This is subtle: if receiver wants x and x is
2184 * greater than the buffersize/MTU then receiver will complain
2185 * that it wants x while sender emits packets of smaller size y.
2186 * Therefore the above ...()->partial_cov statement is essential.
2188 if (UDP_SKB_CB(skb)->cscov < up->pcrlen) {
2189 net_dbg_ratelimited("UDPLite: coverage %d too small, need min %d\n",
2190 UDP_SKB_CB(skb)->cscov, up->pcrlen);
2195 prefetch(&sk->sk_rmem_alloc);
2196 if (rcu_access_pointer(sk->sk_filter) &&
2197 udp_lib_checksum_complete(skb))
2200 if (sk_filter_trim_cap(sk, skb, sizeof(struct udphdr))) {
2201 drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
2205 udp_csum_pull_header(skb);
2207 ipv4_pktinfo_prepare(sk, skb, true);
2208 return __udp_queue_rcv_skb(sk, skb);
2211 drop_reason = SKB_DROP_REASON_UDP_CSUM;
2212 __UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
2214 __UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
2215 atomic_inc(&sk->sk_drops);
2216 kfree_skb_reason(skb, drop_reason);
2220 static int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2222 struct sk_buff *next, *segs;
2225 if (likely(!udp_unexpected_gso(sk, skb)))
2226 return udp_queue_rcv_one_skb(sk, skb);
2228 BUILD_BUG_ON(sizeof(struct udp_skb_cb) > SKB_GSO_CB_OFFSET);
2229 __skb_push(skb, -skb_mac_offset(skb));
2230 segs = udp_rcv_segment(sk, skb, true);
2231 skb_list_walk_safe(segs, skb, next) {
2232 __skb_pull(skb, skb_transport_offset(skb));
2234 udp_post_segment_fix_csum(skb);
2235 ret = udp_queue_rcv_one_skb(sk, skb);
2237 ip_protocol_deliver_rcu(dev_net(skb->dev), skb, ret);
2242 /* For TCP sockets, sk_rx_dst is protected by socket lock
2243 * For UDP, we use xchg() to guard against concurrent changes.
2245 bool udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
2247 struct dst_entry *old;
2249 if (dst_hold_safe(dst)) {
2250 old = xchg((__force struct dst_entry **)&sk->sk_rx_dst, dst);
2256 EXPORT_SYMBOL(udp_sk_rx_dst_set);
2259 * Multicasts and broadcasts go to each listener.
2261 * Note: called only from the BH handler context.
2263 static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
2265 __be32 saddr, __be32 daddr,
2266 struct udp_table *udptable,
2269 struct sock *sk, *first = NULL;
2270 unsigned short hnum = ntohs(uh->dest);
2271 struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum);
2272 unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10);
2273 unsigned int offset = offsetof(typeof(*sk), sk_node);
2274 int dif = skb->dev->ifindex;
2275 int sdif = inet_sdif(skb);
2276 struct hlist_node *node;
2277 struct sk_buff *nskb;
2280 hash2_any = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum) &
2282 hash2 = ipv4_portaddr_hash(net, daddr, hnum) & udptable->mask;
2284 hslot = &udptable->hash2[hash2];
2285 offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
2288 sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
2289 if (!__udp_is_mcast_sock(net, sk, uh->dest, daddr,
2290 uh->source, saddr, dif, sdif, hnum))
2297 nskb = skb_clone(skb, GFP_ATOMIC);
2299 if (unlikely(!nskb)) {
2300 atomic_inc(&sk->sk_drops);
2301 __UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS,
2303 __UDP_INC_STATS(net, UDP_MIB_INERRORS,
2307 if (udp_queue_rcv_skb(sk, nskb) > 0)
2311 /* Also lookup *:port if we are using hash2 and haven't done so yet. */
2312 if (use_hash2 && hash2 != hash2_any) {
2318 if (udp_queue_rcv_skb(first, skb) > 0)
2322 __UDP_INC_STATS(net, UDP_MIB_IGNOREDMULTI,
2323 proto == IPPROTO_UDPLITE);
2328 /* Initialize UDP checksum. If exited with zero value (success),
2329 * CHECKSUM_UNNECESSARY means, that no more checks are required.
2330 * Otherwise, csum completion requires checksumming packet body,
2331 * including udp header and folding it to skb->csum.
2333 static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
2338 UDP_SKB_CB(skb)->partial_cov = 0;
2339 UDP_SKB_CB(skb)->cscov = skb->len;
2341 if (proto == IPPROTO_UDPLITE) {
2342 err = udplite_checksum_init(skb, uh);
2346 if (UDP_SKB_CB(skb)->partial_cov) {
2347 skb->csum = inet_compute_pseudo(skb, proto);
2352 /* Note, we are only interested in != 0 or == 0, thus the
2355 err = (__force int)skb_checksum_init_zero_check(skb, proto, uh->check,
2356 inet_compute_pseudo);
2360 if (skb->ip_summed == CHECKSUM_COMPLETE && !skb->csum_valid) {
2361 /* If SW calculated the value, we know it's bad */
2362 if (skb->csum_complete_sw)
2365 /* HW says the value is bad. Let's validate that.
2366 * skb->csum is no longer the full packet checksum,
2367 * so don't treat it as such.
2369 skb_checksum_complete_unset(skb);
2375 /* wrapper for udp_queue_rcv_skb tacking care of csum conversion and
2376 * return code conversion for ip layer consumption
2378 static int udp_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb,
2383 if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk))
2384 skb_checksum_try_convert(skb, IPPROTO_UDP, inet_compute_pseudo);
2386 ret = udp_queue_rcv_skb(sk, skb);
2388 /* a return value > 0 means to resubmit the input, but
2389 * it wants the return to be -protocol, or 0
2397 * All we need to do is get the socket, and then do a checksum.
2400 int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
2405 unsigned short ulen;
2406 struct rtable *rt = skb_rtable(skb);
2407 __be32 saddr, daddr;
2408 struct net *net = dev_net(skb->dev);
2412 drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2415 * Validate the packet.
2417 if (!pskb_may_pull(skb, sizeof(struct udphdr)))
2418 goto drop; /* No space for header. */
2421 ulen = ntohs(uh->len);
2422 saddr = ip_hdr(skb)->saddr;
2423 daddr = ip_hdr(skb)->daddr;
2425 if (ulen > skb->len)
2428 if (proto == IPPROTO_UDP) {
2429 /* UDP validates ulen. */
2430 if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
2435 if (udp4_csum_init(skb, uh, proto))
2438 sk = skb_steal_sock(skb, &refcounted);
2440 struct dst_entry *dst = skb_dst(skb);
2443 if (unlikely(rcu_dereference(sk->sk_rx_dst) != dst))
2444 udp_sk_rx_dst_set(sk, dst);
2446 ret = udp_unicast_rcv_skb(sk, skb, uh);
2452 if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
2453 return __udp4_lib_mcast_deliver(net, skb, uh,
2454 saddr, daddr, udptable, proto);
2456 sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
2458 return udp_unicast_rcv_skb(sk, skb, uh);
2460 if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
2464 /* No socket. Drop packet silently, if checksum is wrong */
2465 if (udp_lib_checksum_complete(skb))
2468 drop_reason = SKB_DROP_REASON_NO_SOCKET;
2469 __UDP_INC_STATS(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
2470 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
2473 * Hmm. We got an UDP packet to a port to which we
2474 * don't wanna listen. Ignore it.
2476 kfree_skb_reason(skb, drop_reason);
2480 drop_reason = SKB_DROP_REASON_PKT_TOO_SMALL;
2481 net_dbg_ratelimited("UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
2482 proto == IPPROTO_UDPLITE ? "Lite" : "",
2483 &saddr, ntohs(uh->source),
2485 &daddr, ntohs(uh->dest));
2490 * RFC1122: OK. Discards the bad packet silently (as far as
2491 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
2493 drop_reason = SKB_DROP_REASON_UDP_CSUM;
2494 net_dbg_ratelimited("UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
2495 proto == IPPROTO_UDPLITE ? "Lite" : "",
2496 &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
2498 __UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
2500 __UDP_INC_STATS(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
2501 kfree_skb_reason(skb, drop_reason);
2505 /* We can only early demux multicast if there is a single matching socket.
2506 * If more than one socket found returns NULL
2508 static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net,
2509 __be16 loc_port, __be32 loc_addr,
2510 __be16 rmt_port, __be32 rmt_addr,
2513 unsigned short hnum = ntohs(loc_port);
2514 struct sock *sk, *result;
2515 struct udp_hslot *hslot;
2518 slot = udp_hashfn(net, hnum, udp_table.mask);
2519 hslot = &udp_table.hash[slot];
2521 /* Do not bother scanning a too big list */
2522 if (hslot->count > 10)
2526 sk_for_each_rcu(sk, &hslot->head) {
2527 if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr,
2528 rmt_port, rmt_addr, dif, sdif, hnum)) {
2538 /* For unicast we should only early demux connected sockets or we can
2539 * break forwarding setups. The chains here can be long so only check
2540 * if the first socket is an exact match and if not move on.
2542 static struct sock *__udp4_lib_demux_lookup(struct net *net,
2543 __be16 loc_port, __be32 loc_addr,
2544 __be16 rmt_port, __be32 rmt_addr,
2547 INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr);
2548 unsigned short hnum = ntohs(loc_port);
2549 unsigned int hash2, slot2;
2550 struct udp_hslot *hslot2;
2554 hash2 = ipv4_portaddr_hash(net, loc_addr, hnum);
2555 slot2 = hash2 & udp_table.mask;
2556 hslot2 = &udp_table.hash2[slot2];
2557 ports = INET_COMBINED_PORTS(rmt_port, hnum);
2559 udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
2560 if (inet_match(net, sk, acookie, ports, dif, sdif))
2562 /* Only check first socket in chain */
2568 int udp_v4_early_demux(struct sk_buff *skb)
2570 struct net *net = dev_net(skb->dev);
2571 struct in_device *in_dev = NULL;
2572 const struct iphdr *iph;
2573 const struct udphdr *uh;
2574 struct sock *sk = NULL;
2575 struct dst_entry *dst;
2576 int dif = skb->dev->ifindex;
2577 int sdif = inet_sdif(skb);
2580 /* validate the packet */
2581 if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)))
2587 if (skb->pkt_type == PACKET_MULTICAST) {
2588 in_dev = __in_dev_get_rcu(skb->dev);
2593 ours = ip_check_mc_rcu(in_dev, iph->daddr, iph->saddr,
2598 sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr,
2599 uh->source, iph->saddr,
2601 } else if (skb->pkt_type == PACKET_HOST) {
2602 sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr,
2603 uh->source, iph->saddr, dif, sdif);
2606 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
2610 skb->destructor = sock_efree;
2611 dst = rcu_dereference(sk->sk_rx_dst);
2614 dst = dst_check(dst, 0);
2618 /* set noref for now.
2619 * any place which wants to hold dst has to call
2622 skb_dst_set_noref(skb, dst);
2624 /* for unconnected multicast sockets we need to validate
2625 * the source on each packet
2627 if (!inet_sk(sk)->inet_daddr && in_dev)
2628 return ip_mc_validate_source(skb, iph->daddr,
2630 iph->tos & IPTOS_RT_MASK,
2631 skb->dev, in_dev, &itag);
2636 int udp_rcv(struct sk_buff *skb)
2638 return __udp4_lib_rcv(skb, &udp_table, IPPROTO_UDP);
2641 void udp_destroy_sock(struct sock *sk)
2643 struct udp_sock *up = udp_sk(sk);
2644 bool slow = lock_sock_fast(sk);
2646 /* protects from races with udp_abort() */
2647 sock_set_flag(sk, SOCK_DEAD);
2648 udp_flush_pending_frames(sk);
2649 unlock_sock_fast(sk, slow);
2650 if (static_branch_unlikely(&udp_encap_needed_key)) {
2651 if (up->encap_type) {
2652 void (*encap_destroy)(struct sock *sk);
2653 encap_destroy = READ_ONCE(up->encap_destroy);
2657 if (udp_test_bit(ENCAP_ENABLED, sk))
2658 static_branch_dec(&udp_encap_needed_key);
2663 * Socket option code for UDP
2665 int udp_lib_setsockopt(struct sock *sk, int level, int optname,
2666 sockptr_t optval, unsigned int optlen,
2667 int (*push_pending_frames)(struct sock *))
2669 struct udp_sock *up = udp_sk(sk);
2672 int is_udplite = IS_UDPLITE(sk);
2674 if (optlen < sizeof(int))
2677 if (copy_from_sockptr(&val, optval, sizeof(val)))
2680 valbool = val ? 1 : 0;
2685 udp_set_bit(CORK, sk);
2687 udp_clear_bit(CORK, sk);
2689 push_pending_frames(sk);
2698 case UDP_ENCAP_ESPINUDP:
2699 case UDP_ENCAP_ESPINUDP_NON_IKE:
2700 #if IS_ENABLED(CONFIG_IPV6)
2701 if (sk->sk_family == AF_INET6)
2702 WRITE_ONCE(up->encap_rcv,
2703 ipv6_stub->xfrm6_udp_encap_rcv);
2706 WRITE_ONCE(up->encap_rcv,
2707 xfrm4_udp_encap_rcv);
2710 case UDP_ENCAP_L2TPINUDP:
2711 WRITE_ONCE(up->encap_type, val);
2712 udp_tunnel_encap_enable(sk);
2720 case UDP_NO_CHECK6_TX:
2721 udp_set_no_check6_tx(sk, valbool);
2724 case UDP_NO_CHECK6_RX:
2725 udp_set_no_check6_rx(sk, valbool);
2729 if (val < 0 || val > USHRT_MAX)
2731 WRITE_ONCE(up->gso_size, val);
2736 /* when enabling GRO, accept the related GSO packet type */
2738 udp_tunnel_encap_enable(sk);
2739 udp_assign_bit(GRO_ENABLED, sk, valbool);
2740 udp_assign_bit(ACCEPT_L4, sk, valbool);
2744 * UDP-Lite's partial checksum coverage (RFC 3828).
2746 /* The sender sets actual checksum coverage length via this option.
2747 * The case coverage > packet length is handled by send module. */
2748 case UDPLITE_SEND_CSCOV:
2749 if (!is_udplite) /* Disable the option on UDP sockets */
2750 return -ENOPROTOOPT;
2751 if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
2753 else if (val > USHRT_MAX)
2756 up->pcflag |= UDPLITE_SEND_CC;
2759 /* The receiver specifies a minimum checksum coverage value. To make
2760 * sense, this should be set to at least 8 (as done below). If zero is
2761 * used, this again means full checksum coverage. */
2762 case UDPLITE_RECV_CSCOV:
2763 if (!is_udplite) /* Disable the option on UDP sockets */
2764 return -ENOPROTOOPT;
2765 if (val != 0 && val < 8) /* Avoid silly minimal values. */
2767 else if (val > USHRT_MAX)
2770 up->pcflag |= UDPLITE_RECV_CC;
2780 EXPORT_SYMBOL(udp_lib_setsockopt);
2782 int udp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
2783 unsigned int optlen)
2785 if (level == SOL_UDP || level == SOL_UDPLITE)
2786 return udp_lib_setsockopt(sk, level, optname,
2788 udp_push_pending_frames);
2789 return ip_setsockopt(sk, level, optname, optval, optlen);
2792 int udp_lib_getsockopt(struct sock *sk, int level, int optname,
2793 char __user *optval, int __user *optlen)
2795 struct udp_sock *up = udp_sk(sk);
2798 if (get_user(len, optlen))
2804 len = min_t(unsigned int, len, sizeof(int));
2808 val = udp_test_bit(CORK, sk);
2812 val = READ_ONCE(up->encap_type);
2815 case UDP_NO_CHECK6_TX:
2816 val = udp_get_no_check6_tx(sk);
2819 case UDP_NO_CHECK6_RX:
2820 val = udp_get_no_check6_rx(sk);
2824 val = READ_ONCE(up->gso_size);
2828 val = udp_test_bit(GRO_ENABLED, sk);
2831 /* The following two cannot be changed on UDP sockets, the return is
2832 * always 0 (which corresponds to the full checksum coverage of UDP). */
2833 case UDPLITE_SEND_CSCOV:
2837 case UDPLITE_RECV_CSCOV:
2842 return -ENOPROTOOPT;
2845 if (put_user(len, optlen))
2847 if (copy_to_user(optval, &val, len))
2851 EXPORT_SYMBOL(udp_lib_getsockopt);
2853 int udp_getsockopt(struct sock *sk, int level, int optname,
2854 char __user *optval, int __user *optlen)
2856 if (level == SOL_UDP || level == SOL_UDPLITE)
2857 return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2858 return ip_getsockopt(sk, level, optname, optval, optlen);
2862 * udp_poll - wait for a UDP event.
2863 * @file: - file struct
2865 * @wait: - poll table
2867 * This is same as datagram poll, except for the special case of
2868 * blocking sockets. If application is using a blocking fd
2869 * and a packet with checksum error is in the queue;
2870 * then it could get return from select indicating data available
2871 * but then block when reading it. Add special case code
2872 * to work around these arguably broken applications.
2874 __poll_t udp_poll(struct file *file, struct socket *sock, poll_table *wait)
2876 __poll_t mask = datagram_poll(file, sock, wait);
2877 struct sock *sk = sock->sk;
2879 if (!skb_queue_empty_lockless(&udp_sk(sk)->reader_queue))
2880 mask |= EPOLLIN | EPOLLRDNORM;
2882 /* Check for false positives due to checksum errors */
2883 if ((mask & EPOLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
2884 !(sk->sk_shutdown & RCV_SHUTDOWN) && first_packet_length(sk) == -1)
2885 mask &= ~(EPOLLIN | EPOLLRDNORM);
2887 /* psock ingress_msg queue should not contain any bad checksum frames */
2888 if (sk_is_readable(sk))
2889 mask |= EPOLLIN | EPOLLRDNORM;
2893 EXPORT_SYMBOL(udp_poll);
2895 int udp_abort(struct sock *sk, int err)
2899 /* udp{v6}_destroy_sock() sets it under the sk lock, avoid racing
2902 if (sock_flag(sk, SOCK_DEAD))
2906 sk_error_report(sk);
2907 __udp_disconnect(sk, 0);
2914 EXPORT_SYMBOL_GPL(udp_abort);
2916 struct proto udp_prot = {
2918 .owner = THIS_MODULE,
2919 .close = udp_lib_close,
2920 .pre_connect = udp_pre_connect,
2921 .connect = ip4_datagram_connect,
2922 .disconnect = udp_disconnect,
2924 .init = udp_init_sock,
2925 .destroy = udp_destroy_sock,
2926 .setsockopt = udp_setsockopt,
2927 .getsockopt = udp_getsockopt,
2928 .sendmsg = udp_sendmsg,
2929 .recvmsg = udp_recvmsg,
2930 .splice_eof = udp_splice_eof,
2931 .sendpage = udp_sendpage,
2932 .release_cb = ip4_datagram_release_cb,
2933 .hash = udp_lib_hash,
2934 .unhash = udp_lib_unhash,
2935 .rehash = udp_v4_rehash,
2936 .get_port = udp_v4_get_port,
2937 .put_port = udp_lib_unhash,
2938 #ifdef CONFIG_BPF_SYSCALL
2939 .psock_update_sk_prot = udp_bpf_update_proto,
2941 .memory_allocated = &udp_memory_allocated,
2942 .per_cpu_fw_alloc = &udp_memory_per_cpu_fw_alloc,
2944 .sysctl_mem = sysctl_udp_mem,
2945 .sysctl_wmem_offset = offsetof(struct net, ipv4.sysctl_udp_wmem_min),
2946 .sysctl_rmem_offset = offsetof(struct net, ipv4.sysctl_udp_rmem_min),
2947 .obj_size = sizeof(struct udp_sock),
2948 .h.udp_table = &udp_table,
2949 .diag_destroy = udp_abort,
2951 EXPORT_SYMBOL(udp_prot);
2953 /* ------------------------------------------------------------------------ */
2954 #ifdef CONFIG_PROC_FS
2956 static struct sock *udp_get_first(struct seq_file *seq, int start)
2958 struct udp_iter_state *state = seq->private;
2959 struct net *net = seq_file_net(seq);
2960 struct udp_seq_afinfo *afinfo;
2963 if (state->bpf_seq_afinfo)
2964 afinfo = state->bpf_seq_afinfo;
2966 afinfo = pde_data(file_inode(seq->file));
2968 for (state->bucket = start; state->bucket <= afinfo->udp_table->mask;
2970 struct udp_hslot *hslot = &afinfo->udp_table->hash[state->bucket];
2972 if (hlist_empty(&hslot->head))
2975 spin_lock_bh(&hslot->lock);
2976 sk_for_each(sk, &hslot->head) {
2977 if (!net_eq(sock_net(sk), net))
2979 if (afinfo->family == AF_UNSPEC ||
2980 sk->sk_family == afinfo->family)
2983 spin_unlock_bh(&hslot->lock);
2990 static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
2992 struct udp_iter_state *state = seq->private;
2993 struct net *net = seq_file_net(seq);
2994 struct udp_seq_afinfo *afinfo;
2996 if (state->bpf_seq_afinfo)
2997 afinfo = state->bpf_seq_afinfo;
2999 afinfo = pde_data(file_inode(seq->file));
3003 } while (sk && (!net_eq(sock_net(sk), net) ||
3004 (afinfo->family != AF_UNSPEC &&
3005 sk->sk_family != afinfo->family)));
3008 if (state->bucket <= afinfo->udp_table->mask)
3009 spin_unlock_bh(&afinfo->udp_table->hash[state->bucket].lock);
3010 return udp_get_first(seq, state->bucket + 1);
3015 static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
3017 struct sock *sk = udp_get_first(seq, 0);
3020 while (pos && (sk = udp_get_next(seq, sk)) != NULL)
3022 return pos ? NULL : sk;
3025 void *udp_seq_start(struct seq_file *seq, loff_t *pos)
3027 struct udp_iter_state *state = seq->private;
3028 state->bucket = MAX_UDP_PORTS;
3030 return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
3032 EXPORT_SYMBOL(udp_seq_start);
3034 void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3038 if (v == SEQ_START_TOKEN)
3039 sk = udp_get_idx(seq, 0);
3041 sk = udp_get_next(seq, v);
3046 EXPORT_SYMBOL(udp_seq_next);
3048 void udp_seq_stop(struct seq_file *seq, void *v)
3050 struct udp_iter_state *state = seq->private;
3051 struct udp_seq_afinfo *afinfo;
3053 if (state->bpf_seq_afinfo)
3054 afinfo = state->bpf_seq_afinfo;
3056 afinfo = pde_data(file_inode(seq->file));
3058 if (state->bucket <= afinfo->udp_table->mask)
3059 spin_unlock_bh(&afinfo->udp_table->hash[state->bucket].lock);
3061 EXPORT_SYMBOL(udp_seq_stop);
3063 /* ------------------------------------------------------------------------ */
3064 static void udp4_format_sock(struct sock *sp, struct seq_file *f,
3067 struct inet_sock *inet = inet_sk(sp);
3068 __be32 dest = inet->inet_daddr;
3069 __be32 src = inet->inet_rcv_saddr;
3070 __u16 destp = ntohs(inet->inet_dport);
3071 __u16 srcp = ntohs(inet->inet_sport);
3073 seq_printf(f, "%5d: %08X:%04X %08X:%04X"
3074 " %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %u",
3075 bucket, src, srcp, dest, destp, sp->sk_state,
3076 sk_wmem_alloc_get(sp),
3079 from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
3081 refcount_read(&sp->sk_refcnt), sp,
3082 atomic_read(&sp->sk_drops));
3085 int udp4_seq_show(struct seq_file *seq, void *v)
3087 seq_setwidth(seq, 127);
3088 if (v == SEQ_START_TOKEN)
3089 seq_puts(seq, " sl local_address rem_address st tx_queue "
3090 "rx_queue tr tm->when retrnsmt uid timeout "
3091 "inode ref pointer drops");
3093 struct udp_iter_state *state = seq->private;
3095 udp4_format_sock(v, seq, state->bucket);
3101 #ifdef CONFIG_BPF_SYSCALL
3102 struct bpf_iter__udp {
3103 __bpf_md_ptr(struct bpf_iter_meta *, meta);
3104 __bpf_md_ptr(struct udp_sock *, udp_sk);
3105 uid_t uid __aligned(8);
3106 int bucket __aligned(8);
3109 static int udp_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
3110 struct udp_sock *udp_sk, uid_t uid, int bucket)
3112 struct bpf_iter__udp ctx;
3114 meta->seq_num--; /* skip SEQ_START_TOKEN */
3116 ctx.udp_sk = udp_sk;
3118 ctx.bucket = bucket;
3119 return bpf_iter_run_prog(prog, &ctx);
3122 static int bpf_iter_udp_seq_show(struct seq_file *seq, void *v)
3124 struct udp_iter_state *state = seq->private;
3125 struct bpf_iter_meta meta;
3126 struct bpf_prog *prog;
3127 struct sock *sk = v;
3130 if (v == SEQ_START_TOKEN)
3133 uid = from_kuid_munged(seq_user_ns(seq), sock_i_uid(sk));
3135 prog = bpf_iter_get_info(&meta, false);
3136 return udp_prog_seq_show(prog, &meta, v, uid, state->bucket);
3139 static void bpf_iter_udp_seq_stop(struct seq_file *seq, void *v)
3141 struct bpf_iter_meta meta;
3142 struct bpf_prog *prog;
3146 prog = bpf_iter_get_info(&meta, true);
3148 (void)udp_prog_seq_show(prog, &meta, v, 0, 0);
3151 udp_seq_stop(seq, v);
3154 static const struct seq_operations bpf_iter_udp_seq_ops = {
3155 .start = udp_seq_start,
3156 .next = udp_seq_next,
3157 .stop = bpf_iter_udp_seq_stop,
3158 .show = bpf_iter_udp_seq_show,
3162 const struct seq_operations udp_seq_ops = {
3163 .start = udp_seq_start,
3164 .next = udp_seq_next,
3165 .stop = udp_seq_stop,
3166 .show = udp4_seq_show,
3168 EXPORT_SYMBOL(udp_seq_ops);
3170 static struct udp_seq_afinfo udp4_seq_afinfo = {
3172 .udp_table = &udp_table,
3175 static int __net_init udp4_proc_init_net(struct net *net)
3177 if (!proc_create_net_data("udp", 0444, net->proc_net, &udp_seq_ops,
3178 sizeof(struct udp_iter_state), &udp4_seq_afinfo))
3183 static void __net_exit udp4_proc_exit_net(struct net *net)
3185 remove_proc_entry("udp", net->proc_net);
3188 static struct pernet_operations udp4_net_ops = {
3189 .init = udp4_proc_init_net,
3190 .exit = udp4_proc_exit_net,
3193 int __init udp4_proc_init(void)
3195 return register_pernet_subsys(&udp4_net_ops);
3198 void udp4_proc_exit(void)
3200 unregister_pernet_subsys(&udp4_net_ops);
3202 #endif /* CONFIG_PROC_FS */
3204 static __initdata unsigned long uhash_entries;
3205 static int __init set_uhash_entries(char *str)
3212 ret = kstrtoul(str, 0, &uhash_entries);
3216 if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
3217 uhash_entries = UDP_HTABLE_SIZE_MIN;
3220 __setup("uhash_entries=", set_uhash_entries);
3222 void __init udp_table_init(struct udp_table *table, const char *name)
3226 table->hash = alloc_large_system_hash(name,
3227 2 * sizeof(struct udp_hslot),
3229 21, /* one slot per 2 MB */
3233 UDP_HTABLE_SIZE_MIN,
3236 table->hash2 = table->hash + (table->mask + 1);
3237 for (i = 0; i <= table->mask; i++) {
3238 INIT_HLIST_HEAD(&table->hash[i].head);
3239 table->hash[i].count = 0;
3240 spin_lock_init(&table->hash[i].lock);
3242 for (i = 0; i <= table->mask; i++) {
3243 INIT_HLIST_HEAD(&table->hash2[i].head);
3244 table->hash2[i].count = 0;
3245 spin_lock_init(&table->hash2[i].lock);
3249 u32 udp_flow_hashrnd(void)
3251 static u32 hashrnd __read_mostly;
3253 net_get_random_once(&hashrnd, sizeof(hashrnd));
3257 EXPORT_SYMBOL(udp_flow_hashrnd);
3259 static int __net_init udp_sysctl_init(struct net *net)
3261 net->ipv4.sysctl_udp_rmem_min = PAGE_SIZE;
3262 net->ipv4.sysctl_udp_wmem_min = PAGE_SIZE;
3264 #ifdef CONFIG_NET_L3_MASTER_DEV
3265 net->ipv4.sysctl_udp_l3mdev_accept = 0;
3271 static struct pernet_operations __net_initdata udp_sysctl_ops = {
3272 .init = udp_sysctl_init,
3275 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
3276 DEFINE_BPF_ITER_FUNC(udp, struct bpf_iter_meta *meta,
3277 struct udp_sock *udp_sk, uid_t uid, int bucket)
3279 static int bpf_iter_init_udp(void *priv_data, struct bpf_iter_aux_info *aux)
3281 struct udp_iter_state *st = priv_data;
3282 struct udp_seq_afinfo *afinfo;
3285 afinfo = kmalloc(sizeof(*afinfo), GFP_USER | __GFP_NOWARN);
3289 afinfo->family = AF_UNSPEC;
3290 afinfo->udp_table = &udp_table;
3291 st->bpf_seq_afinfo = afinfo;
3292 ret = bpf_iter_init_seq_net(priv_data, aux);
3298 static void bpf_iter_fini_udp(void *priv_data)
3300 struct udp_iter_state *st = priv_data;
3302 kfree(st->bpf_seq_afinfo);
3303 bpf_iter_fini_seq_net(priv_data);
3306 static const struct bpf_iter_seq_info udp_seq_info = {
3307 .seq_ops = &bpf_iter_udp_seq_ops,
3308 .init_seq_private = bpf_iter_init_udp,
3309 .fini_seq_private = bpf_iter_fini_udp,
3310 .seq_priv_size = sizeof(struct udp_iter_state),
3313 static struct bpf_iter_reg udp_reg_info = {
3315 .ctx_arg_info_size = 1,
3317 { offsetof(struct bpf_iter__udp, udp_sk),
3318 PTR_TO_BTF_ID_OR_NULL },
3320 .seq_info = &udp_seq_info,
3323 static void __init bpf_iter_register(void)
3325 udp_reg_info.ctx_arg_info[0].btf_id = btf_sock_ids[BTF_SOCK_TYPE_UDP];
3326 if (bpf_iter_reg_target(&udp_reg_info))
3327 pr_warn("Warning: could not register bpf iterator udp\n");
3331 void __init udp_init(void)
3333 unsigned long limit;
3336 udp_table_init(&udp_table, "UDP");
3337 limit = nr_free_buffer_pages() / 8;
3338 limit = max(limit, 128UL);
3339 sysctl_udp_mem[0] = limit / 4 * 3;
3340 sysctl_udp_mem[1] = limit;
3341 sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
3343 /* 16 spinlocks per cpu */
3344 udp_busylocks_log = ilog2(nr_cpu_ids) + 4;
3345 udp_busylocks = kmalloc(sizeof(spinlock_t) << udp_busylocks_log,
3348 panic("UDP: failed to alloc udp_busylocks\n");
3349 for (i = 0; i < (1U << udp_busylocks_log); i++)
3350 spin_lock_init(udp_busylocks + i);
3352 if (register_pernet_subsys(&udp_sysctl_ops))
3353 panic("UDP: failed to init sysctl parameters.\n");
3355 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
3356 bpf_iter_register();