net: remove duplicate sk_lookup helpers
[platform/kernel/linux-starfive.git] / net / ipv6 / udp.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *      UDP over IPv6
4  *      Linux INET6 implementation
5  *
6  *      Authors:
7  *      Pedro Roque             <roque@di.fc.ul.pt>
8  *
9  *      Based on linux/ipv4/udp.c
10  *
11  *      Fixes:
12  *      Hideaki YOSHIFUJI       :       sin6_scope_id support
13  *      YOSHIFUJI Hideaki @USAGI and:   Support IPV6_V6ONLY socket option, which
14  *      Alexey Kuznetsov                allow both IPv4 and IPv6 sockets to bind
15  *                                      a single port at the same time.
16  *      Kazunori MIYAZAWA @USAGI:       change process style to use ip6_append_data
17  *      YOSHIFUJI Hideaki @USAGI:       convert /proc/net/udp6 to seq_file.
18  */
19
20 #include <linux/bpf-cgroup.h>
21 #include <linux/errno.h>
22 #include <linux/types.h>
23 #include <linux/socket.h>
24 #include <linux/sockios.h>
25 #include <linux/net.h>
26 #include <linux/in6.h>
27 #include <linux/netdevice.h>
28 #include <linux/if_arp.h>
29 #include <linux/ipv6.h>
30 #include <linux/icmpv6.h>
31 #include <linux/init.h>
32 #include <linux/module.h>
33 #include <linux/skbuff.h>
34 #include <linux/slab.h>
35 #include <linux/uaccess.h>
36 #include <linux/indirect_call_wrapper.h>
37
38 #include <net/addrconf.h>
39 #include <net/ndisc.h>
40 #include <net/protocol.h>
41 #include <net/transp_v6.h>
42 #include <net/ip6_route.h>
43 #include <net/raw.h>
44 #include <net/seg6.h>
45 #include <net/tcp_states.h>
46 #include <net/ip6_checksum.h>
47 #include <net/ip6_tunnel.h>
48 #include <trace/events/udp.h>
49 #include <net/xfrm.h>
50 #include <net/inet_hashtables.h>
51 #include <net/inet6_hashtables.h>
52 #include <net/busy_poll.h>
53 #include <net/sock_reuseport.h>
54
55 #include <linux/proc_fs.h>
56 #include <linux/seq_file.h>
57 #include <trace/events/skb.h>
58 #include "udp_impl.h"
59
60 static void udpv6_destruct_sock(struct sock *sk)
61 {
62         udp_destruct_common(sk);
63         inet6_sock_destruct(sk);
64 }
65
66 int udpv6_init_sock(struct sock *sk)
67 {
68         udp_lib_init_sock(sk);
69         sk->sk_destruct = udpv6_destruct_sock;
70         set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
71         return 0;
72 }
73
74 INDIRECT_CALLABLE_SCOPE
75 u32 udp6_ehashfn(const struct net *net,
76                  const struct in6_addr *laddr,
77                  const u16 lport,
78                  const struct in6_addr *faddr,
79                  const __be16 fport)
80 {
81         static u32 udp6_ehash_secret __read_mostly;
82         static u32 udp_ipv6_hash_secret __read_mostly;
83
84         u32 lhash, fhash;
85
86         net_get_random_once(&udp6_ehash_secret,
87                             sizeof(udp6_ehash_secret));
88         net_get_random_once(&udp_ipv6_hash_secret,
89                             sizeof(udp_ipv6_hash_secret));
90
91         lhash = (__force u32)laddr->s6_addr32[3];
92         fhash = __ipv6_addr_jhash(faddr, udp_ipv6_hash_secret);
93
94         return __inet6_ehashfn(lhash, lport, fhash, fport,
95                                udp6_ehash_secret + net_hash_mix(net));
96 }
97
98 int udp_v6_get_port(struct sock *sk, unsigned short snum)
99 {
100         unsigned int hash2_nulladdr =
101                 ipv6_portaddr_hash(sock_net(sk), &in6addr_any, snum);
102         unsigned int hash2_partial =
103                 ipv6_portaddr_hash(sock_net(sk), &sk->sk_v6_rcv_saddr, 0);
104
105         /* precompute partial secondary hash */
106         udp_sk(sk)->udp_portaddr_hash = hash2_partial;
107         return udp_lib_get_port(sk, snum, hash2_nulladdr);
108 }
109
110 void udp_v6_rehash(struct sock *sk)
111 {
112         u16 new_hash = ipv6_portaddr_hash(sock_net(sk),
113                                           &sk->sk_v6_rcv_saddr,
114                                           inet_sk(sk)->inet_num);
115
116         udp_lib_rehash(sk, new_hash);
117 }
118
119 static int compute_score(struct sock *sk, struct net *net,
120                          const struct in6_addr *saddr, __be16 sport,
121                          const struct in6_addr *daddr, unsigned short hnum,
122                          int dif, int sdif)
123 {
124         int bound_dev_if, score;
125         struct inet_sock *inet;
126         bool dev_match;
127
128         if (!net_eq(sock_net(sk), net) ||
129             udp_sk(sk)->udp_port_hash != hnum ||
130             sk->sk_family != PF_INET6)
131                 return -1;
132
133         if (!ipv6_addr_equal(&sk->sk_v6_rcv_saddr, daddr))
134                 return -1;
135
136         score = 0;
137         inet = inet_sk(sk);
138
139         if (inet->inet_dport) {
140                 if (inet->inet_dport != sport)
141                         return -1;
142                 score++;
143         }
144
145         if (!ipv6_addr_any(&sk->sk_v6_daddr)) {
146                 if (!ipv6_addr_equal(&sk->sk_v6_daddr, saddr))
147                         return -1;
148                 score++;
149         }
150
151         bound_dev_if = READ_ONCE(sk->sk_bound_dev_if);
152         dev_match = udp_sk_bound_dev_eq(net, bound_dev_if, dif, sdif);
153         if (!dev_match)
154                 return -1;
155         if (bound_dev_if)
156                 score++;
157
158         if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
159                 score++;
160
161         return score;
162 }
163
164 /* called with rcu_read_lock() */
165 static struct sock *udp6_lib_lookup2(struct net *net,
166                 const struct in6_addr *saddr, __be16 sport,
167                 const struct in6_addr *daddr, unsigned int hnum,
168                 int dif, int sdif, struct udp_hslot *hslot2,
169                 struct sk_buff *skb)
170 {
171         struct sock *sk, *result;
172         int score, badness;
173
174         result = NULL;
175         badness = -1;
176         udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
177                 score = compute_score(sk, net, saddr, sport,
178                                       daddr, hnum, dif, sdif);
179                 if (score > badness) {
180                         badness = score;
181
182                         if (sk->sk_state == TCP_ESTABLISHED) {
183                                 result = sk;
184                                 continue;
185                         }
186
187                         result = inet6_lookup_reuseport(net, sk, skb, sizeof(struct udphdr),
188                                                         saddr, sport, daddr, hnum, udp6_ehashfn);
189                         if (!result) {
190                                 result = sk;
191                                 continue;
192                         }
193
194                         /* Fall back to scoring if group has connections */
195                         if (!reuseport_has_conns(sk))
196                                 return result;
197
198                         /* Reuseport logic returned an error, keep original score. */
199                         if (IS_ERR(result))
200                                 continue;
201
202                         badness = compute_score(sk, net, saddr, sport,
203                                                 daddr, hnum, dif, sdif);
204                 }
205         }
206         return result;
207 }
208
209 /* rcu_read_lock() must be held */
210 struct sock *__udp6_lib_lookup(struct net *net,
211                                const struct in6_addr *saddr, __be16 sport,
212                                const struct in6_addr *daddr, __be16 dport,
213                                int dif, int sdif, struct udp_table *udptable,
214                                struct sk_buff *skb)
215 {
216         unsigned short hnum = ntohs(dport);
217         unsigned int hash2, slot2;
218         struct udp_hslot *hslot2;
219         struct sock *result, *sk;
220
221         hash2 = ipv6_portaddr_hash(net, daddr, hnum);
222         slot2 = hash2 & udptable->mask;
223         hslot2 = &udptable->hash2[slot2];
224
225         /* Lookup connected or non-wildcard sockets */
226         result = udp6_lib_lookup2(net, saddr, sport,
227                                   daddr, hnum, dif, sdif,
228                                   hslot2, skb);
229         if (!IS_ERR_OR_NULL(result) && result->sk_state == TCP_ESTABLISHED)
230                 goto done;
231
232         /* Lookup redirect from BPF */
233         if (static_branch_unlikely(&bpf_sk_lookup_enabled) &&
234             udptable == net->ipv4.udp_table) {
235                 sk = inet6_lookup_run_sk_lookup(net, IPPROTO_UDP, skb, sizeof(struct udphdr),
236                                                 saddr, sport, daddr, hnum, dif,
237                                                 udp6_ehashfn);
238                 if (sk) {
239                         result = sk;
240                         goto done;
241                 }
242         }
243
244         /* Got non-wildcard socket or error on first lookup */
245         if (result)
246                 goto done;
247
248         /* Lookup wildcard sockets */
249         hash2 = ipv6_portaddr_hash(net, &in6addr_any, hnum);
250         slot2 = hash2 & udptable->mask;
251         hslot2 = &udptable->hash2[slot2];
252
253         result = udp6_lib_lookup2(net, saddr, sport,
254                                   &in6addr_any, hnum, dif, sdif,
255                                   hslot2, skb);
256 done:
257         if (IS_ERR(result))
258                 return NULL;
259         return result;
260 }
261 EXPORT_SYMBOL_GPL(__udp6_lib_lookup);
262
263 static struct sock *__udp6_lib_lookup_skb(struct sk_buff *skb,
264                                           __be16 sport, __be16 dport,
265                                           struct udp_table *udptable)
266 {
267         const struct ipv6hdr *iph = ipv6_hdr(skb);
268
269         return __udp6_lib_lookup(dev_net(skb->dev), &iph->saddr, sport,
270                                  &iph->daddr, dport, inet6_iif(skb),
271                                  inet6_sdif(skb), udptable, skb);
272 }
273
274 struct sock *udp6_lib_lookup_skb(const struct sk_buff *skb,
275                                  __be16 sport, __be16 dport)
276 {
277         const struct ipv6hdr *iph = ipv6_hdr(skb);
278         struct net *net = dev_net(skb->dev);
279
280         return __udp6_lib_lookup(net, &iph->saddr, sport,
281                                  &iph->daddr, dport, inet6_iif(skb),
282                                  inet6_sdif(skb), net->ipv4.udp_table, NULL);
283 }
284
285 /* Must be called under rcu_read_lock().
286  * Does increment socket refcount.
287  */
288 #if IS_ENABLED(CONFIG_NF_TPROXY_IPV6) || IS_ENABLED(CONFIG_NF_SOCKET_IPV6)
289 struct sock *udp6_lib_lookup(struct net *net, const struct in6_addr *saddr, __be16 sport,
290                              const struct in6_addr *daddr, __be16 dport, int dif)
291 {
292         struct sock *sk;
293
294         sk =  __udp6_lib_lookup(net, saddr, sport, daddr, dport,
295                                 dif, 0, net->ipv4.udp_table, NULL);
296         if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
297                 sk = NULL;
298         return sk;
299 }
300 EXPORT_SYMBOL_GPL(udp6_lib_lookup);
301 #endif
302
303 /* do not use the scratch area len for jumbogram: their length execeeds the
304  * scratch area space; note that the IP6CB flags is still in the first
305  * cacheline, so checking for jumbograms is cheap
306  */
307 static int udp6_skb_len(struct sk_buff *skb)
308 {
309         return unlikely(inet6_is_jumbogram(skb)) ? skb->len : udp_skb_len(skb);
310 }
311
312 /*
313  *      This should be easy, if there is something there we
314  *      return it, otherwise we block.
315  */
316
317 int udpv6_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
318                   int flags, int *addr_len)
319 {
320         struct ipv6_pinfo *np = inet6_sk(sk);
321         struct inet_sock *inet = inet_sk(sk);
322         struct sk_buff *skb;
323         unsigned int ulen, copied;
324         int off, err, peeking = flags & MSG_PEEK;
325         int is_udplite = IS_UDPLITE(sk);
326         struct udp_mib __percpu *mib;
327         bool checksum_valid = false;
328         int is_udp4;
329
330         if (flags & MSG_ERRQUEUE)
331                 return ipv6_recv_error(sk, msg, len, addr_len);
332
333         if (np->rxpmtu && np->rxopt.bits.rxpmtu)
334                 return ipv6_recv_rxpmtu(sk, msg, len, addr_len);
335
336 try_again:
337         off = sk_peek_offset(sk, flags);
338         skb = __skb_recv_udp(sk, flags, &off, &err);
339         if (!skb)
340                 return err;
341
342         ulen = udp6_skb_len(skb);
343         copied = len;
344         if (copied > ulen - off)
345                 copied = ulen - off;
346         else if (copied < ulen)
347                 msg->msg_flags |= MSG_TRUNC;
348
349         is_udp4 = (skb->protocol == htons(ETH_P_IP));
350         mib = __UDPX_MIB(sk, is_udp4);
351
352         /*
353          * If checksum is needed at all, try to do it while copying the
354          * data.  If the data is truncated, or if we only want a partial
355          * coverage checksum (UDP-Lite), do it before the copy.
356          */
357
358         if (copied < ulen || peeking ||
359             (is_udplite && UDP_SKB_CB(skb)->partial_cov)) {
360                 checksum_valid = udp_skb_csum_unnecessary(skb) ||
361                                 !__udp_lib_checksum_complete(skb);
362                 if (!checksum_valid)
363                         goto csum_copy_err;
364         }
365
366         if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
367                 if (udp_skb_is_linear(skb))
368                         err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
369                 else
370                         err = skb_copy_datagram_msg(skb, off, msg, copied);
371         } else {
372                 err = skb_copy_and_csum_datagram_msg(skb, off, msg);
373                 if (err == -EINVAL)
374                         goto csum_copy_err;
375         }
376         if (unlikely(err)) {
377                 if (!peeking) {
378                         atomic_inc(&sk->sk_drops);
379                         SNMP_INC_STATS(mib, UDP_MIB_INERRORS);
380                 }
381                 kfree_skb(skb);
382                 return err;
383         }
384         if (!peeking)
385                 SNMP_INC_STATS(mib, UDP_MIB_INDATAGRAMS);
386
387         sock_recv_cmsgs(msg, sk, skb);
388
389         /* Copy the address. */
390         if (msg->msg_name) {
391                 DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
392                 sin6->sin6_family = AF_INET6;
393                 sin6->sin6_port = udp_hdr(skb)->source;
394                 sin6->sin6_flowinfo = 0;
395
396                 if (is_udp4) {
397                         ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,
398                                                &sin6->sin6_addr);
399                         sin6->sin6_scope_id = 0;
400                 } else {
401                         sin6->sin6_addr = ipv6_hdr(skb)->saddr;
402                         sin6->sin6_scope_id =
403                                 ipv6_iface_scope_id(&sin6->sin6_addr,
404                                                     inet6_iif(skb));
405                 }
406                 *addr_len = sizeof(*sin6);
407
408                 BPF_CGROUP_RUN_PROG_UDP6_RECVMSG_LOCK(sk,
409                                                       (struct sockaddr *)sin6);
410         }
411
412         if (udp_sk(sk)->gro_enabled)
413                 udp_cmsg_recv(msg, sk, skb);
414
415         if (np->rxopt.all)
416                 ip6_datagram_recv_common_ctl(sk, msg, skb);
417
418         if (is_udp4) {
419                 if (inet->cmsg_flags)
420                         ip_cmsg_recv_offset(msg, sk, skb,
421                                             sizeof(struct udphdr), off);
422         } else {
423                 if (np->rxopt.all)
424                         ip6_datagram_recv_specific_ctl(sk, msg, skb);
425         }
426
427         err = copied;
428         if (flags & MSG_TRUNC)
429                 err = ulen;
430
431         skb_consume_udp(sk, skb, peeking ? -err : err);
432         return err;
433
434 csum_copy_err:
435         if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags,
436                                  udp_skb_destructor)) {
437                 SNMP_INC_STATS(mib, UDP_MIB_CSUMERRORS);
438                 SNMP_INC_STATS(mib, UDP_MIB_INERRORS);
439         }
440         kfree_skb(skb);
441
442         /* starting over for a new packet, but check if we need to yield */
443         cond_resched();
444         msg->msg_flags &= ~MSG_TRUNC;
445         goto try_again;
446 }
447
448 DEFINE_STATIC_KEY_FALSE(udpv6_encap_needed_key);
449 void udpv6_encap_enable(void)
450 {
451         static_branch_inc(&udpv6_encap_needed_key);
452 }
453 EXPORT_SYMBOL(udpv6_encap_enable);
454
455 /* Handler for tunnels with arbitrary destination ports: no socket lookup, go
456  * through error handlers in encapsulations looking for a match.
457  */
458 static int __udp6_lib_err_encap_no_sk(struct sk_buff *skb,
459                                       struct inet6_skb_parm *opt,
460                                       u8 type, u8 code, int offset, __be32 info)
461 {
462         int i;
463
464         for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) {
465                 int (*handler)(struct sk_buff *skb, struct inet6_skb_parm *opt,
466                                u8 type, u8 code, int offset, __be32 info);
467                 const struct ip6_tnl_encap_ops *encap;
468
469                 encap = rcu_dereference(ip6tun_encaps[i]);
470                 if (!encap)
471                         continue;
472                 handler = encap->err_handler;
473                 if (handler && !handler(skb, opt, type, code, offset, info))
474                         return 0;
475         }
476
477         return -ENOENT;
478 }
479
480 /* Try to match ICMP errors to UDP tunnels by looking up a socket without
481  * reversing source and destination port: this will match tunnels that force the
482  * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that
483  * lwtunnels might actually break this assumption by being configured with
484  * different destination ports on endpoints, in this case we won't be able to
485  * trace ICMP messages back to them.
486  *
487  * If this doesn't match any socket, probe tunnels with arbitrary destination
488  * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port
489  * we've sent packets to won't necessarily match the local destination port.
490  *
491  * Then ask the tunnel implementation to match the error against a valid
492  * association.
493  *
494  * Return an error if we can't find a match, the socket if we need further
495  * processing, zero otherwise.
496  */
497 static struct sock *__udp6_lib_err_encap(struct net *net,
498                                          const struct ipv6hdr *hdr, int offset,
499                                          struct udphdr *uh,
500                                          struct udp_table *udptable,
501                                          struct sock *sk,
502                                          struct sk_buff *skb,
503                                          struct inet6_skb_parm *opt,
504                                          u8 type, u8 code, __be32 info)
505 {
506         int (*lookup)(struct sock *sk, struct sk_buff *skb);
507         int network_offset, transport_offset;
508         struct udp_sock *up;
509
510         network_offset = skb_network_offset(skb);
511         transport_offset = skb_transport_offset(skb);
512
513         /* Network header needs to point to the outer IPv6 header inside ICMP */
514         skb_reset_network_header(skb);
515
516         /* Transport header needs to point to the UDP header */
517         skb_set_transport_header(skb, offset);
518
519         if (sk) {
520                 up = udp_sk(sk);
521
522                 lookup = READ_ONCE(up->encap_err_lookup);
523                 if (lookup && lookup(sk, skb))
524                         sk = NULL;
525
526                 goto out;
527         }
528
529         sk = __udp6_lib_lookup(net, &hdr->daddr, uh->source,
530                                &hdr->saddr, uh->dest,
531                                inet6_iif(skb), 0, udptable, skb);
532         if (sk) {
533                 up = udp_sk(sk);
534
535                 lookup = READ_ONCE(up->encap_err_lookup);
536                 if (!lookup || lookup(sk, skb))
537                         sk = NULL;
538         }
539
540 out:
541         if (!sk) {
542                 sk = ERR_PTR(__udp6_lib_err_encap_no_sk(skb, opt, type, code,
543                                                         offset, info));
544         }
545
546         skb_set_transport_header(skb, transport_offset);
547         skb_set_network_header(skb, network_offset);
548
549         return sk;
550 }
551
552 int __udp6_lib_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
553                    u8 type, u8 code, int offset, __be32 info,
554                    struct udp_table *udptable)
555 {
556         struct ipv6_pinfo *np;
557         const struct ipv6hdr *hdr = (const struct ipv6hdr *)skb->data;
558         const struct in6_addr *saddr = &hdr->saddr;
559         const struct in6_addr *daddr = seg6_get_daddr(skb, opt) ? : &hdr->daddr;
560         struct udphdr *uh = (struct udphdr *)(skb->data+offset);
561         bool tunnel = false;
562         struct sock *sk;
563         int harderr;
564         int err;
565         struct net *net = dev_net(skb->dev);
566
567         sk = __udp6_lib_lookup(net, daddr, uh->dest, saddr, uh->source,
568                                inet6_iif(skb), inet6_sdif(skb), udptable, NULL);
569
570         if (!sk || udp_sk(sk)->encap_type) {
571                 /* No socket for error: try tunnels before discarding */
572                 if (static_branch_unlikely(&udpv6_encap_needed_key)) {
573                         sk = __udp6_lib_err_encap(net, hdr, offset, uh,
574                                                   udptable, sk, skb,
575                                                   opt, type, code, info);
576                         if (!sk)
577                                 return 0;
578                 } else
579                         sk = ERR_PTR(-ENOENT);
580
581                 if (IS_ERR(sk)) {
582                         __ICMP6_INC_STATS(net, __in6_dev_get(skb->dev),
583                                           ICMP6_MIB_INERRORS);
584                         return PTR_ERR(sk);
585                 }
586
587                 tunnel = true;
588         }
589
590         harderr = icmpv6_err_convert(type, code, &err);
591         np = inet6_sk(sk);
592
593         if (type == ICMPV6_PKT_TOOBIG) {
594                 if (!ip6_sk_accept_pmtu(sk))
595                         goto out;
596                 ip6_sk_update_pmtu(skb, sk, info);
597                 if (np->pmtudisc != IPV6_PMTUDISC_DONT)
598                         harderr = 1;
599         }
600         if (type == NDISC_REDIRECT) {
601                 if (tunnel) {
602                         ip6_redirect(skb, sock_net(sk), inet6_iif(skb),
603                                      sk->sk_mark, sk->sk_uid);
604                 } else {
605                         ip6_sk_redirect(skb, sk);
606                 }
607                 goto out;
608         }
609
610         /* Tunnels don't have an application socket: don't pass errors back */
611         if (tunnel) {
612                 if (udp_sk(sk)->encap_err_rcv)
613                         udp_sk(sk)->encap_err_rcv(sk, skb, err, uh->dest,
614                                                   ntohl(info), (u8 *)(uh+1));
615                 goto out;
616         }
617
618         if (!np->recverr) {
619                 if (!harderr || sk->sk_state != TCP_ESTABLISHED)
620                         goto out;
621         } else {
622                 ipv6_icmp_error(sk, skb, err, uh->dest, ntohl(info), (u8 *)(uh+1));
623         }
624
625         sk->sk_err = err;
626         sk_error_report(sk);
627 out:
628         return 0;
629 }
630
631 static int __udpv6_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
632 {
633         int rc;
634
635         if (!ipv6_addr_any(&sk->sk_v6_daddr)) {
636                 sock_rps_save_rxhash(sk, skb);
637                 sk_mark_napi_id(sk, skb);
638                 sk_incoming_cpu_update(sk);
639         } else {
640                 sk_mark_napi_id_once(sk, skb);
641         }
642
643         rc = __udp_enqueue_schedule_skb(sk, skb);
644         if (rc < 0) {
645                 int is_udplite = IS_UDPLITE(sk);
646                 enum skb_drop_reason drop_reason;
647
648                 /* Note that an ENOMEM error is charged twice */
649                 if (rc == -ENOMEM) {
650                         UDP6_INC_STATS(sock_net(sk),
651                                          UDP_MIB_RCVBUFERRORS, is_udplite);
652                         drop_reason = SKB_DROP_REASON_SOCKET_RCVBUFF;
653                 } else {
654                         UDP6_INC_STATS(sock_net(sk),
655                                        UDP_MIB_MEMERRORS, is_udplite);
656                         drop_reason = SKB_DROP_REASON_PROTO_MEM;
657                 }
658                 UDP6_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
659                 kfree_skb_reason(skb, drop_reason);
660                 trace_udp_fail_queue_rcv_skb(rc, sk);
661                 return -1;
662         }
663
664         return 0;
665 }
666
667 static __inline__ int udpv6_err(struct sk_buff *skb,
668                                 struct inet6_skb_parm *opt, u8 type,
669                                 u8 code, int offset, __be32 info)
670 {
671         return __udp6_lib_err(skb, opt, type, code, offset, info,
672                               dev_net(skb->dev)->ipv4.udp_table);
673 }
674
675 static int udpv6_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
676 {
677         enum skb_drop_reason drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
678         struct udp_sock *up = udp_sk(sk);
679         int is_udplite = IS_UDPLITE(sk);
680
681         if (!xfrm6_policy_check(sk, XFRM_POLICY_IN, skb)) {
682                 drop_reason = SKB_DROP_REASON_XFRM_POLICY;
683                 goto drop;
684         }
685         nf_reset_ct(skb);
686
687         if (static_branch_unlikely(&udpv6_encap_needed_key) && up->encap_type) {
688                 int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
689
690                 /*
691                  * This is an encapsulation socket so pass the skb to
692                  * the socket's udp_encap_rcv() hook. Otherwise, just
693                  * fall through and pass this up the UDP socket.
694                  * up->encap_rcv() returns the following value:
695                  * =0 if skb was successfully passed to the encap
696                  *    handler or was discarded by it.
697                  * >0 if skb should be passed on to UDP.
698                  * <0 if skb should be resubmitted as proto -N
699                  */
700
701                 /* if we're overly short, let UDP handle it */
702                 encap_rcv = READ_ONCE(up->encap_rcv);
703                 if (encap_rcv) {
704                         int ret;
705
706                         /* Verify checksum before giving to encap */
707                         if (udp_lib_checksum_complete(skb))
708                                 goto csum_error;
709
710                         ret = encap_rcv(sk, skb);
711                         if (ret <= 0) {
712                                 __UDP6_INC_STATS(sock_net(sk),
713                                                  UDP_MIB_INDATAGRAMS,
714                                                  is_udplite);
715                                 return -ret;
716                         }
717                 }
718
719                 /* FALLTHROUGH -- it's a UDP Packet */
720         }
721
722         /*
723          * UDP-Lite specific tests, ignored on UDP sockets (see net/ipv4/udp.c).
724          */
725         if ((up->pcflag & UDPLITE_RECV_CC)  &&  UDP_SKB_CB(skb)->partial_cov) {
726
727                 if (up->pcrlen == 0) {          /* full coverage was set  */
728                         net_dbg_ratelimited("UDPLITE6: partial coverage %d while full coverage %d requested\n",
729                                             UDP_SKB_CB(skb)->cscov, skb->len);
730                         goto drop;
731                 }
732                 if (UDP_SKB_CB(skb)->cscov  <  up->pcrlen) {
733                         net_dbg_ratelimited("UDPLITE6: coverage %d too small, need min %d\n",
734                                             UDP_SKB_CB(skb)->cscov, up->pcrlen);
735                         goto drop;
736                 }
737         }
738
739         prefetch(&sk->sk_rmem_alloc);
740         if (rcu_access_pointer(sk->sk_filter) &&
741             udp_lib_checksum_complete(skb))
742                 goto csum_error;
743
744         if (sk_filter_trim_cap(sk, skb, sizeof(struct udphdr))) {
745                 drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
746                 goto drop;
747         }
748
749         udp_csum_pull_header(skb);
750
751         skb_dst_drop(skb);
752
753         return __udpv6_queue_rcv_skb(sk, skb);
754
755 csum_error:
756         drop_reason = SKB_DROP_REASON_UDP_CSUM;
757         __UDP6_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
758 drop:
759         __UDP6_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
760         atomic_inc(&sk->sk_drops);
761         kfree_skb_reason(skb, drop_reason);
762         return -1;
763 }
764
765 static int udpv6_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
766 {
767         struct sk_buff *next, *segs;
768         int ret;
769
770         if (likely(!udp_unexpected_gso(sk, skb)))
771                 return udpv6_queue_rcv_one_skb(sk, skb);
772
773         __skb_push(skb, -skb_mac_offset(skb));
774         segs = udp_rcv_segment(sk, skb, false);
775         skb_list_walk_safe(segs, skb, next) {
776                 __skb_pull(skb, skb_transport_offset(skb));
777
778                 udp_post_segment_fix_csum(skb);
779                 ret = udpv6_queue_rcv_one_skb(sk, skb);
780                 if (ret > 0)
781                         ip6_protocol_deliver_rcu(dev_net(skb->dev), skb, ret,
782                                                  true);
783         }
784         return 0;
785 }
786
787 static bool __udp_v6_is_mcast_sock(struct net *net, const struct sock *sk,
788                                    __be16 loc_port, const struct in6_addr *loc_addr,
789                                    __be16 rmt_port, const struct in6_addr *rmt_addr,
790                                    int dif, int sdif, unsigned short hnum)
791 {
792         const struct inet_sock *inet = inet_sk(sk);
793
794         if (!net_eq(sock_net(sk), net))
795                 return false;
796
797         if (udp_sk(sk)->udp_port_hash != hnum ||
798             sk->sk_family != PF_INET6 ||
799             (inet->inet_dport && inet->inet_dport != rmt_port) ||
800             (!ipv6_addr_any(&sk->sk_v6_daddr) &&
801                     !ipv6_addr_equal(&sk->sk_v6_daddr, rmt_addr)) ||
802             !udp_sk_bound_dev_eq(net, READ_ONCE(sk->sk_bound_dev_if), dif, sdif) ||
803             (!ipv6_addr_any(&sk->sk_v6_rcv_saddr) &&
804                     !ipv6_addr_equal(&sk->sk_v6_rcv_saddr, loc_addr)))
805                 return false;
806         if (!inet6_mc_check(sk, loc_addr, rmt_addr))
807                 return false;
808         return true;
809 }
810
811 static void udp6_csum_zero_error(struct sk_buff *skb)
812 {
813         /* RFC 2460 section 8.1 says that we SHOULD log
814          * this error. Well, it is reasonable.
815          */
816         net_dbg_ratelimited("IPv6: udp checksum is 0 for [%pI6c]:%u->[%pI6c]:%u\n",
817                             &ipv6_hdr(skb)->saddr, ntohs(udp_hdr(skb)->source),
818                             &ipv6_hdr(skb)->daddr, ntohs(udp_hdr(skb)->dest));
819 }
820
821 /*
822  * Note: called only from the BH handler context,
823  * so we don't need to lock the hashes.
824  */
825 static int __udp6_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
826                 const struct in6_addr *saddr, const struct in6_addr *daddr,
827                 struct udp_table *udptable, int proto)
828 {
829         struct sock *sk, *first = NULL;
830         const struct udphdr *uh = udp_hdr(skb);
831         unsigned short hnum = ntohs(uh->dest);
832         struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum);
833         unsigned int offset = offsetof(typeof(*sk), sk_node);
834         unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10);
835         int dif = inet6_iif(skb);
836         int sdif = inet6_sdif(skb);
837         struct hlist_node *node;
838         struct sk_buff *nskb;
839
840         if (use_hash2) {
841                 hash2_any = ipv6_portaddr_hash(net, &in6addr_any, hnum) &
842                             udptable->mask;
843                 hash2 = ipv6_portaddr_hash(net, daddr, hnum) & udptable->mask;
844 start_lookup:
845                 hslot = &udptable->hash2[hash2];
846                 offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
847         }
848
849         sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
850                 if (!__udp_v6_is_mcast_sock(net, sk, uh->dest, daddr,
851                                             uh->source, saddr, dif, sdif,
852                                             hnum))
853                         continue;
854                 /* If zero checksum and no_check is not on for
855                  * the socket then skip it.
856                  */
857                 if (!uh->check && !udp_sk(sk)->no_check6_rx)
858                         continue;
859                 if (!first) {
860                         first = sk;
861                         continue;
862                 }
863                 nskb = skb_clone(skb, GFP_ATOMIC);
864                 if (unlikely(!nskb)) {
865                         atomic_inc(&sk->sk_drops);
866                         __UDP6_INC_STATS(net, UDP_MIB_RCVBUFERRORS,
867                                          IS_UDPLITE(sk));
868                         __UDP6_INC_STATS(net, UDP_MIB_INERRORS,
869                                          IS_UDPLITE(sk));
870                         continue;
871                 }
872
873                 if (udpv6_queue_rcv_skb(sk, nskb) > 0)
874                         consume_skb(nskb);
875         }
876
877         /* Also lookup *:port if we are using hash2 and haven't done so yet. */
878         if (use_hash2 && hash2 != hash2_any) {
879                 hash2 = hash2_any;
880                 goto start_lookup;
881         }
882
883         if (first) {
884                 if (udpv6_queue_rcv_skb(first, skb) > 0)
885                         consume_skb(skb);
886         } else {
887                 kfree_skb(skb);
888                 __UDP6_INC_STATS(net, UDP_MIB_IGNOREDMULTI,
889                                  proto == IPPROTO_UDPLITE);
890         }
891         return 0;
892 }
893
894 static void udp6_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
895 {
896         if (udp_sk_rx_dst_set(sk, dst)) {
897                 const struct rt6_info *rt = (const struct rt6_info *)dst;
898
899                 sk->sk_rx_dst_cookie = rt6_get_cookie(rt);
900         }
901 }
902
903 /* wrapper for udp_queue_rcv_skb tacking care of csum conversion and
904  * return code conversion for ip layer consumption
905  */
906 static int udp6_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb,
907                                 struct udphdr *uh)
908 {
909         int ret;
910
911         if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk))
912                 skb_checksum_try_convert(skb, IPPROTO_UDP, ip6_compute_pseudo);
913
914         ret = udpv6_queue_rcv_skb(sk, skb);
915
916         /* a return value > 0 means to resubmit the input */
917         if (ret > 0)
918                 return ret;
919         return 0;
920 }
921
922 int __udp6_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
923                    int proto)
924 {
925         enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
926         const struct in6_addr *saddr, *daddr;
927         struct net *net = dev_net(skb->dev);
928         struct udphdr *uh;
929         struct sock *sk;
930         bool refcounted;
931         u32 ulen = 0;
932
933         if (!pskb_may_pull(skb, sizeof(struct udphdr)))
934                 goto discard;
935
936         saddr = &ipv6_hdr(skb)->saddr;
937         daddr = &ipv6_hdr(skb)->daddr;
938         uh = udp_hdr(skb);
939
940         ulen = ntohs(uh->len);
941         if (ulen > skb->len)
942                 goto short_packet;
943
944         if (proto == IPPROTO_UDP) {
945                 /* UDP validates ulen. */
946
947                 /* Check for jumbo payload */
948                 if (ulen == 0)
949                         ulen = skb->len;
950
951                 if (ulen < sizeof(*uh))
952                         goto short_packet;
953
954                 if (ulen < skb->len) {
955                         if (pskb_trim_rcsum(skb, ulen))
956                                 goto short_packet;
957                         saddr = &ipv6_hdr(skb)->saddr;
958                         daddr = &ipv6_hdr(skb)->daddr;
959                         uh = udp_hdr(skb);
960                 }
961         }
962
963         if (udp6_csum_init(skb, uh, proto))
964                 goto csum_error;
965
966         /* Check if the socket is already available, e.g. due to early demux */
967         sk = skb_steal_sock(skb, &refcounted);
968         if (sk) {
969                 struct dst_entry *dst = skb_dst(skb);
970                 int ret;
971
972                 if (unlikely(rcu_dereference(sk->sk_rx_dst) != dst))
973                         udp6_sk_rx_dst_set(sk, dst);
974
975                 if (!uh->check && !udp_sk(sk)->no_check6_rx) {
976                         if (refcounted)
977                                 sock_put(sk);
978                         goto report_csum_error;
979                 }
980
981                 ret = udp6_unicast_rcv_skb(sk, skb, uh);
982                 if (refcounted)
983                         sock_put(sk);
984                 return ret;
985         }
986
987         /*
988          *      Multicast receive code
989          */
990         if (ipv6_addr_is_multicast(daddr))
991                 return __udp6_lib_mcast_deliver(net, skb,
992                                 saddr, daddr, udptable, proto);
993
994         /* Unicast */
995         sk = __udp6_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
996         if (sk) {
997                 if (!uh->check && !udp_sk(sk)->no_check6_rx)
998                         goto report_csum_error;
999                 return udp6_unicast_rcv_skb(sk, skb, uh);
1000         }
1001
1002         reason = SKB_DROP_REASON_NO_SOCKET;
1003
1004         if (!uh->check)
1005                 goto report_csum_error;
1006
1007         if (!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb))
1008                 goto discard;
1009         nf_reset_ct(skb);
1010
1011         if (udp_lib_checksum_complete(skb))
1012                 goto csum_error;
1013
1014         __UDP6_INC_STATS(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
1015         icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_PORT_UNREACH, 0);
1016
1017         kfree_skb_reason(skb, reason);
1018         return 0;
1019
1020 short_packet:
1021         if (reason == SKB_DROP_REASON_NOT_SPECIFIED)
1022                 reason = SKB_DROP_REASON_PKT_TOO_SMALL;
1023         net_dbg_ratelimited("UDP%sv6: short packet: From [%pI6c]:%u %d/%d to [%pI6c]:%u\n",
1024                             proto == IPPROTO_UDPLITE ? "-Lite" : "",
1025                             saddr, ntohs(uh->source),
1026                             ulen, skb->len,
1027                             daddr, ntohs(uh->dest));
1028         goto discard;
1029
1030 report_csum_error:
1031         udp6_csum_zero_error(skb);
1032 csum_error:
1033         if (reason == SKB_DROP_REASON_NOT_SPECIFIED)
1034                 reason = SKB_DROP_REASON_UDP_CSUM;
1035         __UDP6_INC_STATS(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
1036 discard:
1037         __UDP6_INC_STATS(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
1038         kfree_skb_reason(skb, reason);
1039         return 0;
1040 }
1041
1042
1043 static struct sock *__udp6_lib_demux_lookup(struct net *net,
1044                         __be16 loc_port, const struct in6_addr *loc_addr,
1045                         __be16 rmt_port, const struct in6_addr *rmt_addr,
1046                         int dif, int sdif)
1047 {
1048         struct udp_table *udptable = net->ipv4.udp_table;
1049         unsigned short hnum = ntohs(loc_port);
1050         unsigned int hash2, slot2;
1051         struct udp_hslot *hslot2;
1052         __portpair ports;
1053         struct sock *sk;
1054
1055         hash2 = ipv6_portaddr_hash(net, loc_addr, hnum);
1056         slot2 = hash2 & udptable->mask;
1057         hslot2 = &udptable->hash2[slot2];
1058         ports = INET_COMBINED_PORTS(rmt_port, hnum);
1059
1060         udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
1061                 if (sk->sk_state == TCP_ESTABLISHED &&
1062                     inet6_match(net, sk, rmt_addr, loc_addr, ports, dif, sdif))
1063                         return sk;
1064                 /* Only check first socket in chain */
1065                 break;
1066         }
1067         return NULL;
1068 }
1069
1070 void udp_v6_early_demux(struct sk_buff *skb)
1071 {
1072         struct net *net = dev_net(skb->dev);
1073         const struct udphdr *uh;
1074         struct sock *sk;
1075         struct dst_entry *dst;
1076         int dif = skb->dev->ifindex;
1077         int sdif = inet6_sdif(skb);
1078
1079         if (!pskb_may_pull(skb, skb_transport_offset(skb) +
1080             sizeof(struct udphdr)))
1081                 return;
1082
1083         uh = udp_hdr(skb);
1084
1085         if (skb->pkt_type == PACKET_HOST)
1086                 sk = __udp6_lib_demux_lookup(net, uh->dest,
1087                                              &ipv6_hdr(skb)->daddr,
1088                                              uh->source, &ipv6_hdr(skb)->saddr,
1089                                              dif, sdif);
1090         else
1091                 return;
1092
1093         if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
1094                 return;
1095
1096         skb->sk = sk;
1097         skb->destructor = sock_efree;
1098         dst = rcu_dereference(sk->sk_rx_dst);
1099
1100         if (dst)
1101                 dst = dst_check(dst, sk->sk_rx_dst_cookie);
1102         if (dst) {
1103                 /* set noref for now.
1104                  * any place which wants to hold dst has to call
1105                  * dst_hold_safe()
1106                  */
1107                 skb_dst_set_noref(skb, dst);
1108         }
1109 }
1110
1111 INDIRECT_CALLABLE_SCOPE int udpv6_rcv(struct sk_buff *skb)
1112 {
1113         return __udp6_lib_rcv(skb, dev_net(skb->dev)->ipv4.udp_table, IPPROTO_UDP);
1114 }
1115
1116 /*
1117  * Throw away all pending data and cancel the corking. Socket is locked.
1118  */
1119 static void udp_v6_flush_pending_frames(struct sock *sk)
1120 {
1121         struct udp_sock *up = udp_sk(sk);
1122
1123         if (up->pending == AF_INET)
1124                 udp_flush_pending_frames(sk);
1125         else if (up->pending) {
1126                 up->len = 0;
1127                 up->pending = 0;
1128                 ip6_flush_pending_frames(sk);
1129         }
1130 }
1131
1132 static int udpv6_pre_connect(struct sock *sk, struct sockaddr *uaddr,
1133                              int addr_len)
1134 {
1135         if (addr_len < offsetofend(struct sockaddr, sa_family))
1136                 return -EINVAL;
1137         /* The following checks are replicated from __ip6_datagram_connect()
1138          * and intended to prevent BPF program called below from accessing
1139          * bytes that are out of the bound specified by user in addr_len.
1140          */
1141         if (uaddr->sa_family == AF_INET) {
1142                 if (ipv6_only_sock(sk))
1143                         return -EAFNOSUPPORT;
1144                 return udp_pre_connect(sk, uaddr, addr_len);
1145         }
1146
1147         if (addr_len < SIN6_LEN_RFC2133)
1148                 return -EINVAL;
1149
1150         return BPF_CGROUP_RUN_PROG_INET6_CONNECT_LOCK(sk, uaddr);
1151 }
1152
1153 /**
1154  *      udp6_hwcsum_outgoing  -  handle outgoing HW checksumming
1155  *      @sk:    socket we are sending on
1156  *      @skb:   sk_buff containing the filled-in UDP header
1157  *              (checksum field must be zeroed out)
1158  *      @saddr: source address
1159  *      @daddr: destination address
1160  *      @len:   length of packet
1161  */
1162 static void udp6_hwcsum_outgoing(struct sock *sk, struct sk_buff *skb,
1163                                  const struct in6_addr *saddr,
1164                                  const struct in6_addr *daddr, int len)
1165 {
1166         unsigned int offset;
1167         struct udphdr *uh = udp_hdr(skb);
1168         struct sk_buff *frags = skb_shinfo(skb)->frag_list;
1169         __wsum csum = 0;
1170
1171         if (!frags) {
1172                 /* Only one fragment on the socket.  */
1173                 skb->csum_start = skb_transport_header(skb) - skb->head;
1174                 skb->csum_offset = offsetof(struct udphdr, check);
1175                 uh->check = ~csum_ipv6_magic(saddr, daddr, len, IPPROTO_UDP, 0);
1176         } else {
1177                 /*
1178                  * HW-checksum won't work as there are two or more
1179                  * fragments on the socket so that all csums of sk_buffs
1180                  * should be together
1181                  */
1182                 offset = skb_transport_offset(skb);
1183                 skb->csum = skb_checksum(skb, offset, skb->len - offset, 0);
1184                 csum = skb->csum;
1185
1186                 skb->ip_summed = CHECKSUM_NONE;
1187
1188                 do {
1189                         csum = csum_add(csum, frags->csum);
1190                 } while ((frags = frags->next));
1191
1192                 uh->check = csum_ipv6_magic(saddr, daddr, len, IPPROTO_UDP,
1193                                             csum);
1194                 if (uh->check == 0)
1195                         uh->check = CSUM_MANGLED_0;
1196         }
1197 }
1198
1199 /*
1200  *      Sending
1201  */
1202
1203 static int udp_v6_send_skb(struct sk_buff *skb, struct flowi6 *fl6,
1204                            struct inet_cork *cork)
1205 {
1206         struct sock *sk = skb->sk;
1207         struct udphdr *uh;
1208         int err = 0;
1209         int is_udplite = IS_UDPLITE(sk);
1210         __wsum csum = 0;
1211         int offset = skb_transport_offset(skb);
1212         int len = skb->len - offset;
1213         int datalen = len - sizeof(*uh);
1214
1215         /*
1216          * Create a UDP header
1217          */
1218         uh = udp_hdr(skb);
1219         uh->source = fl6->fl6_sport;
1220         uh->dest = fl6->fl6_dport;
1221         uh->len = htons(len);
1222         uh->check = 0;
1223
1224         if (cork->gso_size) {
1225                 const int hlen = skb_network_header_len(skb) +
1226                                  sizeof(struct udphdr);
1227
1228                 if (hlen + cork->gso_size > cork->fragsize) {
1229                         kfree_skb(skb);
1230                         return -EINVAL;
1231                 }
1232                 if (datalen > cork->gso_size * UDP_MAX_SEGMENTS) {
1233                         kfree_skb(skb);
1234                         return -EINVAL;
1235                 }
1236                 if (udp_sk(sk)->no_check6_tx) {
1237                         kfree_skb(skb);
1238                         return -EINVAL;
1239                 }
1240                 if (skb->ip_summed != CHECKSUM_PARTIAL || is_udplite ||
1241                     dst_xfrm(skb_dst(skb))) {
1242                         kfree_skb(skb);
1243                         return -EIO;
1244                 }
1245
1246                 if (datalen > cork->gso_size) {
1247                         skb_shinfo(skb)->gso_size = cork->gso_size;
1248                         skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4;
1249                         skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(datalen,
1250                                                                  cork->gso_size);
1251                 }
1252                 goto csum_partial;
1253         }
1254
1255         if (is_udplite)
1256                 csum = udplite_csum(skb);
1257         else if (udp_sk(sk)->no_check6_tx) {   /* UDP csum disabled */
1258                 skb->ip_summed = CHECKSUM_NONE;
1259                 goto send;
1260         } else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
1261 csum_partial:
1262                 udp6_hwcsum_outgoing(sk, skb, &fl6->saddr, &fl6->daddr, len);
1263                 goto send;
1264         } else
1265                 csum = udp_csum(skb);
1266
1267         /* add protocol-dependent pseudo-header */
1268         uh->check = csum_ipv6_magic(&fl6->saddr, &fl6->daddr,
1269                                     len, fl6->flowi6_proto, csum);
1270         if (uh->check == 0)
1271                 uh->check = CSUM_MANGLED_0;
1272
1273 send:
1274         err = ip6_send_skb(skb);
1275         if (err) {
1276                 if (err == -ENOBUFS && !inet6_sk(sk)->recverr) {
1277                         UDP6_INC_STATS(sock_net(sk),
1278                                        UDP_MIB_SNDBUFERRORS, is_udplite);
1279                         err = 0;
1280                 }
1281         } else {
1282                 UDP6_INC_STATS(sock_net(sk),
1283                                UDP_MIB_OUTDATAGRAMS, is_udplite);
1284         }
1285         return err;
1286 }
1287
1288 static int udp_v6_push_pending_frames(struct sock *sk)
1289 {
1290         struct sk_buff *skb;
1291         struct udp_sock  *up = udp_sk(sk);
1292         int err = 0;
1293
1294         if (up->pending == AF_INET)
1295                 return udp_push_pending_frames(sk);
1296
1297         skb = ip6_finish_skb(sk);
1298         if (!skb)
1299                 goto out;
1300
1301         err = udp_v6_send_skb(skb, &inet_sk(sk)->cork.fl.u.ip6,
1302                               &inet_sk(sk)->cork.base);
1303 out:
1304         up->len = 0;
1305         up->pending = 0;
1306         return err;
1307 }
1308
1309 int udpv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1310 {
1311         struct ipv6_txoptions opt_space;
1312         struct udp_sock *up = udp_sk(sk);
1313         struct inet_sock *inet = inet_sk(sk);
1314         struct ipv6_pinfo *np = inet6_sk(sk);
1315         DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
1316         struct in6_addr *daddr, *final_p, final;
1317         struct ipv6_txoptions *opt = NULL;
1318         struct ipv6_txoptions *opt_to_free = NULL;
1319         struct ip6_flowlabel *flowlabel = NULL;
1320         struct inet_cork_full cork;
1321         struct flowi6 *fl6 = &cork.fl.u.ip6;
1322         struct dst_entry *dst;
1323         struct ipcm6_cookie ipc6;
1324         int addr_len = msg->msg_namelen;
1325         bool connected = false;
1326         int ulen = len;
1327         int corkreq = READ_ONCE(up->corkflag) || msg->msg_flags&MSG_MORE;
1328         int err;
1329         int is_udplite = IS_UDPLITE(sk);
1330         int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
1331
1332         ipcm6_init(&ipc6);
1333         ipc6.gso_size = READ_ONCE(up->gso_size);
1334         ipc6.sockc.tsflags = sk->sk_tsflags;
1335         ipc6.sockc.mark = sk->sk_mark;
1336
1337         /* destination address check */
1338         if (sin6) {
1339                 if (addr_len < offsetof(struct sockaddr, sa_data))
1340                         return -EINVAL;
1341
1342                 switch (sin6->sin6_family) {
1343                 case AF_INET6:
1344                         if (addr_len < SIN6_LEN_RFC2133)
1345                                 return -EINVAL;
1346                         daddr = &sin6->sin6_addr;
1347                         if (ipv6_addr_any(daddr) &&
1348                             ipv6_addr_v4mapped(&np->saddr))
1349                                 ipv6_addr_set_v4mapped(htonl(INADDR_LOOPBACK),
1350                                                        daddr);
1351                         break;
1352                 case AF_INET:
1353                         goto do_udp_sendmsg;
1354                 case AF_UNSPEC:
1355                         msg->msg_name = sin6 = NULL;
1356                         msg->msg_namelen = addr_len = 0;
1357                         daddr = NULL;
1358                         break;
1359                 default:
1360                         return -EINVAL;
1361                 }
1362         } else if (!up->pending) {
1363                 if (sk->sk_state != TCP_ESTABLISHED)
1364                         return -EDESTADDRREQ;
1365                 daddr = &sk->sk_v6_daddr;
1366         } else
1367                 daddr = NULL;
1368
1369         if (daddr) {
1370                 if (ipv6_addr_v4mapped(daddr)) {
1371                         struct sockaddr_in sin;
1372                         sin.sin_family = AF_INET;
1373                         sin.sin_port = sin6 ? sin6->sin6_port : inet->inet_dport;
1374                         sin.sin_addr.s_addr = daddr->s6_addr32[3];
1375                         msg->msg_name = &sin;
1376                         msg->msg_namelen = sizeof(sin);
1377 do_udp_sendmsg:
1378                         err = ipv6_only_sock(sk) ?
1379                                 -ENETUNREACH : udp_sendmsg(sk, msg, len);
1380                         msg->msg_name = sin6;
1381                         msg->msg_namelen = addr_len;
1382                         return err;
1383                 }
1384         }
1385
1386         /* Rough check on arithmetic overflow,
1387            better check is made in ip6_append_data().
1388            */
1389         if (len > INT_MAX - sizeof(struct udphdr))
1390                 return -EMSGSIZE;
1391
1392         getfrag  =  is_udplite ?  udplite_getfrag : ip_generic_getfrag;
1393         if (up->pending) {
1394                 if (up->pending == AF_INET)
1395                         return udp_sendmsg(sk, msg, len);
1396                 /*
1397                  * There are pending frames.
1398                  * The socket lock must be held while it's corked.
1399                  */
1400                 lock_sock(sk);
1401                 if (likely(up->pending)) {
1402                         if (unlikely(up->pending != AF_INET6)) {
1403                                 release_sock(sk);
1404                                 return -EAFNOSUPPORT;
1405                         }
1406                         dst = NULL;
1407                         goto do_append_data;
1408                 }
1409                 release_sock(sk);
1410         }
1411         ulen += sizeof(struct udphdr);
1412
1413         memset(fl6, 0, sizeof(*fl6));
1414
1415         if (sin6) {
1416                 if (sin6->sin6_port == 0)
1417                         return -EINVAL;
1418
1419                 fl6->fl6_dport = sin6->sin6_port;
1420                 daddr = &sin6->sin6_addr;
1421
1422                 if (np->sndflow) {
1423                         fl6->flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK;
1424                         if (fl6->flowlabel & IPV6_FLOWLABEL_MASK) {
1425                                 flowlabel = fl6_sock_lookup(sk, fl6->flowlabel);
1426                                 if (IS_ERR(flowlabel))
1427                                         return -EINVAL;
1428                         }
1429                 }
1430
1431                 /*
1432                  * Otherwise it will be difficult to maintain
1433                  * sk->sk_dst_cache.
1434                  */
1435                 if (sk->sk_state == TCP_ESTABLISHED &&
1436                     ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
1437                         daddr = &sk->sk_v6_daddr;
1438
1439                 if (addr_len >= sizeof(struct sockaddr_in6) &&
1440                     sin6->sin6_scope_id &&
1441                     __ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr)))
1442                         fl6->flowi6_oif = sin6->sin6_scope_id;
1443         } else {
1444                 if (sk->sk_state != TCP_ESTABLISHED)
1445                         return -EDESTADDRREQ;
1446
1447                 fl6->fl6_dport = inet->inet_dport;
1448                 daddr = &sk->sk_v6_daddr;
1449                 fl6->flowlabel = np->flow_label;
1450                 connected = true;
1451         }
1452
1453         if (!fl6->flowi6_oif)
1454                 fl6->flowi6_oif = READ_ONCE(sk->sk_bound_dev_if);
1455
1456         if (!fl6->flowi6_oif)
1457                 fl6->flowi6_oif = np->sticky_pktinfo.ipi6_ifindex;
1458
1459         fl6->flowi6_uid = sk->sk_uid;
1460
1461         if (msg->msg_controllen) {
1462                 opt = &opt_space;
1463                 memset(opt, 0, sizeof(struct ipv6_txoptions));
1464                 opt->tot_len = sizeof(*opt);
1465                 ipc6.opt = opt;
1466
1467                 err = udp_cmsg_send(sk, msg, &ipc6.gso_size);
1468                 if (err > 0)
1469                         err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, fl6,
1470                                                     &ipc6);
1471                 if (err < 0) {
1472                         fl6_sock_release(flowlabel);
1473                         return err;
1474                 }
1475                 if ((fl6->flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) {
1476                         flowlabel = fl6_sock_lookup(sk, fl6->flowlabel);
1477                         if (IS_ERR(flowlabel))
1478                                 return -EINVAL;
1479                 }
1480                 if (!(opt->opt_nflen|opt->opt_flen))
1481                         opt = NULL;
1482                 connected = false;
1483         }
1484         if (!opt) {
1485                 opt = txopt_get(np);
1486                 opt_to_free = opt;
1487         }
1488         if (flowlabel)
1489                 opt = fl6_merge_options(&opt_space, flowlabel, opt);
1490         opt = ipv6_fixup_options(&opt_space, opt);
1491         ipc6.opt = opt;
1492
1493         fl6->flowi6_proto = sk->sk_protocol;
1494         fl6->flowi6_mark = ipc6.sockc.mark;
1495         fl6->daddr = *daddr;
1496         if (ipv6_addr_any(&fl6->saddr) && !ipv6_addr_any(&np->saddr))
1497                 fl6->saddr = np->saddr;
1498         fl6->fl6_sport = inet->inet_sport;
1499
1500         if (cgroup_bpf_enabled(CGROUP_UDP6_SENDMSG) && !connected) {
1501                 err = BPF_CGROUP_RUN_PROG_UDP6_SENDMSG_LOCK(sk,
1502                                            (struct sockaddr *)sin6,
1503                                            &fl6->saddr);
1504                 if (err)
1505                         goto out_no_dst;
1506                 if (sin6) {
1507                         if (ipv6_addr_v4mapped(&sin6->sin6_addr)) {
1508                                 /* BPF program rewrote IPv6-only by IPv4-mapped
1509                                  * IPv6. It's currently unsupported.
1510                                  */
1511                                 err = -ENOTSUPP;
1512                                 goto out_no_dst;
1513                         }
1514                         if (sin6->sin6_port == 0) {
1515                                 /* BPF program set invalid port. Reject it. */
1516                                 err = -EINVAL;
1517                                 goto out_no_dst;
1518                         }
1519                         fl6->fl6_dport = sin6->sin6_port;
1520                         fl6->daddr = sin6->sin6_addr;
1521                 }
1522         }
1523
1524         if (ipv6_addr_any(&fl6->daddr))
1525                 fl6->daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
1526
1527         final_p = fl6_update_dst(fl6, opt, &final);
1528         if (final_p)
1529                 connected = false;
1530
1531         if (!fl6->flowi6_oif && ipv6_addr_is_multicast(&fl6->daddr)) {
1532                 fl6->flowi6_oif = np->mcast_oif;
1533                 connected = false;
1534         } else if (!fl6->flowi6_oif)
1535                 fl6->flowi6_oif = np->ucast_oif;
1536
1537         security_sk_classify_flow(sk, flowi6_to_flowi_common(fl6));
1538
1539         if (ipc6.tclass < 0)
1540                 ipc6.tclass = np->tclass;
1541
1542         fl6->flowlabel = ip6_make_flowinfo(ipc6.tclass, fl6->flowlabel);
1543
1544         dst = ip6_sk_dst_lookup_flow(sk, fl6, final_p, connected);
1545         if (IS_ERR(dst)) {
1546                 err = PTR_ERR(dst);
1547                 dst = NULL;
1548                 goto out;
1549         }
1550
1551         if (ipc6.hlimit < 0)
1552                 ipc6.hlimit = ip6_sk_dst_hoplimit(np, fl6, dst);
1553
1554         if (msg->msg_flags&MSG_CONFIRM)
1555                 goto do_confirm;
1556 back_from_confirm:
1557
1558         /* Lockless fast path for the non-corking case */
1559         if (!corkreq) {
1560                 struct sk_buff *skb;
1561
1562                 skb = ip6_make_skb(sk, getfrag, msg, ulen,
1563                                    sizeof(struct udphdr), &ipc6,
1564                                    (struct rt6_info *)dst,
1565                                    msg->msg_flags, &cork);
1566                 err = PTR_ERR(skb);
1567                 if (!IS_ERR_OR_NULL(skb))
1568                         err = udp_v6_send_skb(skb, fl6, &cork.base);
1569                 /* ip6_make_skb steals dst reference */
1570                 goto out_no_dst;
1571         }
1572
1573         lock_sock(sk);
1574         if (unlikely(up->pending)) {
1575                 /* The socket is already corked while preparing it. */
1576                 /* ... which is an evident application bug. --ANK */
1577                 release_sock(sk);
1578
1579                 net_dbg_ratelimited("udp cork app bug 2\n");
1580                 err = -EINVAL;
1581                 goto out;
1582         }
1583
1584         up->pending = AF_INET6;
1585
1586 do_append_data:
1587         if (ipc6.dontfrag < 0)
1588                 ipc6.dontfrag = np->dontfrag;
1589         up->len += ulen;
1590         err = ip6_append_data(sk, getfrag, msg, ulen, sizeof(struct udphdr),
1591                               &ipc6, fl6, (struct rt6_info *)dst,
1592                               corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
1593         if (err)
1594                 udp_v6_flush_pending_frames(sk);
1595         else if (!corkreq)
1596                 err = udp_v6_push_pending_frames(sk);
1597         else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
1598                 up->pending = 0;
1599
1600         if (err > 0)
1601                 err = np->recverr ? net_xmit_errno(err) : 0;
1602         release_sock(sk);
1603
1604 out:
1605         dst_release(dst);
1606 out_no_dst:
1607         fl6_sock_release(flowlabel);
1608         txopt_put(opt_to_free);
1609         if (!err)
1610                 return len;
1611         /*
1612          * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space.  Reporting
1613          * ENOBUFS might not be good (it's not tunable per se), but otherwise
1614          * we don't have a good statistic (IpOutDiscards but it can be too many
1615          * things).  We could add another new stat but at least for now that
1616          * seems like overkill.
1617          */
1618         if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
1619                 UDP6_INC_STATS(sock_net(sk),
1620                                UDP_MIB_SNDBUFERRORS, is_udplite);
1621         }
1622         return err;
1623
1624 do_confirm:
1625         if (msg->msg_flags & MSG_PROBE)
1626                 dst_confirm_neigh(dst, &fl6->daddr);
1627         if (!(msg->msg_flags&MSG_PROBE) || len)
1628                 goto back_from_confirm;
1629         err = 0;
1630         goto out;
1631 }
1632 EXPORT_SYMBOL(udpv6_sendmsg);
1633
1634 static void udpv6_splice_eof(struct socket *sock)
1635 {
1636         struct sock *sk = sock->sk;
1637         struct udp_sock *up = udp_sk(sk);
1638
1639         if (!up->pending || READ_ONCE(up->corkflag))
1640                 return;
1641
1642         lock_sock(sk);
1643         if (up->pending && !READ_ONCE(up->corkflag))
1644                 udp_v6_push_pending_frames(sk);
1645         release_sock(sk);
1646 }
1647
1648 void udpv6_destroy_sock(struct sock *sk)
1649 {
1650         struct udp_sock *up = udp_sk(sk);
1651         lock_sock(sk);
1652
1653         /* protects from races with udp_abort() */
1654         sock_set_flag(sk, SOCK_DEAD);
1655         udp_v6_flush_pending_frames(sk);
1656         release_sock(sk);
1657
1658         if (static_branch_unlikely(&udpv6_encap_needed_key)) {
1659                 if (up->encap_type) {
1660                         void (*encap_destroy)(struct sock *sk);
1661                         encap_destroy = READ_ONCE(up->encap_destroy);
1662                         if (encap_destroy)
1663                                 encap_destroy(sk);
1664                 }
1665                 if (up->encap_enabled) {
1666                         static_branch_dec(&udpv6_encap_needed_key);
1667                         udp_encap_disable();
1668                 }
1669         }
1670 }
1671
1672 /*
1673  *      Socket option code for UDP
1674  */
1675 int udpv6_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
1676                      unsigned int optlen)
1677 {
1678         if (level == SOL_UDP  ||  level == SOL_UDPLITE || level == SOL_SOCKET)
1679                 return udp_lib_setsockopt(sk, level, optname,
1680                                           optval, optlen,
1681                                           udp_v6_push_pending_frames);
1682         return ipv6_setsockopt(sk, level, optname, optval, optlen);
1683 }
1684
1685 int udpv6_getsockopt(struct sock *sk, int level, int optname,
1686                      char __user *optval, int __user *optlen)
1687 {
1688         if (level == SOL_UDP  ||  level == SOL_UDPLITE)
1689                 return udp_lib_getsockopt(sk, level, optname, optval, optlen);
1690         return ipv6_getsockopt(sk, level, optname, optval, optlen);
1691 }
1692
1693 static const struct inet6_protocol udpv6_protocol = {
1694         .handler        =       udpv6_rcv,
1695         .err_handler    =       udpv6_err,
1696         .flags          =       INET6_PROTO_NOPOLICY|INET6_PROTO_FINAL,
1697 };
1698
1699 /* ------------------------------------------------------------------------ */
1700 #ifdef CONFIG_PROC_FS
1701 int udp6_seq_show(struct seq_file *seq, void *v)
1702 {
1703         if (v == SEQ_START_TOKEN) {
1704                 seq_puts(seq, IPV6_SEQ_DGRAM_HEADER);
1705         } else {
1706                 int bucket = ((struct udp_iter_state *)seq->private)->bucket;
1707                 const struct inet_sock *inet = inet_sk((const struct sock *)v);
1708                 __u16 srcp = ntohs(inet->inet_sport);
1709                 __u16 destp = ntohs(inet->inet_dport);
1710                 __ip6_dgram_sock_seq_show(seq, v, srcp, destp,
1711                                           udp_rqueue_get(v), bucket);
1712         }
1713         return 0;
1714 }
1715
1716 const struct seq_operations udp6_seq_ops = {
1717         .start          = udp_seq_start,
1718         .next           = udp_seq_next,
1719         .stop           = udp_seq_stop,
1720         .show           = udp6_seq_show,
1721 };
1722 EXPORT_SYMBOL(udp6_seq_ops);
1723
1724 static struct udp_seq_afinfo udp6_seq_afinfo = {
1725         .family         = AF_INET6,
1726         .udp_table      = NULL,
1727 };
1728
1729 int __net_init udp6_proc_init(struct net *net)
1730 {
1731         if (!proc_create_net_data("udp6", 0444, net->proc_net, &udp6_seq_ops,
1732                         sizeof(struct udp_iter_state), &udp6_seq_afinfo))
1733                 return -ENOMEM;
1734         return 0;
1735 }
1736
1737 void udp6_proc_exit(struct net *net)
1738 {
1739         remove_proc_entry("udp6", net->proc_net);
1740 }
1741 #endif /* CONFIG_PROC_FS */
1742
1743 /* ------------------------------------------------------------------------ */
1744
1745 struct proto udpv6_prot = {
1746         .name                   = "UDPv6",
1747         .owner                  = THIS_MODULE,
1748         .close                  = udp_lib_close,
1749         .pre_connect            = udpv6_pre_connect,
1750         .connect                = ip6_datagram_connect,
1751         .disconnect             = udp_disconnect,
1752         .ioctl                  = udp_ioctl,
1753         .init                   = udpv6_init_sock,
1754         .destroy                = udpv6_destroy_sock,
1755         .setsockopt             = udpv6_setsockopt,
1756         .getsockopt             = udpv6_getsockopt,
1757         .sendmsg                = udpv6_sendmsg,
1758         .recvmsg                = udpv6_recvmsg,
1759         .splice_eof             = udpv6_splice_eof,
1760         .release_cb             = ip6_datagram_release_cb,
1761         .hash                   = udp_lib_hash,
1762         .unhash                 = udp_lib_unhash,
1763         .rehash                 = udp_v6_rehash,
1764         .get_port               = udp_v6_get_port,
1765         .put_port               = udp_lib_unhash,
1766 #ifdef CONFIG_BPF_SYSCALL
1767         .psock_update_sk_prot   = udp_bpf_update_proto,
1768 #endif
1769
1770         .memory_allocated       = &udp_memory_allocated,
1771         .per_cpu_fw_alloc       = &udp_memory_per_cpu_fw_alloc,
1772
1773         .sysctl_mem             = sysctl_udp_mem,
1774         .sysctl_wmem_offset     = offsetof(struct net, ipv4.sysctl_udp_wmem_min),
1775         .sysctl_rmem_offset     = offsetof(struct net, ipv4.sysctl_udp_rmem_min),
1776         .obj_size               = sizeof(struct udp6_sock),
1777         .ipv6_pinfo_offset = offsetof(struct udp6_sock, inet6),
1778         .h.udp_table            = NULL,
1779         .diag_destroy           = udp_abort,
1780 };
1781
1782 static struct inet_protosw udpv6_protosw = {
1783         .type =      SOCK_DGRAM,
1784         .protocol =  IPPROTO_UDP,
1785         .prot =      &udpv6_prot,
1786         .ops =       &inet6_dgram_ops,
1787         .flags =     INET_PROTOSW_PERMANENT,
1788 };
1789
1790 int __init udpv6_init(void)
1791 {
1792         int ret;
1793
1794         ret = inet6_add_protocol(&udpv6_protocol, IPPROTO_UDP);
1795         if (ret)
1796                 goto out;
1797
1798         ret = inet6_register_protosw(&udpv6_protosw);
1799         if (ret)
1800                 goto out_udpv6_protocol;
1801 out:
1802         return ret;
1803
1804 out_udpv6_protocol:
1805         inet6_del_protocol(&udpv6_protocol, IPPROTO_UDP);
1806         goto out;
1807 }
1808
1809 void udpv6_exit(void)
1810 {
1811         inet6_unregister_protosw(&udpv6_protosw);
1812         inet6_del_protocol(&udpv6_protocol, IPPROTO_UDP);
1813 }