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