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