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