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 * Generic socket support routines. Memory allocators, socket lock/release 8 * handler for protocols to use and generic option handler. 9 * 10 * Authors: Ross Biro 11 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> 12 * Florian La Roche, <flla@stud.uni-sb.de> 13 * Alan Cox, <A.Cox@swansea.ac.uk> 14 * 15 * Fixes: 16 * Alan Cox : Numerous verify_area() problems 17 * Alan Cox : Connecting on a connecting socket 18 * now returns an error for tcp. 19 * Alan Cox : sock->protocol is set correctly. 20 * and is not sometimes left as 0. 21 * Alan Cox : connect handles icmp errors on a 22 * connect properly. Unfortunately there 23 * is a restart syscall nasty there. I 24 * can't match BSD without hacking the C 25 * library. Ideas urgently sought! 26 * Alan Cox : Disallow bind() to addresses that are 27 * not ours - especially broadcast ones!! 28 * Alan Cox : Socket 1024 _IS_ ok for users. (fencepost) 29 * Alan Cox : sock_wfree/sock_rfree don't destroy sockets, 30 * instead they leave that for the DESTROY timer. 31 * Alan Cox : Clean up error flag in accept 32 * Alan Cox : TCP ack handling is buggy, the DESTROY timer 33 * was buggy. Put a remove_sock() in the handler 34 * for memory when we hit 0. Also altered the timer 35 * code. The ACK stuff can wait and needs major 36 * TCP layer surgery. 37 * Alan Cox : Fixed TCP ack bug, removed remove sock 38 * and fixed timer/inet_bh race. 39 * Alan Cox : Added zapped flag for TCP 40 * Alan Cox : Move kfree_skb into skbuff.c and tidied up surplus code 41 * Alan Cox : for new sk_buff allocations wmalloc/rmalloc now call alloc_skb 42 * Alan Cox : kfree_s calls now are kfree_skbmem so we can track skb resources 43 * Alan Cox : Supports socket option broadcast now as does udp. Packet and raw need fixing. 44 * Alan Cox : Added RCVBUF,SNDBUF size setting. It suddenly occurred to me how easy it was so... 45 * Rick Sladkey : Relaxed UDP rules for matching packets. 46 * C.E.Hawkins : IFF_PROMISC/SIOCGHWADDR support 47 * Pauline Middelink : identd support 48 * Alan Cox : Fixed connect() taking signals I think. 49 * Alan Cox : SO_LINGER supported 50 * Alan Cox : Error reporting fixes 51 * Anonymous : inet_create tidied up (sk->reuse setting) 52 * Alan Cox : inet sockets don't set sk->type! 53 * Alan Cox : Split socket option code 54 * Alan Cox : Callbacks 55 * Alan Cox : Nagle flag for Charles & Johannes stuff 56 * Alex : Removed restriction on inet fioctl 57 * Alan Cox : Splitting INET from NET core 58 * Alan Cox : Fixed bogus SO_TYPE handling in getsockopt() 59 * Adam Caldwell : Missing return in SO_DONTROUTE/SO_DEBUG code 60 * Alan Cox : Split IP from generic code 61 * Alan Cox : New kfree_skbmem() 62 * Alan Cox : Make SO_DEBUG superuser only. 63 * Alan Cox : Allow anyone to clear SO_DEBUG 64 * (compatibility fix) 65 * Alan Cox : Added optimistic memory grabbing for AF_UNIX throughput. 66 * Alan Cox : Allocator for a socket is settable. 67 * Alan Cox : SO_ERROR includes soft errors. 68 * Alan Cox : Allow NULL arguments on some SO_ opts 69 * Alan Cox : Generic socket allocation to make hooks 70 * easier (suggested by Craig Metz). 71 * Michael Pall : SO_ERROR returns positive errno again 72 * Steve Whitehouse: Added default destructor to free 73 * protocol private data. 74 * Steve Whitehouse: Added various other default routines 75 * common to several socket families. 76 * Chris Evans : Call suser() check last on F_SETOWN 77 * Jay Schulist : Added SO_ATTACH_FILTER and SO_DETACH_FILTER. 78 * Andi Kleen : Add sock_kmalloc()/sock_kfree_s() 79 * Andi Kleen : Fix write_space callback 80 * Chris Evans : Security fixes - signedness again 81 * Arnaldo C. Melo : cleanups, use skb_queue_purge 82 * 83 * To Fix: 84 */ 85 86 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 87 88 #include <linux/unaligned.h> 89 #include <linux/capability.h> 90 #include <linux/errno.h> 91 #include <linux/errqueue.h> 92 #include <linux/types.h> 93 #include <linux/socket.h> 94 #include <linux/in.h> 95 #include <linux/kernel.h> 96 #include <linux/module.h> 97 #include <linux/proc_fs.h> 98 #include <linux/seq_file.h> 99 #include <linux/sched.h> 100 #include <linux/sched/mm.h> 101 #include <linux/timer.h> 102 #include <linux/string.h> 103 #include <linux/sockios.h> 104 #include <linux/net.h> 105 #include <linux/mm.h> 106 #include <linux/slab.h> 107 #include <linux/interrupt.h> 108 #include <linux/poll.h> 109 #include <linux/tcp.h> 110 #include <linux/udp.h> 111 #include <linux/init.h> 112 #include <linux/highmem.h> 113 #include <linux/user_namespace.h> 114 #include <linux/static_key.h> 115 #include <linux/memcontrol.h> 116 #include <linux/prefetch.h> 117 #include <linux/compat.h> 118 #include <linux/mroute.h> 119 #include <linux/mroute6.h> 120 #include <linux/icmpv6.h> 121 122 #include <linux/uaccess.h> 123 124 #include <linux/netdevice.h> 125 #include <net/protocol.h> 126 #include <linux/skbuff.h> 127 #include <linux/skbuff_ref.h> 128 #include <net/net_namespace.h> 129 #include <net/request_sock.h> 130 #include <net/sock.h> 131 #include <net/proto_memory.h> 132 #include <net/page_pool/types.h> 133 #include <linux/net_tstamp.h> 134 #include <net/xfrm.h> 135 #include <linux/ipsec.h> 136 #include <net/cls_cgroup.h> 137 #include <net/netprio_cgroup.h> 138 #include <linux/sock_diag.h> 139 140 #include <linux/filter.h> 141 #include <net/sock_reuseport.h> 142 #include <net/bpf_sk_storage.h> 143 144 #include <trace/events/sock.h> 145 146 #include <net/psp.h> 147 #include <net/tcp.h> 148 #include <net/busy_poll.h> 149 #include <net/phonet/phonet.h> 150 151 #include <linux/ethtool.h> 152 153 #include <uapi/linux/pidfd.h> 154 155 #include "dev.h" 156 157 static DEFINE_MUTEX(proto_list_mutex); 158 static LIST_HEAD(proto_list); 159 160 static void sock_def_write_space_wfree(struct sock *sk, int wmem_alloc); 161 static void sock_def_write_space(struct sock *sk); 162 163 /** 164 * sk_ns_capable - General socket capability test 165 * @sk: Socket to use a capability on or through 166 * @user_ns: The user namespace of the capability to use 167 * @cap: The capability to use 168 * 169 * Test to see if the opener of the socket had when the socket was 170 * created and the current process has the capability @cap in the user 171 * namespace @user_ns. 172 */ 173 bool sk_ns_capable(const struct sock *sk, 174 struct user_namespace *user_ns, int cap) 175 { 176 return file_ns_capable(sk->sk_socket->file, user_ns, cap) && 177 ns_capable(user_ns, cap); 178 } 179 EXPORT_SYMBOL(sk_ns_capable); 180 181 /** 182 * sk_capable - Socket global capability test 183 * @sk: Socket to use a capability on or through 184 * @cap: The global capability to use 185 * 186 * Test to see if the opener of the socket had when the socket was 187 * created and the current process has the capability @cap in all user 188 * namespaces. 189 */ 190 bool sk_capable(const struct sock *sk, int cap) 191 { 192 return sk_ns_capable(sk, &init_user_ns, cap); 193 } 194 EXPORT_SYMBOL(sk_capable); 195 196 /** 197 * sk_net_capable - Network namespace socket capability test 198 * @sk: Socket to use a capability on or through 199 * @cap: The capability to use 200 * 201 * Test to see if the opener of the socket had when the socket was created 202 * and the current process has the capability @cap over the network namespace 203 * the socket is a member of. 204 */ 205 bool sk_net_capable(const struct sock *sk, int cap) 206 { 207 return sk_ns_capable(sk, sock_net(sk)->user_ns, cap); 208 } 209 EXPORT_SYMBOL(sk_net_capable); 210 211 /* 212 * Each address family might have different locking rules, so we have 213 * one slock key per address family and separate keys for internal and 214 * userspace sockets. 215 */ 216 static struct lock_class_key af_family_keys[AF_MAX]; 217 static struct lock_class_key af_family_kern_keys[AF_MAX]; 218 static struct lock_class_key af_family_slock_keys[AF_MAX]; 219 static struct lock_class_key af_family_kern_slock_keys[AF_MAX]; 220 221 /* 222 * Make lock validator output more readable. (we pre-construct these 223 * strings build-time, so that runtime initialization of socket 224 * locks is fast): 225 */ 226 227 #define _sock_locks(x) \ 228 x "AF_UNSPEC", x "AF_UNIX" , x "AF_INET" , \ 229 x "AF_AX25" , x "AF_IPX" , x "AF_APPLETALK", \ 230 x "AF_NETROM", x "AF_BRIDGE" , x "AF_ATMPVC" , \ 231 x "AF_X25" , x "AF_INET6" , x "AF_ROSE" , \ 232 x "AF_DECnet", x "AF_NETBEUI" , x "AF_SECURITY" , \ 233 x "AF_KEY" , x "AF_NETLINK" , x "AF_PACKET" , \ 234 x "AF_ASH" , x "AF_ECONET" , x "AF_ATMSVC" , \ 235 x "AF_RDS" , x "AF_SNA" , x "AF_IRDA" , \ 236 x "AF_PPPOX" , x "AF_WANPIPE" , x "AF_LLC" , \ 237 x "27" , x "28" , x "AF_CAN" , \ 238 x "AF_TIPC" , x "AF_BLUETOOTH", x "IUCV" , \ 239 x "AF_RXRPC" , x "AF_ISDN" , x "AF_PHONET" , \ 240 x "AF_IEEE802154", x "AF_CAIF" , x "AF_ALG" , \ 241 x "AF_NFC" , x "AF_VSOCK" , x "AF_KCM" , \ 242 x "AF_QIPCRTR", x "AF_SMC" , x "AF_XDP" , \ 243 x "AF_MCTP" , \ 244 x "AF_MAX" 245 246 static const char *const af_family_key_strings[AF_MAX+1] = { 247 _sock_locks("sk_lock-") 248 }; 249 static const char *const af_family_slock_key_strings[AF_MAX+1] = { 250 _sock_locks("slock-") 251 }; 252 static const char *const af_family_clock_key_strings[AF_MAX+1] = { 253 _sock_locks("clock-") 254 }; 255 256 static const char *const af_family_kern_key_strings[AF_MAX+1] = { 257 _sock_locks("k-sk_lock-") 258 }; 259 static const char *const af_family_kern_slock_key_strings[AF_MAX+1] = { 260 _sock_locks("k-slock-") 261 }; 262 static const char *const af_family_kern_clock_key_strings[AF_MAX+1] = { 263 _sock_locks("k-clock-") 264 }; 265 static const char *const af_family_rlock_key_strings[AF_MAX+1] = { 266 _sock_locks("rlock-") 267 }; 268 static const char *const af_family_wlock_key_strings[AF_MAX+1] = { 269 _sock_locks("wlock-") 270 }; 271 static const char *const af_family_elock_key_strings[AF_MAX+1] = { 272 _sock_locks("elock-") 273 }; 274 275 /* 276 * sk_callback_lock and sk queues locking rules are per-address-family, 277 * so split the lock classes by using a per-AF key: 278 */ 279 static struct lock_class_key af_callback_keys[AF_MAX]; 280 static struct lock_class_key af_rlock_keys[AF_MAX]; 281 static struct lock_class_key af_wlock_keys[AF_MAX]; 282 static struct lock_class_key af_elock_keys[AF_MAX]; 283 static struct lock_class_key af_kern_callback_keys[AF_MAX]; 284 285 /* Run time adjustable parameters. */ 286 __u32 sysctl_wmem_max __read_mostly = 4 << 20; 287 EXPORT_SYMBOL(sysctl_wmem_max); 288 __u32 sysctl_rmem_max __read_mostly = 4 << 20; 289 EXPORT_SYMBOL(sysctl_rmem_max); 290 __u32 sysctl_wmem_default __read_mostly = SK_WMEM_DEFAULT; 291 __u32 sysctl_rmem_default __read_mostly = SK_RMEM_DEFAULT; 292 293 DEFINE_STATIC_KEY_FALSE(memalloc_socks_key); 294 EXPORT_SYMBOL_GPL(memalloc_socks_key); 295 296 /** 297 * sk_set_memalloc - sets %SOCK_MEMALLOC 298 * @sk: socket to set it on 299 * 300 * Set %SOCK_MEMALLOC on a socket for access to emergency reserves. 301 * It's the responsibility of the admin to adjust min_free_kbytes 302 * to meet the requirements 303 */ 304 void sk_set_memalloc(struct sock *sk) 305 { 306 sock_set_flag(sk, SOCK_MEMALLOC); 307 sk->sk_allocation |= __GFP_MEMALLOC; 308 static_branch_inc(&memalloc_socks_key); 309 } 310 EXPORT_SYMBOL_GPL(sk_set_memalloc); 311 312 void sk_clear_memalloc(struct sock *sk) 313 { 314 sock_reset_flag(sk, SOCK_MEMALLOC); 315 sk->sk_allocation &= ~__GFP_MEMALLOC; 316 static_branch_dec(&memalloc_socks_key); 317 318 /* 319 * SOCK_MEMALLOC is allowed to ignore rmem limits to ensure forward 320 * progress of swapping. SOCK_MEMALLOC may be cleared while 321 * it has rmem allocations due to the last swapfile being deactivated 322 * but there is a risk that the socket is unusable due to exceeding 323 * the rmem limits. Reclaim the reserves and obey rmem limits again. 324 */ 325 sk_mem_reclaim(sk); 326 } 327 EXPORT_SYMBOL_GPL(sk_clear_memalloc); 328 329 int __sk_backlog_rcv(struct sock *sk, struct sk_buff *skb) 330 { 331 int ret; 332 unsigned int noreclaim_flag; 333 334 /* these should have been dropped before queueing */ 335 BUG_ON(!sock_flag(sk, SOCK_MEMALLOC)); 336 337 noreclaim_flag = memalloc_noreclaim_save(); 338 ret = INDIRECT_CALL_INET(sk->sk_backlog_rcv, 339 tcp_v6_do_rcv, 340 tcp_v4_do_rcv, 341 sk, skb); 342 memalloc_noreclaim_restore(noreclaim_flag); 343 344 return ret; 345 } 346 EXPORT_SYMBOL(__sk_backlog_rcv); 347 348 void sk_error_report(struct sock *sk) 349 { 350 sk->sk_error_report(sk); 351 352 switch (sk->sk_family) { 353 case AF_INET: 354 fallthrough; 355 case AF_INET6: 356 trace_inet_sk_error_report(sk); 357 break; 358 default: 359 break; 360 } 361 } 362 EXPORT_SYMBOL(sk_error_report); 363 364 int sock_get_timeout(long timeo, void *optval, bool old_timeval) 365 { 366 struct __kernel_sock_timeval tv; 367 368 if (timeo == MAX_SCHEDULE_TIMEOUT) { 369 tv.tv_sec = 0; 370 tv.tv_usec = 0; 371 } else { 372 tv.tv_sec = timeo / HZ; 373 tv.tv_usec = ((timeo % HZ) * USEC_PER_SEC) / HZ; 374 } 375 376 if (old_timeval && in_compat_syscall() && !COMPAT_USE_64BIT_TIME) { 377 struct old_timeval32 tv32 = { tv.tv_sec, tv.tv_usec }; 378 *(struct old_timeval32 *)optval = tv32; 379 return sizeof(tv32); 380 } 381 382 if (old_timeval) { 383 struct __kernel_old_timeval old_tv; 384 old_tv.tv_sec = tv.tv_sec; 385 old_tv.tv_usec = tv.tv_usec; 386 *(struct __kernel_old_timeval *)optval = old_tv; 387 return sizeof(old_tv); 388 } 389 390 *(struct __kernel_sock_timeval *)optval = tv; 391 return sizeof(tv); 392 } 393 EXPORT_SYMBOL(sock_get_timeout); 394 395 int sock_copy_user_timeval(struct __kernel_sock_timeval *tv, 396 sockptr_t optval, int optlen, bool old_timeval) 397 { 398 if (old_timeval && in_compat_syscall() && !COMPAT_USE_64BIT_TIME) { 399 struct old_timeval32 tv32; 400 401 if (optlen < sizeof(tv32)) 402 return -EINVAL; 403 404 if (copy_from_sockptr(&tv32, optval, sizeof(tv32))) 405 return -EFAULT; 406 tv->tv_sec = tv32.tv_sec; 407 tv->tv_usec = tv32.tv_usec; 408 } else if (old_timeval) { 409 struct __kernel_old_timeval old_tv; 410 411 if (optlen < sizeof(old_tv)) 412 return -EINVAL; 413 if (copy_from_sockptr(&old_tv, optval, sizeof(old_tv))) 414 return -EFAULT; 415 tv->tv_sec = old_tv.tv_sec; 416 tv->tv_usec = old_tv.tv_usec; 417 } else { 418 if (optlen < sizeof(*tv)) 419 return -EINVAL; 420 if (copy_from_sockptr(tv, optval, sizeof(*tv))) 421 return -EFAULT; 422 } 423 424 return 0; 425 } 426 EXPORT_SYMBOL(sock_copy_user_timeval); 427 428 static int sock_set_timeout(long *timeo_p, sockptr_t optval, int optlen, 429 bool old_timeval) 430 { 431 struct __kernel_sock_timeval tv; 432 int err = sock_copy_user_timeval(&tv, optval, optlen, old_timeval); 433 long val; 434 435 if (err) 436 return err; 437 438 if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC) 439 return -EDOM; 440 441 if (tv.tv_sec < 0) { 442 static int warned __read_mostly; 443 444 WRITE_ONCE(*timeo_p, 0); 445 if (warned < 10 && net_ratelimit()) { 446 warned++; 447 pr_info("%s: `%s' (pid %d) tries to set negative timeout\n", 448 __func__, current->comm, task_pid_nr(current)); 449 } 450 return 0; 451 } 452 val = MAX_SCHEDULE_TIMEOUT; 453 if ((tv.tv_sec || tv.tv_usec) && 454 (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1))) 455 val = tv.tv_sec * HZ + DIV_ROUND_UP((unsigned long)tv.tv_usec, 456 USEC_PER_SEC / HZ); 457 WRITE_ONCE(*timeo_p, val); 458 return 0; 459 } 460 461 static bool sk_set_prio_allowed(const struct sock *sk, int val) 462 { 463 return ((val >= TC_PRIO_BESTEFFORT && val <= TC_PRIO_INTERACTIVE) || 464 sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_RAW) || 465 sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)); 466 } 467 468 static bool sock_needs_netstamp(const struct sock *sk) 469 { 470 switch (sk->sk_family) { 471 case AF_UNSPEC: 472 case AF_UNIX: 473 return false; 474 default: 475 return true; 476 } 477 } 478 479 static void sock_disable_timestamp(struct sock *sk, unsigned long flags) 480 { 481 if (sk->sk_flags & flags) { 482 sk->sk_flags &= ~flags; 483 if (sock_needs_netstamp(sk) && 484 !(sk->sk_flags & SK_FLAGS_TIMESTAMP)) 485 net_disable_timestamp(); 486 } 487 } 488 489 490 int __sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) 491 { 492 unsigned long flags; 493 struct sk_buff_head *list = &sk->sk_receive_queue; 494 495 if (atomic_read(&sk->sk_rmem_alloc) >= READ_ONCE(sk->sk_rcvbuf)) { 496 sk_drops_inc(sk); 497 trace_sock_rcvqueue_full(sk, skb); 498 return -ENOMEM; 499 } 500 501 if (!sk_rmem_schedule(sk, skb, skb->truesize)) { 502 sk_drops_inc(sk); 503 return -ENOBUFS; 504 } 505 506 skb->dev = NULL; 507 skb_set_owner_r(skb, sk); 508 509 /* we escape from rcu protected region, make sure we dont leak 510 * a norefcounted dst 511 */ 512 skb_dst_force(skb); 513 514 spin_lock_irqsave(&list->lock, flags); 515 sock_skb_set_dropcount(sk, skb); 516 __skb_queue_tail(list, skb); 517 spin_unlock_irqrestore(&list->lock, flags); 518 519 if (!sock_flag(sk, SOCK_DEAD)) 520 sk->sk_data_ready(sk); 521 return 0; 522 } 523 EXPORT_SYMBOL(__sock_queue_rcv_skb); 524 525 enum skb_drop_reason 526 sock_queue_rcv_skb_reason(struct sock *sk, struct sk_buff *skb) 527 { 528 enum skb_drop_reason drop_reason; 529 int err; 530 531 drop_reason = sk_filter_reason(sk, skb); 532 if (drop_reason) 533 return drop_reason; 534 535 err = __sock_queue_rcv_skb(sk, skb); 536 switch (err) { 537 case -ENOMEM: 538 return SKB_DROP_REASON_SOCKET_RCVBUFF; 539 case -ENOBUFS: 540 return SKB_DROP_REASON_PROTO_MEM; 541 } 542 return SKB_NOT_DROPPED_YET; 543 } 544 EXPORT_SYMBOL(sock_queue_rcv_skb_reason); 545 546 int __sk_receive_skb(struct sock *sk, struct sk_buff *skb, 547 const int nested, unsigned int trim_cap, bool refcounted) 548 { 549 enum skb_drop_reason reason; 550 int rc = NET_RX_SUCCESS; 551 int err; 552 553 reason = sk_filter_trim_cap(sk, skb, trim_cap); 554 if (reason) 555 goto discard_and_relse; 556 557 skb->dev = NULL; 558 559 if (sk_rcvqueues_full(sk, READ_ONCE(sk->sk_rcvbuf))) { 560 sk_drops_inc(sk); 561 reason = SKB_DROP_REASON_SOCKET_RCVBUFF; 562 goto discard_and_relse; 563 } 564 if (nested) 565 bh_lock_sock_nested(sk); 566 else 567 bh_lock_sock(sk); 568 if (!sock_owned_by_user(sk)) { 569 /* 570 * trylock + unlock semantics: 571 */ 572 mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_); 573 574 rc = sk_backlog_rcv(sk, skb); 575 576 mutex_release(&sk->sk_lock.dep_map, _RET_IP_); 577 } else if ((err = sk_add_backlog(sk, skb, READ_ONCE(sk->sk_rcvbuf)))) { 578 bh_unlock_sock(sk); 579 if (err == -ENOMEM) 580 reason = SKB_DROP_REASON_PFMEMALLOC; 581 if (err == -ENOBUFS) 582 reason = SKB_DROP_REASON_SOCKET_BACKLOG; 583 sk_drops_inc(sk); 584 goto discard_and_relse; 585 } 586 587 bh_unlock_sock(sk); 588 out: 589 if (refcounted) 590 sock_put(sk); 591 return rc; 592 discard_and_relse: 593 sk_skb_reason_drop(sk, skb, reason); 594 goto out; 595 } 596 EXPORT_SYMBOL(__sk_receive_skb); 597 598 INDIRECT_CALLABLE_DECLARE(struct dst_entry *ip6_dst_check(struct dst_entry *, 599 u32)); 600 INDIRECT_CALLABLE_DECLARE(struct dst_entry *ipv4_dst_check(struct dst_entry *, 601 u32)); 602 struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie) 603 { 604 struct dst_entry *dst = __sk_dst_get(sk); 605 606 if (dst && READ_ONCE(dst->obsolete) && 607 INDIRECT_CALL_INET(dst->ops->check, ip6_dst_check, ipv4_dst_check, 608 dst, cookie) == NULL) { 609 sk_tx_queue_clear(sk); 610 WRITE_ONCE(sk->sk_dst_pending_confirm, 0); 611 RCU_INIT_POINTER(sk->sk_dst_cache, NULL); 612 dst_release(dst); 613 return NULL; 614 } 615 616 return dst; 617 } 618 EXPORT_SYMBOL(__sk_dst_check); 619 620 struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie) 621 { 622 struct dst_entry *dst = sk_dst_get(sk); 623 624 if (dst && READ_ONCE(dst->obsolete) && 625 INDIRECT_CALL_INET(dst->ops->check, ip6_dst_check, ipv4_dst_check, 626 dst, cookie) == NULL) { 627 sk_dst_reset(sk); 628 dst_release(dst); 629 return NULL; 630 } 631 632 return dst; 633 } 634 EXPORT_SYMBOL(sk_dst_check); 635 636 static int sock_bindtoindex_locked(struct sock *sk, int ifindex) 637 { 638 int ret = -ENOPROTOOPT; 639 #ifdef CONFIG_NETDEVICES 640 struct net *net = sock_net(sk); 641 642 /* Sorry... */ 643 ret = -EPERM; 644 if (sk->sk_bound_dev_if && !ns_capable(net->user_ns, CAP_NET_RAW)) 645 goto out; 646 647 ret = -EINVAL; 648 if (ifindex < 0) 649 goto out; 650 651 /* Paired with all READ_ONCE() done locklessly. */ 652 WRITE_ONCE(sk->sk_bound_dev_if, ifindex); 653 654 if (sk->sk_prot->rehash) 655 sk->sk_prot->rehash(sk); 656 sk_dst_reset(sk); 657 658 ret = 0; 659 660 out: 661 #endif 662 663 return ret; 664 } 665 666 int sock_bindtoindex(struct sock *sk, int ifindex, bool lock_sk) 667 { 668 int ret; 669 670 if (lock_sk) 671 lock_sock(sk); 672 ret = sock_bindtoindex_locked(sk, ifindex); 673 if (lock_sk) 674 release_sock(sk); 675 676 return ret; 677 } 678 EXPORT_SYMBOL(sock_bindtoindex); 679 680 static int sock_setbindtodevice(struct sock *sk, sockptr_t optval, int optlen) 681 { 682 int ret = -ENOPROTOOPT; 683 #ifdef CONFIG_NETDEVICES 684 struct net *net = sock_net(sk); 685 char devname[IFNAMSIZ]; 686 int index; 687 688 ret = -EINVAL; 689 if (optlen < 0) 690 goto out; 691 692 /* Bind this socket to a particular device like "eth0", 693 * as specified in the passed interface name. If the 694 * name is "" or the option length is zero the socket 695 * is not bound. 696 */ 697 if (optlen > IFNAMSIZ - 1) 698 optlen = IFNAMSIZ - 1; 699 memset(devname, 0, sizeof(devname)); 700 701 ret = -EFAULT; 702 if (copy_from_sockptr(devname, optval, optlen)) 703 goto out; 704 705 index = 0; 706 if (devname[0] != '\0') { 707 struct net_device *dev; 708 709 rcu_read_lock(); 710 dev = dev_get_by_name_rcu(net, devname); 711 if (dev) 712 index = dev->ifindex; 713 rcu_read_unlock(); 714 ret = -ENODEV; 715 if (!dev) 716 goto out; 717 } 718 719 sockopt_lock_sock(sk); 720 ret = sock_bindtoindex_locked(sk, index); 721 sockopt_release_sock(sk); 722 out: 723 #endif 724 725 return ret; 726 } 727 728 static int sock_getbindtodevice(struct sock *sk, sockptr_t optval, 729 sockptr_t optlen, int len) 730 { 731 int ret = -ENOPROTOOPT; 732 #ifdef CONFIG_NETDEVICES 733 int bound_dev_if = READ_ONCE(sk->sk_bound_dev_if); 734 struct net *net = sock_net(sk); 735 char devname[IFNAMSIZ]; 736 737 if (bound_dev_if == 0) { 738 len = 0; 739 goto zero; 740 } 741 742 ret = -EINVAL; 743 if (len < IFNAMSIZ) 744 goto out; 745 746 ret = netdev_get_name(net, devname, bound_dev_if); 747 if (ret) 748 goto out; 749 750 len = strlen(devname) + 1; 751 752 ret = -EFAULT; 753 if (copy_to_sockptr(optval, devname, len)) 754 goto out; 755 756 zero: 757 ret = -EFAULT; 758 if (copy_to_sockptr(optlen, &len, sizeof(int))) 759 goto out; 760 761 ret = 0; 762 763 out: 764 #endif 765 766 return ret; 767 } 768 769 bool sk_mc_loop(const struct sock *sk) 770 { 771 if (dev_recursion_level()) 772 return false; 773 sk = sk_const_to_full_sk(sk); 774 if (!sk) 775 return true; 776 777 switch (READ_ONCE(sk->sk_family)) { 778 case AF_INET: 779 return inet_test_bit(MC_LOOP, sk); 780 #if IS_ENABLED(CONFIG_IPV6) 781 case AF_INET6: 782 return inet6_test_bit(MC6_LOOP, sk); 783 #endif 784 } 785 return true; 786 } 787 EXPORT_SYMBOL(sk_mc_loop); 788 789 void sock_set_reuseaddr(struct sock *sk) 790 { 791 lock_sock(sk); 792 sk->sk_reuse = SK_CAN_REUSE; 793 release_sock(sk); 794 } 795 EXPORT_SYMBOL(sock_set_reuseaddr); 796 797 void sock_set_reuseport(struct sock *sk) 798 { 799 lock_sock(sk); 800 sk->sk_reuseport = true; 801 release_sock(sk); 802 } 803 EXPORT_SYMBOL(sock_set_reuseport); 804 805 void sock_no_linger(struct sock *sk) 806 { 807 lock_sock(sk); 808 WRITE_ONCE(sk->sk_lingertime, 0); 809 sock_set_flag(sk, SOCK_LINGER); 810 release_sock(sk); 811 } 812 EXPORT_SYMBOL(sock_no_linger); 813 814 void sock_set_priority(struct sock *sk, u32 priority) 815 { 816 WRITE_ONCE(sk->sk_priority, priority); 817 } 818 EXPORT_SYMBOL(sock_set_priority); 819 820 void sock_set_sndtimeo(struct sock *sk, s64 secs) 821 { 822 if (secs && secs < MAX_SCHEDULE_TIMEOUT / HZ - 1) 823 WRITE_ONCE(sk->sk_sndtimeo, secs * HZ); 824 else 825 WRITE_ONCE(sk->sk_sndtimeo, MAX_SCHEDULE_TIMEOUT); 826 } 827 EXPORT_SYMBOL(sock_set_sndtimeo); 828 829 static void __sock_set_timestamps(struct sock *sk, bool val, bool new, bool ns) 830 { 831 sock_valbool_flag(sk, SOCK_RCVTSTAMP, val); 832 sock_valbool_flag(sk, SOCK_RCVTSTAMPNS, val && ns); 833 if (val) { 834 sock_valbool_flag(sk, SOCK_TSTAMP_NEW, new); 835 sock_enable_timestamp(sk, SOCK_TIMESTAMP); 836 } 837 } 838 839 void sock_set_timestamp(struct sock *sk, int optname, bool valbool) 840 { 841 switch (optname) { 842 case SO_TIMESTAMP_OLD: 843 __sock_set_timestamps(sk, valbool, false, false); 844 break; 845 case SO_TIMESTAMP_NEW: 846 __sock_set_timestamps(sk, valbool, true, false); 847 break; 848 case SO_TIMESTAMPNS_OLD: 849 __sock_set_timestamps(sk, valbool, false, true); 850 break; 851 case SO_TIMESTAMPNS_NEW: 852 __sock_set_timestamps(sk, valbool, true, true); 853 break; 854 } 855 } 856 857 static int sock_timestamping_bind_phc(struct sock *sk, int phc_index) 858 { 859 struct net *net = sock_net(sk); 860 struct net_device *dev = NULL; 861 bool match = false; 862 int *vclock_index; 863 int i, num; 864 865 if (sk->sk_bound_dev_if) 866 dev = dev_get_by_index(net, sk->sk_bound_dev_if); 867 868 if (!dev) { 869 pr_err("%s: sock not bind to device\n", __func__); 870 return -EOPNOTSUPP; 871 } 872 873 num = ethtool_get_phc_vclocks(dev, &vclock_index); 874 dev_put(dev); 875 876 for (i = 0; i < num; i++) { 877 if (*(vclock_index + i) == phc_index) { 878 match = true; 879 break; 880 } 881 } 882 883 if (num > 0) 884 kfree(vclock_index); 885 886 if (!match) 887 return -EINVAL; 888 889 WRITE_ONCE(sk->sk_bind_phc, phc_index); 890 891 return 0; 892 } 893 894 int sock_set_timestamping(struct sock *sk, int optname, 895 struct so_timestamping timestamping) 896 { 897 int val = timestamping.flags; 898 int ret; 899 900 if (val & ~SOF_TIMESTAMPING_MASK) 901 return -EINVAL; 902 903 if (val & SOF_TIMESTAMPING_OPT_ID_TCP && 904 !(val & SOF_TIMESTAMPING_OPT_ID)) 905 return -EINVAL; 906 907 if (val & SOF_TIMESTAMPING_OPT_ID && 908 !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) { 909 if (sk_is_tcp(sk)) { 910 if ((1 << sk->sk_state) & 911 (TCPF_CLOSE | TCPF_LISTEN)) 912 return -EINVAL; 913 if (val & SOF_TIMESTAMPING_OPT_ID_TCP) 914 atomic_set(&sk->sk_tskey, tcp_sk(sk)->write_seq); 915 else 916 atomic_set(&sk->sk_tskey, tcp_sk(sk)->snd_una); 917 } else { 918 atomic_set(&sk->sk_tskey, 0); 919 } 920 } 921 922 if (val & SOF_TIMESTAMPING_OPT_STATS && 923 !(val & SOF_TIMESTAMPING_OPT_TSONLY)) 924 return -EINVAL; 925 926 if (val & SOF_TIMESTAMPING_BIND_PHC) { 927 ret = sock_timestamping_bind_phc(sk, timestamping.bind_phc); 928 if (ret) 929 return ret; 930 } 931 932 WRITE_ONCE(sk->sk_tsflags, val); 933 sock_valbool_flag(sk, SOCK_TSTAMP_NEW, optname == SO_TIMESTAMPING_NEW); 934 sock_valbool_flag(sk, SOCK_TIMESTAMPING_ANY, !!(val & TSFLAGS_ANY)); 935 936 if (val & SOF_TIMESTAMPING_RX_SOFTWARE) 937 sock_enable_timestamp(sk, 938 SOCK_TIMESTAMPING_RX_SOFTWARE); 939 else 940 sock_disable_timestamp(sk, 941 (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); 942 return 0; 943 } 944 945 #if defined(CONFIG_CGROUP_BPF) 946 void bpf_skops_tx_timestamping(struct sock *sk, struct sk_buff *skb, int op) 947 { 948 struct bpf_sock_ops_kern sock_ops; 949 950 memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp)); 951 sock_ops.op = op; 952 sock_ops.is_fullsock = 1; 953 sock_ops.sk = sk; 954 bpf_skops_init_skb(&sock_ops, skb, 0); 955 __cgroup_bpf_run_filter_sock_ops(sk, &sock_ops, CGROUP_SOCK_OPS); 956 } 957 #endif 958 959 void sock_set_keepalive(struct sock *sk) 960 { 961 lock_sock(sk); 962 if (sk->sk_prot->keepalive) 963 sk->sk_prot->keepalive(sk, true); 964 sock_valbool_flag(sk, SOCK_KEEPOPEN, true); 965 release_sock(sk); 966 } 967 EXPORT_SYMBOL(sock_set_keepalive); 968 969 static void __sock_set_rcvbuf(struct sock *sk, int val) 970 { 971 struct socket *sock = sk->sk_socket; 972 973 /* Ensure val * 2 fits into an int, to prevent max_t() from treating it 974 * as a negative value. 975 */ 976 val = min_t(int, val, INT_MAX / 2); 977 sk->sk_userlocks |= SOCK_RCVBUF_LOCK; 978 979 /* We double it on the way in to account for "struct sk_buff" etc. 980 * overhead. Applications assume that the SO_RCVBUF setting they make 981 * will allow that much actual data to be received on that socket. 982 * 983 * Applications are unaware that "struct sk_buff" and other overheads 984 * allocate from the receive buffer during socket buffer allocation. 985 * 986 * And after considering the possible alternatives, returning the value 987 * we actually used in getsockopt is the most desirable behavior. 988 */ 989 WRITE_ONCE(sk->sk_rcvbuf, max_t(int, val * 2, SOCK_MIN_RCVBUF)); 990 991 if (sock) { 992 const struct proto_ops *ops = READ_ONCE(sock->ops); 993 994 if (ops->set_rcvbuf) 995 ops->set_rcvbuf(sk, sk->sk_rcvbuf); 996 } 997 } 998 999 void sock_set_rcvbuf(struct sock *sk, int val) 1000 { 1001 lock_sock(sk); 1002 __sock_set_rcvbuf(sk, val); 1003 release_sock(sk); 1004 } 1005 EXPORT_SYMBOL(sock_set_rcvbuf); 1006 1007 static void __sock_set_mark(struct sock *sk, u32 val) 1008 { 1009 if (val != sk->sk_mark) { 1010 WRITE_ONCE(sk->sk_mark, val); 1011 sk_dst_reset(sk); 1012 } 1013 } 1014 1015 void sock_set_mark(struct sock *sk, u32 val) 1016 { 1017 lock_sock(sk); 1018 __sock_set_mark(sk, val); 1019 release_sock(sk); 1020 } 1021 EXPORT_SYMBOL(sock_set_mark); 1022 1023 static void sock_release_reserved_memory(struct sock *sk, int bytes) 1024 { 1025 /* Round down bytes to multiple of pages */ 1026 bytes = round_down(bytes, PAGE_SIZE); 1027 1028 WARN_ON(bytes > sk->sk_reserved_mem); 1029 WRITE_ONCE(sk->sk_reserved_mem, sk->sk_reserved_mem - bytes); 1030 sk_mem_reclaim(sk); 1031 } 1032 1033 static int sock_reserve_memory(struct sock *sk, int bytes) 1034 { 1035 long allocated; 1036 bool charged; 1037 int pages; 1038 1039 if (!mem_cgroup_sk_enabled(sk) || !sk_is_tcp(sk)) 1040 return -EOPNOTSUPP; 1041 1042 if (!bytes) 1043 return 0; 1044 1045 pages = sk_mem_pages(bytes); 1046 1047 /* pre-charge to memcg */ 1048 charged = mem_cgroup_sk_charge(sk, pages, 1049 GFP_KERNEL | __GFP_RETRY_MAYFAIL); 1050 if (!charged) 1051 return -ENOMEM; 1052 1053 if (sk->sk_bypass_prot_mem) 1054 goto success; 1055 1056 /* pre-charge to forward_alloc */ 1057 sk_memory_allocated_add(sk, pages); 1058 allocated = sk_memory_allocated(sk); 1059 1060 /* If the system goes into memory pressure with this 1061 * precharge, give up and return error. 1062 */ 1063 if (allocated > sk_prot_mem_limits(sk, 1)) { 1064 sk_memory_allocated_sub(sk, pages); 1065 mem_cgroup_sk_uncharge(sk, pages); 1066 return -ENOMEM; 1067 } 1068 1069 success: 1070 sk_forward_alloc_add(sk, pages << PAGE_SHIFT); 1071 1072 WRITE_ONCE(sk->sk_reserved_mem, 1073 sk->sk_reserved_mem + (pages << PAGE_SHIFT)); 1074 1075 return 0; 1076 } 1077 1078 #ifdef CONFIG_PAGE_POOL 1079 1080 /* This is the number of tokens and frags that the user can SO_DEVMEM_DONTNEED 1081 * in 1 syscall. The limit exists to limit the amount of memory the kernel 1082 * allocates to copy these tokens, and to prevent looping over the frags for 1083 * too long. 1084 */ 1085 #define MAX_DONTNEED_TOKENS 128 1086 #define MAX_DONTNEED_FRAGS 1024 1087 1088 static noinline_for_stack int 1089 sock_devmem_dontneed(struct sock *sk, sockptr_t optval, unsigned int optlen) 1090 { 1091 unsigned int num_tokens, i, j, netmem_num = 0; 1092 struct dmabuf_token *tokens; 1093 int ret = 0, num_frags = 0; 1094 netmem_ref netmems[16]; 1095 1096 if (!sk_is_tcp(sk)) 1097 return -EBADF; 1098 1099 if (optlen % sizeof(*tokens) || 1100 optlen > sizeof(*tokens) * MAX_DONTNEED_TOKENS) 1101 return -EINVAL; 1102 1103 num_tokens = optlen / sizeof(*tokens); 1104 tokens = kvmalloc_objs(*tokens, num_tokens); 1105 if (!tokens) 1106 return -ENOMEM; 1107 1108 if (copy_from_sockptr(tokens, optval, optlen)) { 1109 kvfree(tokens); 1110 return -EFAULT; 1111 } 1112 1113 xa_lock_bh(&sk->sk_user_frags); 1114 for (i = 0; i < num_tokens; i++) { 1115 for (j = 0; j < tokens[i].token_count; j++) { 1116 if (++num_frags > MAX_DONTNEED_FRAGS) 1117 goto frag_limit_reached; 1118 1119 netmem_ref netmem = (__force netmem_ref)__xa_erase( 1120 &sk->sk_user_frags, tokens[i].token_start + j); 1121 1122 if (!netmem || WARN_ON_ONCE(!netmem_is_net_iov(netmem))) 1123 continue; 1124 1125 netmems[netmem_num++] = netmem; 1126 if (netmem_num == ARRAY_SIZE(netmems)) { 1127 xa_unlock_bh(&sk->sk_user_frags); 1128 page_pool_put_netmem_bulk(netmems, 1129 ARRAY_SIZE(netmems)); 1130 netmem_num = 0; 1131 xa_lock_bh(&sk->sk_user_frags); 1132 } 1133 ret++; 1134 } 1135 } 1136 1137 frag_limit_reached: 1138 xa_unlock_bh(&sk->sk_user_frags); 1139 page_pool_put_netmem_bulk(netmems, netmem_num); 1140 1141 kvfree(tokens); 1142 return ret; 1143 } 1144 #endif 1145 1146 void sockopt_lock_sock(struct sock *sk) 1147 { 1148 /* When current->bpf_ctx is set, the setsockopt is called from 1149 * a bpf prog. bpf has ensured the sk lock has been 1150 * acquired before calling setsockopt(). 1151 */ 1152 if (has_current_bpf_ctx()) 1153 return; 1154 1155 lock_sock(sk); 1156 } 1157 EXPORT_SYMBOL(sockopt_lock_sock); 1158 1159 void sockopt_release_sock(struct sock *sk) 1160 { 1161 if (has_current_bpf_ctx()) 1162 return; 1163 1164 release_sock(sk); 1165 } 1166 EXPORT_SYMBOL(sockopt_release_sock); 1167 1168 bool sockopt_ns_capable(struct user_namespace *ns, int cap) 1169 { 1170 return has_current_bpf_ctx() || ns_capable(ns, cap); 1171 } 1172 EXPORT_SYMBOL(sockopt_ns_capable); 1173 1174 bool sockopt_capable(int cap) 1175 { 1176 return has_current_bpf_ctx() || capable(cap); 1177 } 1178 EXPORT_SYMBOL(sockopt_capable); 1179 1180 static int sockopt_validate_clockid(__kernel_clockid_t value) 1181 { 1182 switch (value) { 1183 case CLOCK_REALTIME: 1184 case CLOCK_MONOTONIC: 1185 case CLOCK_TAI: 1186 return 0; 1187 } 1188 return -EINVAL; 1189 } 1190 1191 /* 1192 * This is meant for all protocols to use and covers goings on 1193 * at the socket level. Everything here is generic. 1194 */ 1195 1196 int sk_setsockopt(struct sock *sk, int level, int optname, 1197 sockptr_t optval, unsigned int optlen) 1198 { 1199 struct so_timestamping timestamping; 1200 struct socket *sock = sk->sk_socket; 1201 struct sock_txtime sk_txtime; 1202 int val; 1203 int valbool; 1204 struct linger ling; 1205 int ret = 0; 1206 1207 /* 1208 * Options without arguments 1209 */ 1210 1211 if (optname == SO_BINDTODEVICE) 1212 return sock_setbindtodevice(sk, optval, optlen); 1213 1214 if (optlen < sizeof(int)) 1215 return -EINVAL; 1216 1217 if (copy_from_sockptr(&val, optval, sizeof(val))) 1218 return -EFAULT; 1219 1220 valbool = val ? 1 : 0; 1221 1222 /* handle options which do not require locking the socket. */ 1223 switch (optname) { 1224 case SO_PRIORITY: 1225 if (sk_set_prio_allowed(sk, val)) { 1226 sock_set_priority(sk, val); 1227 return 0; 1228 } 1229 return -EPERM; 1230 case SO_TYPE: 1231 case SO_PROTOCOL: 1232 case SO_DOMAIN: 1233 case SO_ERROR: 1234 return -ENOPROTOOPT; 1235 #ifdef CONFIG_NET_RX_BUSY_POLL 1236 case SO_BUSY_POLL: 1237 if (val < 0) 1238 return -EINVAL; 1239 WRITE_ONCE(sk->sk_ll_usec, val); 1240 return 0; 1241 case SO_PREFER_BUSY_POLL: 1242 if (valbool && !sockopt_capable(CAP_NET_ADMIN)) 1243 return -EPERM; 1244 WRITE_ONCE(sk->sk_prefer_busy_poll, valbool); 1245 return 0; 1246 case SO_BUSY_POLL_BUDGET: 1247 if (val > READ_ONCE(sk->sk_busy_poll_budget) && 1248 !sockopt_capable(CAP_NET_ADMIN)) 1249 return -EPERM; 1250 if (val < 0 || val > U16_MAX) 1251 return -EINVAL; 1252 WRITE_ONCE(sk->sk_busy_poll_budget, val); 1253 return 0; 1254 #endif 1255 case SO_MAX_PACING_RATE: 1256 { 1257 unsigned long ulval = (val == ~0U) ? ~0UL : (unsigned int)val; 1258 unsigned long pacing_rate; 1259 1260 if (sizeof(ulval) != sizeof(val) && 1261 optlen >= sizeof(ulval) && 1262 copy_from_sockptr(&ulval, optval, sizeof(ulval))) { 1263 return -EFAULT; 1264 } 1265 if (ulval != ~0UL) 1266 cmpxchg(&sk->sk_pacing_status, 1267 SK_PACING_NONE, 1268 SK_PACING_NEEDED); 1269 /* Pairs with READ_ONCE() from sk_getsockopt() */ 1270 WRITE_ONCE(sk->sk_max_pacing_rate, ulval); 1271 pacing_rate = READ_ONCE(sk->sk_pacing_rate); 1272 if (ulval < pacing_rate) 1273 WRITE_ONCE(sk->sk_pacing_rate, ulval); 1274 return 0; 1275 } 1276 case SO_TXREHASH: 1277 if (!sk_is_tcp(sk)) 1278 return -EOPNOTSUPP; 1279 if (val < -1 || val > 1) 1280 return -EINVAL; 1281 if ((u8)val == SOCK_TXREHASH_DEFAULT) 1282 val = READ_ONCE(sock_net(sk)->core.sysctl_txrehash); 1283 /* Paired with READ_ONCE() in tcp_rtx_synack() 1284 * and sk_getsockopt(). 1285 */ 1286 WRITE_ONCE(sk->sk_txrehash, (u8)val); 1287 return 0; 1288 case SO_PEEK_OFF: 1289 { 1290 int (*set_peek_off)(struct sock *sk, int val); 1291 1292 set_peek_off = READ_ONCE(sock->ops)->set_peek_off; 1293 if (set_peek_off) 1294 ret = set_peek_off(sk, val); 1295 else 1296 ret = -EOPNOTSUPP; 1297 return ret; 1298 } 1299 #ifdef CONFIG_PAGE_POOL 1300 case SO_DEVMEM_DONTNEED: 1301 return sock_devmem_dontneed(sk, optval, optlen); 1302 #endif 1303 case SO_SNDTIMEO_OLD: 1304 case SO_SNDTIMEO_NEW: 1305 return sock_set_timeout(&sk->sk_sndtimeo, optval, 1306 optlen, optname == SO_SNDTIMEO_OLD); 1307 case SO_RCVTIMEO_OLD: 1308 case SO_RCVTIMEO_NEW: 1309 return sock_set_timeout(&sk->sk_rcvtimeo, optval, 1310 optlen, optname == SO_RCVTIMEO_OLD); 1311 } 1312 1313 sockopt_lock_sock(sk); 1314 1315 switch (optname) { 1316 case SO_DEBUG: 1317 if (val && !sockopt_capable(CAP_NET_ADMIN)) 1318 ret = -EACCES; 1319 else 1320 sock_valbool_flag(sk, SOCK_DBG, valbool); 1321 break; 1322 case SO_REUSEADDR: 1323 sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); 1324 break; 1325 case SO_REUSEPORT: 1326 if (valbool && !sk_is_inet(sk)) 1327 ret = -EOPNOTSUPP; 1328 else 1329 sk->sk_reuseport = valbool; 1330 break; 1331 case SO_DONTROUTE: 1332 sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); 1333 sk_dst_reset(sk); 1334 break; 1335 case SO_BROADCAST: 1336 sock_valbool_flag(sk, SOCK_BROADCAST, valbool); 1337 break; 1338 case SO_SNDBUF: 1339 /* Don't error on this BSD doesn't and if you think 1340 * about it this is right. Otherwise apps have to 1341 * play 'guess the biggest size' games. RCVBUF/SNDBUF 1342 * are treated in BSD as hints 1343 */ 1344 val = min_t(u32, val, READ_ONCE(sysctl_wmem_max)); 1345 set_sndbuf: 1346 /* Ensure val * 2 fits into an int, to prevent max_t() 1347 * from treating it as a negative value. 1348 */ 1349 val = min_t(int, val, INT_MAX / 2); 1350 sk->sk_userlocks |= SOCK_SNDBUF_LOCK; 1351 WRITE_ONCE(sk->sk_sndbuf, 1352 max_t(int, val * 2, SOCK_MIN_SNDBUF)); 1353 /* Wake up sending tasks if we upped the value. */ 1354 sk->sk_write_space(sk); 1355 break; 1356 1357 case SO_SNDBUFFORCE: 1358 if (!sockopt_capable(CAP_NET_ADMIN)) { 1359 ret = -EPERM; 1360 break; 1361 } 1362 1363 /* No negative values (to prevent underflow, as val will be 1364 * multiplied by 2). 1365 */ 1366 if (val < 0) 1367 val = 0; 1368 goto set_sndbuf; 1369 1370 case SO_RCVBUF: 1371 /* Don't error on this BSD doesn't and if you think 1372 * about it this is right. Otherwise apps have to 1373 * play 'guess the biggest size' games. RCVBUF/SNDBUF 1374 * are treated in BSD as hints 1375 */ 1376 __sock_set_rcvbuf(sk, min_t(u32, val, READ_ONCE(sysctl_rmem_max))); 1377 break; 1378 1379 case SO_RCVBUFFORCE: 1380 if (!sockopt_capable(CAP_NET_ADMIN)) { 1381 ret = -EPERM; 1382 break; 1383 } 1384 1385 /* No negative values (to prevent underflow, as val will be 1386 * multiplied by 2). 1387 */ 1388 __sock_set_rcvbuf(sk, max(val, 0)); 1389 break; 1390 1391 case SO_KEEPALIVE: 1392 if (sk->sk_prot->keepalive) 1393 sk->sk_prot->keepalive(sk, valbool); 1394 sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); 1395 break; 1396 1397 case SO_OOBINLINE: 1398 sock_valbool_flag(sk, SOCK_URGINLINE, valbool); 1399 break; 1400 1401 case SO_NO_CHECK: 1402 sk->sk_no_check_tx = valbool; 1403 break; 1404 1405 case SO_LINGER: 1406 if (optlen < sizeof(ling)) { 1407 ret = -EINVAL; /* 1003.1g */ 1408 break; 1409 } 1410 if (copy_from_sockptr(&ling, optval, sizeof(ling))) { 1411 ret = -EFAULT; 1412 break; 1413 } 1414 if (!ling.l_onoff) { 1415 sock_reset_flag(sk, SOCK_LINGER); 1416 } else { 1417 unsigned long t_sec = ling.l_linger; 1418 1419 if (t_sec >= MAX_SCHEDULE_TIMEOUT / HZ) 1420 WRITE_ONCE(sk->sk_lingertime, MAX_SCHEDULE_TIMEOUT); 1421 else 1422 WRITE_ONCE(sk->sk_lingertime, t_sec * HZ); 1423 sock_set_flag(sk, SOCK_LINGER); 1424 } 1425 break; 1426 1427 case SO_BSDCOMPAT: 1428 break; 1429 1430 case SO_TIMESTAMP_OLD: 1431 case SO_TIMESTAMP_NEW: 1432 case SO_TIMESTAMPNS_OLD: 1433 case SO_TIMESTAMPNS_NEW: 1434 sock_set_timestamp(sk, optname, valbool); 1435 break; 1436 1437 case SO_TIMESTAMPING_NEW: 1438 case SO_TIMESTAMPING_OLD: 1439 if (optlen == sizeof(timestamping)) { 1440 if (copy_from_sockptr(×tamping, optval, 1441 sizeof(timestamping))) { 1442 ret = -EFAULT; 1443 break; 1444 } 1445 } else { 1446 memset(×tamping, 0, sizeof(timestamping)); 1447 timestamping.flags = val; 1448 } 1449 ret = sock_set_timestamping(sk, optname, timestamping); 1450 break; 1451 1452 case SO_RCVLOWAT: 1453 { 1454 int (*set_rcvlowat)(struct sock *sk, int val) = NULL; 1455 1456 if (val < 0) 1457 val = INT_MAX; 1458 if (sock) 1459 set_rcvlowat = READ_ONCE(sock->ops)->set_rcvlowat; 1460 if (set_rcvlowat) 1461 ret = set_rcvlowat(sk, val); 1462 else 1463 WRITE_ONCE(sk->sk_rcvlowat, val ? : 1); 1464 break; 1465 } 1466 case SO_ATTACH_FILTER: { 1467 struct sock_fprog fprog; 1468 1469 if (sk_is_tcp(sk) && 1470 !sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) { 1471 ret = -EPERM; 1472 break; 1473 } 1474 ret = copy_bpf_fprog_from_user(&fprog, optval, optlen); 1475 if (!ret) 1476 ret = sk_attach_filter(&fprog, sk); 1477 break; 1478 } 1479 case SO_ATTACH_BPF: 1480 ret = -EINVAL; 1481 if (optlen == sizeof(u32)) { 1482 u32 ufd; 1483 1484 ret = -EFAULT; 1485 if (copy_from_sockptr(&ufd, optval, sizeof(ufd))) 1486 break; 1487 1488 ret = sk_attach_bpf(ufd, sk); 1489 } 1490 break; 1491 1492 case SO_ATTACH_REUSEPORT_CBPF: { 1493 struct sock_fprog fprog; 1494 1495 ret = copy_bpf_fprog_from_user(&fprog, optval, optlen); 1496 if (!ret) 1497 ret = sk_reuseport_attach_filter(&fprog, sk); 1498 break; 1499 } 1500 case SO_ATTACH_REUSEPORT_EBPF: 1501 ret = -EINVAL; 1502 if (optlen == sizeof(u32)) { 1503 u32 ufd; 1504 1505 ret = -EFAULT; 1506 if (copy_from_sockptr(&ufd, optval, sizeof(ufd))) 1507 break; 1508 1509 ret = sk_reuseport_attach_bpf(ufd, sk); 1510 } 1511 break; 1512 1513 case SO_DETACH_REUSEPORT_BPF: 1514 ret = reuseport_detach_prog(sk); 1515 break; 1516 1517 case SO_DETACH_FILTER: 1518 ret = sk_detach_filter(sk); 1519 break; 1520 1521 case SO_LOCK_FILTER: 1522 if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool) 1523 ret = -EPERM; 1524 else 1525 sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool); 1526 break; 1527 1528 case SO_MARK: 1529 if (!sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_RAW) && 1530 !sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) { 1531 ret = -EPERM; 1532 break; 1533 } 1534 1535 __sock_set_mark(sk, val); 1536 break; 1537 case SO_RCVMARK: 1538 sock_valbool_flag(sk, SOCK_RCVMARK, valbool); 1539 break; 1540 1541 case SO_RCVPRIORITY: 1542 sock_valbool_flag(sk, SOCK_RCVPRIORITY, valbool); 1543 break; 1544 1545 case SO_RXQ_OVFL: 1546 sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); 1547 break; 1548 1549 case SO_WIFI_STATUS: 1550 sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); 1551 break; 1552 1553 case SO_NOFCS: 1554 sock_valbool_flag(sk, SOCK_NOFCS, valbool); 1555 break; 1556 1557 case SO_SELECT_ERR_QUEUE: 1558 sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool); 1559 break; 1560 1561 case SO_PASSCRED: 1562 if (sk_may_scm_recv(sk)) 1563 sk->sk_scm_credentials = valbool; 1564 else 1565 ret = -EOPNOTSUPP; 1566 break; 1567 1568 case SO_PASSSEC: 1569 if (IS_ENABLED(CONFIG_SECURITY_NETWORK) && sk_may_scm_recv(sk)) 1570 sk->sk_scm_security = valbool; 1571 else 1572 ret = -EOPNOTSUPP; 1573 break; 1574 1575 case SO_PASSPIDFD: 1576 if (sk_is_unix(sk)) 1577 sk->sk_scm_pidfd = valbool; 1578 else 1579 ret = -EOPNOTSUPP; 1580 break; 1581 1582 case SO_PASSPIDFD_THREAD: 1583 if (sk_is_unix(sk)) 1584 sk->sk_scm_pidfd_thread = valbool; 1585 else 1586 ret = -EOPNOTSUPP; 1587 break; 1588 1589 case SO_PASSRIGHTS: 1590 if (sk_is_unix(sk)) 1591 sk->sk_scm_rights = valbool; 1592 else 1593 ret = -EOPNOTSUPP; 1594 break; 1595 1596 case SO_INCOMING_CPU: 1597 reuseport_update_incoming_cpu(sk, val); 1598 break; 1599 1600 case SO_CNX_ADVICE: 1601 if (val == 1) 1602 dst_negative_advice(sk); 1603 break; 1604 1605 case SO_ZEROCOPY: 1606 if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6) { 1607 if (!(sk_is_tcp(sk) || 1608 (sk->sk_type == SOCK_DGRAM && 1609 sk->sk_protocol == IPPROTO_UDP))) 1610 ret = -EOPNOTSUPP; 1611 } else if (sk->sk_family != PF_RDS) { 1612 ret = -EOPNOTSUPP; 1613 } 1614 if (!ret) { 1615 if (val < 0 || val > 1) 1616 ret = -EINVAL; 1617 else 1618 sock_valbool_flag(sk, SOCK_ZEROCOPY, valbool); 1619 } 1620 break; 1621 1622 case SO_TXTIME: 1623 if (optlen != sizeof(struct sock_txtime)) { 1624 ret = -EINVAL; 1625 break; 1626 } else if (copy_from_sockptr(&sk_txtime, optval, 1627 sizeof(struct sock_txtime))) { 1628 ret = -EFAULT; 1629 break; 1630 } else if (sk_txtime.flags & ~SOF_TXTIME_FLAGS_MASK) { 1631 ret = -EINVAL; 1632 break; 1633 } 1634 /* CLOCK_MONOTONIC is only used by sch_fq, and this packet 1635 * scheduler has enough safe guards. 1636 */ 1637 if (sk_txtime.clockid != CLOCK_MONOTONIC && 1638 !sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) { 1639 ret = -EPERM; 1640 break; 1641 } 1642 1643 ret = sockopt_validate_clockid(sk_txtime.clockid); 1644 if (ret) 1645 break; 1646 1647 sock_valbool_flag(sk, SOCK_TXTIME, true); 1648 sk->sk_clockid = sk_txtime.clockid; 1649 sk->sk_txtime_deadline_mode = 1650 !!(sk_txtime.flags & SOF_TXTIME_DEADLINE_MODE); 1651 sk->sk_txtime_report_errors = 1652 !!(sk_txtime.flags & SOF_TXTIME_REPORT_ERRORS); 1653 break; 1654 1655 case SO_BINDTOIFINDEX: 1656 ret = sock_bindtoindex_locked(sk, val); 1657 break; 1658 1659 case SO_BUF_LOCK: 1660 if (val & ~SOCK_BUF_LOCK_MASK) { 1661 ret = -EINVAL; 1662 break; 1663 } 1664 sk->sk_userlocks = val | (sk->sk_userlocks & 1665 ~SOCK_BUF_LOCK_MASK); 1666 break; 1667 1668 case SO_RESERVE_MEM: 1669 { 1670 int delta; 1671 1672 if (val < 0 || val > SZ_1G) { 1673 ret = -EINVAL; 1674 break; 1675 } 1676 1677 delta = val - sk->sk_reserved_mem; 1678 if (delta < 0) 1679 sock_release_reserved_memory(sk, -delta); 1680 else 1681 ret = sock_reserve_memory(sk, delta); 1682 break; 1683 } 1684 1685 default: 1686 ret = -ENOPROTOOPT; 1687 break; 1688 } 1689 sockopt_release_sock(sk); 1690 return ret; 1691 } 1692 1693 int sock_setsockopt(struct socket *sock, int level, int optname, 1694 sockptr_t optval, unsigned int optlen) 1695 { 1696 return sk_setsockopt(sock->sk, level, optname, 1697 optval, optlen); 1698 } 1699 EXPORT_SYMBOL(sock_setsockopt); 1700 1701 static const struct cred *sk_get_peer_cred(struct sock *sk) 1702 { 1703 const struct cred *cred; 1704 1705 spin_lock(&sk->sk_peer_lock); 1706 cred = get_cred(sk->sk_peer_cred); 1707 spin_unlock(&sk->sk_peer_lock); 1708 1709 return cred; 1710 } 1711 1712 static void cred_to_ucred(struct pid *pid, const struct cred *cred, 1713 struct ucred *ucred) 1714 { 1715 ucred->pid = pid_vnr(pid); 1716 ucred->uid = ucred->gid = -1; 1717 if (cred) { 1718 struct user_namespace *current_ns = current_user_ns(); 1719 1720 ucred->uid = from_kuid_munged(current_ns, cred->euid); 1721 ucred->gid = from_kgid_munged(current_ns, cred->egid); 1722 } 1723 } 1724 1725 static int groups_to_user(sockptr_t dst, const struct group_info *src) 1726 { 1727 struct user_namespace *user_ns = current_user_ns(); 1728 int i; 1729 1730 for (i = 0; i < src->ngroups; i++) { 1731 gid_t gid = from_kgid_munged(user_ns, src->gid[i]); 1732 1733 if (copy_to_sockptr_offset(dst, i * sizeof(gid), &gid, sizeof(gid))) 1734 return -EFAULT; 1735 } 1736 1737 return 0; 1738 } 1739 1740 /* Hand out a pidfd for @type of the socket's peer via SO_PEERPIDFD*. */ 1741 static int sk_getsockopt_peerpidfd(struct sock *sk, enum pid_type type, 1742 sockptr_t optval, sockptr_t optlen, int len) 1743 { 1744 struct file *pidfd_file = NULL; 1745 unsigned int flags = 0; 1746 struct pid *peer_pid; 1747 int pidfd; 1748 1749 /* Userspace can't close a pidfd whose number it didn't get. */ 1750 if (len < sizeof(pidfd)) 1751 return -EINVAL; 1752 len = sizeof(pidfd); 1753 1754 spin_lock(&sk->sk_peer_lock); 1755 peer_pid = get_pid(sk->sk_peer_pid[type]); 1756 spin_unlock(&sk->sk_peer_lock); 1757 1758 if (!peer_pid) 1759 return -ENODATA; 1760 1761 /* The use of PIDFD_STALE requires stashing of struct pid on pidfs 1762 * with pidfs_register_pid() and only AF_UNIX is prepared for this. 1763 */ 1764 if (sk_is_unix(sk)) 1765 flags |= PIDFD_STALE; 1766 if (type == PIDTYPE_PID) 1767 flags |= PIDFD_THREAD; 1768 1769 pidfd = pidfd_prepare(peer_pid, flags, &pidfd_file); 1770 put_pid(peer_pid); 1771 if (pidfd < 0) 1772 return pidfd; 1773 1774 if (copy_to_sockptr(optval, &pidfd, len) || 1775 copy_to_sockptr(optlen, &len, sizeof(int))) { 1776 put_unused_fd(pidfd); 1777 fput(pidfd_file); 1778 1779 return -EFAULT; 1780 } 1781 1782 fd_install(pidfd, pidfd_file); 1783 return 0; 1784 } 1785 1786 int sk_getsockopt(struct sock *sk, int level, int optname, 1787 sockptr_t optval, sockptr_t optlen) 1788 { 1789 struct socket *sock = sk->sk_socket; 1790 1791 union { 1792 int val; 1793 u64 val64; 1794 unsigned long ulval; 1795 struct linger ling; 1796 struct old_timeval32 tm32; 1797 struct __kernel_old_timeval tm; 1798 struct __kernel_sock_timeval stm; 1799 struct sock_txtime txtime; 1800 struct so_timestamping timestamping; 1801 } v; 1802 1803 int lv = sizeof(int); 1804 int len; 1805 1806 if (copy_from_sockptr(&len, optlen, sizeof(int))) 1807 return -EFAULT; 1808 if (len < 0) 1809 return -EINVAL; 1810 1811 memset(&v, 0, sizeof(v)); 1812 1813 switch (optname) { 1814 case SO_DEBUG: 1815 v.val = sock_flag(sk, SOCK_DBG); 1816 break; 1817 1818 case SO_DONTROUTE: 1819 v.val = sock_flag(sk, SOCK_LOCALROUTE); 1820 break; 1821 1822 case SO_BROADCAST: 1823 v.val = sock_flag(sk, SOCK_BROADCAST); 1824 break; 1825 1826 case SO_SNDBUF: 1827 v.val = READ_ONCE(sk->sk_sndbuf); 1828 break; 1829 1830 case SO_RCVBUF: 1831 v.val = READ_ONCE(sk->sk_rcvbuf); 1832 break; 1833 1834 case SO_REUSEADDR: 1835 v.val = sk->sk_reuse; 1836 break; 1837 1838 case SO_REUSEPORT: 1839 v.val = sk->sk_reuseport; 1840 break; 1841 1842 case SO_KEEPALIVE: 1843 v.val = sock_flag(sk, SOCK_KEEPOPEN); 1844 break; 1845 1846 case SO_TYPE: 1847 v.val = sk->sk_type; 1848 break; 1849 1850 case SO_PROTOCOL: 1851 v.val = sk->sk_protocol; 1852 break; 1853 1854 case SO_DOMAIN: 1855 v.val = sk->sk_family; 1856 break; 1857 1858 case SO_ERROR: 1859 v.val = -sock_error(sk); 1860 if (v.val == 0) 1861 v.val = xchg(&sk->sk_err_soft, 0); 1862 break; 1863 1864 case SO_OOBINLINE: 1865 v.val = sock_flag(sk, SOCK_URGINLINE); 1866 break; 1867 1868 case SO_NO_CHECK: 1869 v.val = sk->sk_no_check_tx; 1870 break; 1871 1872 case SO_PRIORITY: 1873 v.val = READ_ONCE(sk->sk_priority); 1874 break; 1875 1876 case SO_LINGER: 1877 lv = sizeof(v.ling); 1878 v.ling.l_onoff = sock_flag(sk, SOCK_LINGER); 1879 v.ling.l_linger = READ_ONCE(sk->sk_lingertime) / HZ; 1880 break; 1881 1882 case SO_BSDCOMPAT: 1883 break; 1884 1885 case SO_TIMESTAMP_OLD: 1886 v.val = sock_flag(sk, SOCK_RCVTSTAMP) && 1887 !sock_flag(sk, SOCK_TSTAMP_NEW) && 1888 !sock_flag(sk, SOCK_RCVTSTAMPNS); 1889 break; 1890 1891 case SO_TIMESTAMPNS_OLD: 1892 v.val = sock_flag(sk, SOCK_RCVTSTAMPNS) && !sock_flag(sk, SOCK_TSTAMP_NEW); 1893 break; 1894 1895 case SO_TIMESTAMP_NEW: 1896 v.val = sock_flag(sk, SOCK_RCVTSTAMP) && sock_flag(sk, SOCK_TSTAMP_NEW); 1897 break; 1898 1899 case SO_TIMESTAMPNS_NEW: 1900 v.val = sock_flag(sk, SOCK_RCVTSTAMPNS) && sock_flag(sk, SOCK_TSTAMP_NEW); 1901 break; 1902 1903 case SO_TIMESTAMPING_OLD: 1904 case SO_TIMESTAMPING_NEW: 1905 lv = sizeof(v.timestamping); 1906 /* For the later-added case SO_TIMESTAMPING_NEW: Be strict about only 1907 * returning the flags when they were set through the same option. 1908 * Don't change the beviour for the old case SO_TIMESTAMPING_OLD. 1909 */ 1910 if (optname == SO_TIMESTAMPING_OLD || sock_flag(sk, SOCK_TSTAMP_NEW)) { 1911 v.timestamping.flags = READ_ONCE(sk->sk_tsflags); 1912 v.timestamping.bind_phc = READ_ONCE(sk->sk_bind_phc); 1913 } 1914 break; 1915 1916 case SO_RCVTIMEO_OLD: 1917 case SO_RCVTIMEO_NEW: 1918 lv = sock_get_timeout(READ_ONCE(sk->sk_rcvtimeo), &v, 1919 SO_RCVTIMEO_OLD == optname); 1920 break; 1921 1922 case SO_SNDTIMEO_OLD: 1923 case SO_SNDTIMEO_NEW: 1924 lv = sock_get_timeout(READ_ONCE(sk->sk_sndtimeo), &v, 1925 SO_SNDTIMEO_OLD == optname); 1926 break; 1927 1928 case SO_RCVLOWAT: 1929 v.val = READ_ONCE(sk->sk_rcvlowat); 1930 break; 1931 1932 case SO_SNDLOWAT: 1933 v.val = 1; 1934 break; 1935 1936 case SO_PASSCRED: 1937 if (!sk_may_scm_recv(sk)) 1938 return -EOPNOTSUPP; 1939 1940 v.val = sk->sk_scm_credentials; 1941 break; 1942 1943 case SO_PASSPIDFD: 1944 if (!sk_is_unix(sk)) 1945 return -EOPNOTSUPP; 1946 1947 v.val = sk->sk_scm_pidfd; 1948 break; 1949 1950 case SO_PASSPIDFD_THREAD: 1951 if (!sk_is_unix(sk)) 1952 return -EOPNOTSUPP; 1953 1954 v.val = sk->sk_scm_pidfd_thread; 1955 break; 1956 1957 case SO_PASSRIGHTS: 1958 if (!sk_is_unix(sk)) 1959 return -EOPNOTSUPP; 1960 1961 v.val = sk->sk_scm_rights; 1962 break; 1963 1964 case SO_PEERCRED: 1965 { 1966 struct ucred peercred; 1967 if (len > sizeof(peercred)) 1968 len = sizeof(peercred); 1969 1970 spin_lock(&sk->sk_peer_lock); 1971 cred_to_ucred(sk->sk_peer_pid[PIDTYPE_TGID], sk->sk_peer_cred, 1972 &peercred); 1973 spin_unlock(&sk->sk_peer_lock); 1974 1975 if (copy_to_sockptr(optval, &peercred, len)) 1976 return -EFAULT; 1977 goto lenout; 1978 } 1979 1980 case SO_PEERPIDFD: 1981 return sk_getsockopt_peerpidfd(sk, PIDTYPE_TGID, optval, optlen, len); 1982 1983 case SO_PEERPIDFD_THREAD: 1984 /* Only AF_UNIX records the peer's connecting thread. */ 1985 if (!sk_is_unix(sk)) 1986 return -EOPNOTSUPP; 1987 1988 return sk_getsockopt_peerpidfd(sk, PIDTYPE_PID, optval, optlen, len); 1989 1990 case SO_PEERGROUPS: 1991 { 1992 const struct cred *cred; 1993 int ret, n; 1994 1995 cred = sk_get_peer_cred(sk); 1996 if (!cred) 1997 return -ENODATA; 1998 1999 n = cred->group_info->ngroups; 2000 if (len < n * sizeof(gid_t)) { 2001 len = n * sizeof(gid_t); 2002 put_cred(cred); 2003 return copy_to_sockptr(optlen, &len, sizeof(int)) ? -EFAULT : -ERANGE; 2004 } 2005 len = n * sizeof(gid_t); 2006 2007 ret = groups_to_user(optval, cred->group_info); 2008 put_cred(cred); 2009 if (ret) 2010 return ret; 2011 goto lenout; 2012 } 2013 2014 case SO_PEERNAME: 2015 { 2016 struct sockaddr_storage address; 2017 2018 lv = READ_ONCE(sock->ops)->getname(sock, (struct sockaddr *)&address, 2); 2019 if (lv < 0) 2020 return -ENOTCONN; 2021 if (lv < len) 2022 return -EINVAL; 2023 if (copy_to_sockptr(optval, &address, len)) 2024 return -EFAULT; 2025 goto lenout; 2026 } 2027 2028 /* Dubious BSD thing... Probably nobody even uses it, but 2029 * the UNIX standard wants it for whatever reason... -DaveM 2030 */ 2031 case SO_ACCEPTCONN: 2032 v.val = sk->sk_state == TCP_LISTEN; 2033 break; 2034 2035 case SO_PASSSEC: 2036 if (!IS_ENABLED(CONFIG_SECURITY_NETWORK) || !sk_may_scm_recv(sk)) 2037 return -EOPNOTSUPP; 2038 2039 v.val = sk->sk_scm_security; 2040 break; 2041 2042 case SO_PEERSEC: 2043 return security_socket_getpeersec_stream(sock, 2044 optval, optlen, len); 2045 2046 case SO_MARK: 2047 v.val = READ_ONCE(sk->sk_mark); 2048 break; 2049 2050 case SO_RCVMARK: 2051 v.val = sock_flag(sk, SOCK_RCVMARK); 2052 break; 2053 2054 case SO_RCVPRIORITY: 2055 v.val = sock_flag(sk, SOCK_RCVPRIORITY); 2056 break; 2057 2058 case SO_RXQ_OVFL: 2059 v.val = sock_flag(sk, SOCK_RXQ_OVFL); 2060 break; 2061 2062 case SO_WIFI_STATUS: 2063 v.val = sock_flag(sk, SOCK_WIFI_STATUS); 2064 break; 2065 2066 case SO_PEEK_OFF: 2067 if (!READ_ONCE(sock->ops)->set_peek_off) 2068 return -EOPNOTSUPP; 2069 2070 v.val = READ_ONCE(sk->sk_peek_off); 2071 break; 2072 case SO_NOFCS: 2073 v.val = sock_flag(sk, SOCK_NOFCS); 2074 break; 2075 2076 case SO_BINDTODEVICE: 2077 return sock_getbindtodevice(sk, optval, optlen, len); 2078 2079 case SO_GET_FILTER: 2080 len = sk_get_filter(sk, optval, len); 2081 if (len < 0) 2082 return len; 2083 2084 goto lenout; 2085 2086 case SO_LOCK_FILTER: 2087 v.val = sock_flag(sk, SOCK_FILTER_LOCKED); 2088 break; 2089 2090 case SO_BPF_EXTENSIONS: 2091 v.val = bpf_tell_extensions(); 2092 break; 2093 2094 case SO_SELECT_ERR_QUEUE: 2095 v.val = sock_flag(sk, SOCK_SELECT_ERR_QUEUE); 2096 break; 2097 2098 #ifdef CONFIG_NET_RX_BUSY_POLL 2099 case SO_BUSY_POLL: 2100 v.val = READ_ONCE(sk->sk_ll_usec); 2101 break; 2102 case SO_PREFER_BUSY_POLL: 2103 v.val = READ_ONCE(sk->sk_prefer_busy_poll); 2104 break; 2105 #endif 2106 2107 case SO_MAX_PACING_RATE: 2108 /* The READ_ONCE() pair with the WRITE_ONCE() in sk_setsockopt() */ 2109 if (sizeof(v.ulval) != sizeof(v.val) && len >= sizeof(v.ulval)) { 2110 lv = sizeof(v.ulval); 2111 v.ulval = READ_ONCE(sk->sk_max_pacing_rate); 2112 } else { 2113 /* 32bit version */ 2114 v.val = min_t(unsigned long, ~0U, 2115 READ_ONCE(sk->sk_max_pacing_rate)); 2116 } 2117 break; 2118 2119 case SO_INCOMING_CPU: 2120 v.val = READ_ONCE(sk->sk_incoming_cpu); 2121 break; 2122 2123 case SO_MEMINFO: 2124 { 2125 u32 meminfo[SK_MEMINFO_VARS]; 2126 2127 sk_get_meminfo(sk, meminfo); 2128 2129 len = min_t(unsigned int, len, sizeof(meminfo)); 2130 if (copy_to_sockptr(optval, &meminfo, len)) 2131 return -EFAULT; 2132 2133 goto lenout; 2134 } 2135 2136 #ifdef CONFIG_NET_RX_BUSY_POLL 2137 case SO_INCOMING_NAPI_ID: 2138 v.val = READ_ONCE(sk->sk_napi_id); 2139 2140 /* aggregate non-NAPI IDs down to 0 */ 2141 if (!napi_id_valid(v.val)) 2142 v.val = 0; 2143 2144 break; 2145 #endif 2146 2147 case SO_COOKIE: 2148 lv = sizeof(u64); 2149 if (len < lv) 2150 return -EINVAL; 2151 v.val64 = sock_gen_cookie(sk); 2152 break; 2153 2154 case SO_ZEROCOPY: 2155 v.val = sock_flag(sk, SOCK_ZEROCOPY); 2156 break; 2157 2158 case SO_TXTIME: 2159 lv = sizeof(v.txtime); 2160 v.txtime.clockid = sk->sk_clockid; 2161 v.txtime.flags |= sk->sk_txtime_deadline_mode ? 2162 SOF_TXTIME_DEADLINE_MODE : 0; 2163 v.txtime.flags |= sk->sk_txtime_report_errors ? 2164 SOF_TXTIME_REPORT_ERRORS : 0; 2165 break; 2166 2167 case SO_BINDTOIFINDEX: 2168 v.val = READ_ONCE(sk->sk_bound_dev_if); 2169 break; 2170 2171 case SO_NETNS_COOKIE: 2172 lv = sizeof(u64); 2173 if (len != lv) 2174 return -EINVAL; 2175 v.val64 = sock_net(sk)->net_cookie; 2176 break; 2177 2178 case SO_BUF_LOCK: 2179 v.val = sk->sk_userlocks & SOCK_BUF_LOCK_MASK; 2180 break; 2181 2182 case SO_RESERVE_MEM: 2183 v.val = READ_ONCE(sk->sk_reserved_mem); 2184 break; 2185 2186 case SO_TXREHASH: 2187 if (!sk_is_tcp(sk)) 2188 return -EOPNOTSUPP; 2189 2190 /* Paired with WRITE_ONCE() in sk_setsockopt() */ 2191 v.val = READ_ONCE(sk->sk_txrehash); 2192 break; 2193 2194 default: 2195 /* We implement the SO_SNDLOWAT etc to not be settable 2196 * (1003.1g 7). 2197 */ 2198 return -ENOPROTOOPT; 2199 } 2200 2201 if (len > lv) 2202 len = lv; 2203 if (copy_to_sockptr(optval, &v, len)) 2204 return -EFAULT; 2205 lenout: 2206 if (copy_to_sockptr(optlen, &len, sizeof(int))) 2207 return -EFAULT; 2208 return 0; 2209 } 2210 2211 /* 2212 * Initialize an sk_lock. 2213 * 2214 * (We also register the sk_lock with the lock validator.) 2215 */ 2216 static inline void sock_lock_init(struct sock *sk) 2217 { 2218 sk_owner_clear(sk); 2219 2220 if (sk->sk_kern_sock) 2221 sock_lock_init_class_and_name( 2222 sk, 2223 af_family_kern_slock_key_strings[sk->sk_family], 2224 af_family_kern_slock_keys + sk->sk_family, 2225 af_family_kern_key_strings[sk->sk_family], 2226 af_family_kern_keys + sk->sk_family); 2227 else 2228 sock_lock_init_class_and_name( 2229 sk, 2230 af_family_slock_key_strings[sk->sk_family], 2231 af_family_slock_keys + sk->sk_family, 2232 af_family_key_strings[sk->sk_family], 2233 af_family_keys + sk->sk_family); 2234 } 2235 2236 /* 2237 * Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet, 2238 * even temporarily, because of RCU lookups. sk_node should also be left as is. 2239 * We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end 2240 */ 2241 static void sock_copy(struct sock *nsk, const struct sock *osk) 2242 { 2243 const struct proto *prot = READ_ONCE(osk->sk_prot); 2244 #ifdef CONFIG_SECURITY_NETWORK 2245 void *sptr = nsk->sk_security; 2246 #endif 2247 2248 /* If we move sk_tx_queue_mapping out of the private section, 2249 * we must check if sk_tx_queue_clear() is called after 2250 * sock_copy() in sk_clone_lock(). 2251 */ 2252 BUILD_BUG_ON(offsetof(struct sock, sk_tx_queue_mapping) < 2253 offsetof(struct sock, sk_dontcopy_begin) || 2254 offsetof(struct sock, sk_tx_queue_mapping) >= 2255 offsetof(struct sock, sk_dontcopy_end)); 2256 2257 memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin)); 2258 2259 unsafe_memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end, 2260 prot->obj_size - offsetof(struct sock, sk_dontcopy_end), 2261 /* alloc is larger than struct, see sk_prot_alloc() */); 2262 2263 #ifdef CONFIG_SECURITY_NETWORK 2264 nsk->sk_security = sptr; 2265 security_sk_clone(osk, nsk); 2266 #endif 2267 } 2268 2269 static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority, 2270 int family) 2271 { 2272 struct sock *sk; 2273 struct kmem_cache *slab; 2274 2275 slab = prot->slab; 2276 if (slab != NULL) { 2277 sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO); 2278 if (!sk) 2279 return sk; 2280 if (want_init_on_alloc(priority)) 2281 sk_prot_clear_nulls(sk, prot->obj_size); 2282 } else 2283 sk = kmalloc(prot->obj_size, priority); 2284 2285 if (sk != NULL) { 2286 if (security_sk_alloc(sk, family, priority)) 2287 goto out_free; 2288 2289 if (!try_module_get(prot->owner)) 2290 goto out_free_sec; 2291 } 2292 2293 return sk; 2294 2295 out_free_sec: 2296 security_sk_free(sk); 2297 out_free: 2298 if (slab != NULL) 2299 kmem_cache_free(slab, sk); 2300 else 2301 kfree(sk); 2302 return NULL; 2303 } 2304 2305 static void sk_prot_free(struct proto *prot, struct sock *sk) 2306 { 2307 struct kmem_cache *slab; 2308 struct module *owner; 2309 2310 owner = prot->owner; 2311 slab = prot->slab; 2312 2313 cgroup_sk_free(&sk->sk_cgrp_data); 2314 mem_cgroup_sk_free(sk); 2315 security_sk_free(sk); 2316 2317 sk_owner_put(sk); 2318 2319 if (slab != NULL) 2320 kmem_cache_free(slab, sk); 2321 else 2322 kfree(sk); 2323 module_put(owner); 2324 } 2325 2326 /** 2327 * sk_alloc - All socket objects are allocated here 2328 * @net: the applicable net namespace 2329 * @family: protocol family 2330 * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) 2331 * @prot: struct proto associated with this new sock instance 2332 * @kern: is this to be a kernel socket? 2333 */ 2334 struct sock *sk_alloc(struct net *net, int family, gfp_t priority, 2335 struct proto *prot, int kern) 2336 { 2337 struct sock *sk; 2338 2339 sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family); 2340 if (sk) { 2341 sk->sk_family = family; 2342 /* 2343 * See comment in struct sock definition to understand 2344 * why we need sk_prot_creator -acme 2345 */ 2346 sk->sk_prot = sk->sk_prot_creator = prot; 2347 2348 if (READ_ONCE(net->core.sysctl_bypass_prot_mem)) 2349 sk->sk_bypass_prot_mem = 1; 2350 2351 sk->sk_kern_sock = kern; 2352 sock_lock_init(sk); 2353 2354 sk->sk_net_refcnt = kern ? 0 : 1; 2355 if (likely(sk->sk_net_refcnt)) { 2356 get_net_track(net, &sk->ns_tracker, priority); 2357 sock_inuse_add(net, 1); 2358 } else { 2359 net_passive_inc(net); 2360 __netns_tracker_alloc(net, &sk->ns_tracker, 2361 false, priority); 2362 } 2363 2364 sock_net_set(sk, net); 2365 refcount_set(&sk->sk_wmem_alloc, SK_WMEM_ALLOC_BIAS); 2366 2367 mem_cgroup_sk_alloc(sk); 2368 cgroup_sk_alloc(&sk->sk_cgrp_data); 2369 sock_update_classid(&sk->sk_cgrp_data); 2370 sock_update_netprioidx(&sk->sk_cgrp_data); 2371 sk_tx_queue_clear(sk); 2372 } 2373 2374 return sk; 2375 } 2376 EXPORT_SYMBOL(sk_alloc); 2377 2378 /* Sockets having SOCK_RCU_FREE will call this function after one RCU 2379 * grace period. This is the case for UDP sockets and TCP listeners. 2380 */ 2381 static void __sk_destruct(struct rcu_head *head) 2382 { 2383 struct sock *sk = container_of(head, struct sock, sk_rcu); 2384 struct net *net = sock_net(sk); 2385 struct sk_filter *filter; 2386 2387 if (sk->sk_destruct) 2388 sk->sk_destruct(sk); 2389 2390 filter = rcu_dereference_check(sk->sk_filter, 2391 refcount_read(&sk->sk_wmem_alloc) == 0); 2392 if (filter) { 2393 sk_filter_uncharge(sk, filter); 2394 RCU_INIT_POINTER(sk->sk_filter, NULL); 2395 } 2396 2397 sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP); 2398 2399 #ifdef CONFIG_BPF_SYSCALL 2400 bpf_sk_storage_free(sk); 2401 #endif 2402 2403 if (atomic_read(&sk->sk_omem_alloc)) 2404 pr_debug("%s: optmem leakage (%d bytes) detected\n", 2405 __func__, atomic_read(&sk->sk_omem_alloc)); 2406 2407 if (sk->sk_frag.page) { 2408 put_page(sk->sk_frag.page); 2409 sk->sk_frag.page = NULL; 2410 } 2411 2412 /* We do not need to acquire sk->sk_peer_lock, we are the last user. */ 2413 put_cred(sk->sk_peer_cred); 2414 put_pids(sk->sk_peer_pid); 2415 2416 if (likely(sk->sk_net_refcnt)) { 2417 put_net_track(net, &sk->ns_tracker); 2418 } else { 2419 __netns_tracker_free(net, &sk->ns_tracker, false); 2420 net_passive_dec(net); 2421 } 2422 sk_prot_free(sk->sk_prot_creator, sk); 2423 } 2424 2425 void __sk_net_refcnt_upgrade(struct sock *sk, gfp_t gfp) 2426 { 2427 struct net *net = sock_net(sk); 2428 2429 WARN_ON_ONCE(sk->sk_net_refcnt); 2430 __netns_tracker_free(net, &sk->ns_tracker, false); 2431 net_passive_dec(net); 2432 sk->sk_net_refcnt = 1; 2433 get_net_track(net, &sk->ns_tracker, gfp); 2434 sock_inuse_add(net, 1); 2435 } 2436 2437 void sk_net_refcnt_upgrade(struct sock *sk) 2438 { 2439 __sk_net_refcnt_upgrade(sk, GFP_KERNEL); 2440 } 2441 EXPORT_SYMBOL_GPL(sk_net_refcnt_upgrade); 2442 2443 void sk_destruct(struct sock *sk) 2444 { 2445 bool use_call_rcu = sock_flag(sk, SOCK_RCU_FREE); 2446 2447 if (rcu_access_pointer(sk->sk_reuseport_cb)) { 2448 reuseport_detach_sock(sk); 2449 use_call_rcu = true; 2450 } 2451 2452 if (use_call_rcu) 2453 call_rcu(&sk->sk_rcu, __sk_destruct); 2454 else 2455 __sk_destruct(&sk->sk_rcu); 2456 } 2457 2458 static void __sk_free(struct sock *sk) 2459 { 2460 if (likely(sk->sk_net_refcnt)) 2461 sock_inuse_add(sock_net(sk), -1); 2462 2463 if (unlikely(sk->sk_net_refcnt && sock_diag_has_destroy_listeners(sk))) 2464 sock_diag_broadcast_destroy(sk); 2465 else 2466 sk_destruct(sk); 2467 } 2468 2469 void sk_free(struct sock *sk) 2470 { 2471 /* 2472 * We subtract one from sk_wmem_alloc and can know if 2473 * some packets are still in some tx queue. 2474 * If not null, sock_wfree() will call __sk_free(sk) later 2475 */ 2476 if (refcount_dec_and_test(&sk->sk_wmem_alloc)) 2477 __sk_free(sk); 2478 } 2479 EXPORT_SYMBOL(sk_free); 2480 2481 static void sk_init_common(struct sock *sk) 2482 { 2483 skb_queue_head_init(&sk->sk_receive_queue); 2484 skb_queue_head_init(&sk->sk_write_queue); 2485 skb_queue_head_init(&sk->sk_error_queue); 2486 2487 rwlock_init(&sk->sk_callback_lock); 2488 lockdep_set_class_and_name(&sk->sk_receive_queue.lock, 2489 af_rlock_keys + sk->sk_family, 2490 af_family_rlock_key_strings[sk->sk_family]); 2491 lockdep_set_class_and_name(&sk->sk_write_queue.lock, 2492 af_wlock_keys + sk->sk_family, 2493 af_family_wlock_key_strings[sk->sk_family]); 2494 lockdep_set_class_and_name(&sk->sk_error_queue.lock, 2495 af_elock_keys + sk->sk_family, 2496 af_family_elock_key_strings[sk->sk_family]); 2497 if (sk->sk_kern_sock) 2498 lockdep_set_class_and_name(&sk->sk_callback_lock, 2499 af_kern_callback_keys + sk->sk_family, 2500 af_family_kern_clock_key_strings[sk->sk_family]); 2501 else 2502 lockdep_set_class_and_name(&sk->sk_callback_lock, 2503 af_callback_keys + sk->sk_family, 2504 af_family_clock_key_strings[sk->sk_family]); 2505 } 2506 2507 /** 2508 * sk_clone - clone a socket 2509 * @sk: the socket to clone 2510 * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) 2511 * @lock: if true, lock the cloned sk 2512 * 2513 * If @lock is true, the clone is locked by bh_lock_sock(), and 2514 * caller must unlock socket even in error path by bh_unlock_sock(). 2515 */ 2516 struct sock *sk_clone(const struct sock *sk, const gfp_t priority, 2517 bool lock) 2518 { 2519 struct proto *prot = READ_ONCE(sk->sk_prot); 2520 struct sk_filter *filter; 2521 bool is_charged = true; 2522 struct sock *newsk; 2523 2524 newsk = sk_prot_alloc(prot, priority, sk->sk_family); 2525 if (!newsk) 2526 goto out; 2527 2528 sock_copy(newsk, sk); 2529 2530 newsk->sk_prot_creator = prot; 2531 #ifdef CONFIG_BPF_SYSCALL 2532 RCU_INIT_POINTER(newsk->sk_bpf_storage, NULL); 2533 #endif 2534 #if IS_ENABLED(CONFIG_INET_PSP) 2535 DEBUG_NET_WARN_ON_ONCE(rcu_access_pointer(sk->psp_assoc)); 2536 #endif 2537 2538 /* SANITY */ 2539 if (likely(newsk->sk_net_refcnt)) { 2540 get_net_track(sock_net(newsk), &newsk->ns_tracker, priority); 2541 sock_inuse_add(sock_net(newsk), 1); 2542 } else { 2543 /* Kernel sockets are not elevating the struct net refcount. 2544 * Instead, use a tracker to more easily detect if a layer 2545 * is not properly dismantling its kernel sockets at netns 2546 * destroy time. 2547 */ 2548 net_passive_inc(sock_net(newsk)); 2549 __netns_tracker_alloc(sock_net(newsk), &newsk->ns_tracker, 2550 false, priority); 2551 } 2552 2553 sk_node_init(&newsk->sk_node); 2554 sock_lock_init(newsk); 2555 spin_lock_init(&newsk->sk_peer_lock); 2556 2557 if (lock) 2558 bh_lock_sock(newsk); 2559 2560 newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL; 2561 newsk->sk_backlog.len = 0; 2562 2563 atomic_set(&newsk->sk_rmem_alloc, 0); 2564 2565 refcount_set(&newsk->sk_wmem_alloc, SK_WMEM_ALLOC_BIAS); 2566 2567 atomic_set(&newsk->sk_omem_alloc, 0); 2568 sk_init_common(newsk); 2569 2570 newsk->sk_dst_cache = NULL; 2571 newsk->sk_dst_pending_confirm = 0; 2572 newsk->sk_wmem_queued = 0; 2573 newsk->sk_forward_alloc = 0; 2574 newsk->sk_reserved_mem = 0; 2575 DEBUG_NET_WARN_ON_ONCE(newsk->sk_drop_counters); 2576 sk_drops_reset(newsk); 2577 newsk->sk_send_head = NULL; 2578 newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK; 2579 atomic_set(&newsk->sk_zckey, 0); 2580 2581 sock_reset_flag(newsk, SOCK_DONE); 2582 2583 #ifdef CONFIG_MEMCG 2584 /* sk->sk_memcg will be populated at accept() time */ 2585 newsk->sk_memcg = NULL; 2586 #endif 2587 2588 cgroup_sk_clone(&newsk->sk_cgrp_data); 2589 2590 RCU_INIT_POINTER(newsk->sk_reuseport_cb, NULL); 2591 2592 if (sock_needs_netstamp(sk) && newsk->sk_flags & SK_FLAGS_TIMESTAMP) 2593 net_enable_timestamp(); 2594 2595 rcu_read_lock(); 2596 filter = rcu_dereference(sk->sk_filter); 2597 if (filter != NULL) 2598 /* though it's an empty new sock, the charging may fail 2599 * if sysctl_optmem_max was changed between creation of 2600 * original socket and cloning 2601 */ 2602 is_charged = sk_filter_charge(newsk, filter); 2603 RCU_INIT_POINTER(newsk->sk_filter, filter); 2604 rcu_read_unlock(); 2605 2606 if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) { 2607 /* We need to make sure that we don't uncharge the new 2608 * socket if we couldn't charge it in the first place 2609 * as otherwise we uncharge the parent's filter. 2610 */ 2611 if (!is_charged) 2612 RCU_INIT_POINTER(newsk->sk_filter, NULL); 2613 2614 goto free; 2615 } 2616 2617 if (bpf_sk_storage_clone(sk, newsk)) 2618 goto free; 2619 2620 /* Clear sk_user_data if parent had the pointer tagged 2621 * as not suitable for copying when cloning. 2622 */ 2623 if (sk_user_data_is_nocopy(newsk)) 2624 newsk->sk_user_data = NULL; 2625 2626 newsk->sk_err = 0; 2627 newsk->sk_err_soft = 0; 2628 newsk->sk_priority = 0; 2629 newsk->sk_incoming_cpu = raw_smp_processor_id(); 2630 2631 /* Before updating sk_refcnt, we must commit prior changes to memory 2632 * (Documentation/RCU/rculist_nulls.rst for details) 2633 */ 2634 smp_wmb(); 2635 refcount_set(&newsk->sk_refcnt, 2); 2636 2637 sk_set_socket(newsk, NULL); 2638 sk_tx_queue_clear(newsk); 2639 sk_rx_queue_clear(newsk); 2640 RCU_INIT_POINTER(newsk->sk_wq, NULL); 2641 2642 if (newsk->sk_prot->sockets_allocated) 2643 sk_sockets_allocated_inc(newsk); 2644 out: 2645 return newsk; 2646 free: 2647 /* It is still raw copy of parent, so invalidate 2648 * destructor and make plain sk_free() 2649 */ 2650 newsk->sk_destruct = NULL; 2651 if (lock) 2652 bh_unlock_sock(newsk); 2653 sk_free(newsk); 2654 newsk = NULL; 2655 goto out; 2656 } 2657 EXPORT_SYMBOL_GPL(sk_clone); 2658 2659 static u32 sk_dst_gso_max_size(struct sock *sk, const struct net_device *dev) 2660 { 2661 bool is_ipv6 = false; 2662 u32 max_size; 2663 2664 #if IS_ENABLED(CONFIG_IPV6) 2665 is_ipv6 = (sk->sk_family == AF_INET6 && 2666 !ipv6_addr_v4mapped(&sk->sk_v6_rcv_saddr)); 2667 #endif 2668 /* pairs with the WRITE_ONCE() in netif_set_gso(_ipv4)_max_size() */ 2669 max_size = is_ipv6 ? READ_ONCE(dev->gso_max_size) : 2670 READ_ONCE(dev->gso_ipv4_max_size); 2671 if (max_size > GSO_LEGACY_MAX_SIZE && !sk_is_tcp(sk)) 2672 max_size = GSO_LEGACY_MAX_SIZE; 2673 2674 return max_size - (MAX_TCP_HEADER + 1); 2675 } 2676 2677 void sk_setup_caps(struct sock *sk, struct dst_entry *dst) 2678 { 2679 const struct net_device *dev; 2680 u32 max_segs = 1; 2681 2682 rcu_read_lock(); 2683 dev = dst_dev_rcu(dst); 2684 sk->sk_route_caps = dev->features; 2685 if (sk_is_tcp(sk)) { 2686 struct inet_connection_sock *icsk = inet_csk(sk); 2687 2688 sk->sk_route_caps |= NETIF_F_GSO; 2689 icsk->icsk_ack.dst_quick_ack = dst_metric(dst, RTAX_QUICKACK); 2690 } 2691 if (sk->sk_route_caps & NETIF_F_GSO) 2692 sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE; 2693 if (unlikely(sk->sk_gso_disabled)) 2694 sk->sk_route_caps &= ~NETIF_F_GSO_MASK; 2695 if (sk_can_gso(sk)) { 2696 if (dst->header_len && !xfrm_dst_offload_ok(dst)) { 2697 sk->sk_route_caps &= ~NETIF_F_GSO_MASK; 2698 } else { 2699 sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM; 2700 sk->sk_gso_max_size = sk_dst_gso_max_size(sk, dev); 2701 /* pairs with the WRITE_ONCE() in netif_set_gso_max_segs() */ 2702 max_segs = max_t(u32, READ_ONCE(dev->gso_max_segs), 1); 2703 } 2704 } 2705 sk->sk_gso_max_segs = max_segs; 2706 sk_dst_set(sk, dst); 2707 rcu_read_unlock(); 2708 } 2709 EXPORT_SYMBOL_GPL(sk_setup_caps); 2710 2711 bool sk_has_decrypt_user(const struct sock *sk) 2712 { 2713 return psp_sk_assoc(sk) || 2714 (sk_is_inet(sk) && inet_csk_has_ulp(sk)); /* for tls */ 2715 } 2716 2717 /* 2718 * Simple resource managers for sockets. 2719 */ 2720 2721 2722 /* 2723 * Write buffer destructor automatically called from kfree_skb. 2724 */ 2725 void sock_wfree(struct sk_buff *skb) 2726 { 2727 unsigned int len = skb->truesize; 2728 struct sock *sk = skb->sk; 2729 bool free; 2730 int old; 2731 2732 if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) { 2733 void (*sk_write_space)(struct sock *sk); 2734 2735 sk_write_space = READ_ONCE(sk->sk_write_space); 2736 2737 if (sock_flag(sk, SOCK_RCU_FREE) && 2738 sk_write_space == sock_def_write_space) { 2739 rcu_read_lock(); 2740 free = __refcount_sub_and_test(len, &sk->sk_wmem_alloc, 2741 &old); 2742 sock_def_write_space_wfree(sk, old - len); 2743 rcu_read_unlock(); 2744 if (unlikely(free)) 2745 __sk_free(sk); 2746 return; 2747 } 2748 2749 /* 2750 * Keep a reference on sk_wmem_alloc, this will be released 2751 * after sk_write_space() call 2752 */ 2753 WARN_ON(refcount_sub_and_test(len - 1, &sk->sk_wmem_alloc)); 2754 sk_write_space(sk); 2755 len = 1; 2756 } 2757 /* 2758 * if sk_wmem_alloc reaches 0, we must finish what sk_free() 2759 * could not do because of in-flight packets 2760 */ 2761 if (refcount_sub_and_test(len, &sk->sk_wmem_alloc)) 2762 __sk_free(sk); 2763 } 2764 EXPORT_SYMBOL(sock_wfree); 2765 2766 /* This variant of sock_wfree() is used by TCP, 2767 * since it sets SOCK_USE_WRITE_QUEUE. 2768 */ 2769 #ifdef CONFIG_INET 2770 void __sock_wfree(struct sk_buff *skb) 2771 { 2772 struct sock *sk = skb->sk; 2773 2774 if (refcount_sub_and_test(skb->truesize, &sk->sk_wmem_alloc)) 2775 __sk_free(sk); 2776 } 2777 EXPORT_SYMBOL_GPL(__sock_wfree); 2778 #endif 2779 2780 void skb_set_owner_w(struct sk_buff *skb, struct sock *sk) 2781 { 2782 int old_wmem; 2783 2784 skb_orphan(skb); 2785 #ifdef CONFIG_INET 2786 if (unlikely(!sk_fullsock(sk))) 2787 return skb_set_owner_edemux(skb, sk); 2788 #endif 2789 skb->sk = sk; 2790 skb->destructor = sock_wfree; 2791 skb_set_hash_from_sk(skb, sk); 2792 /* 2793 * We used to take a refcount on sk, but following operation 2794 * is enough to guarantee sk_free() won't free this sock until 2795 * all in-flight packets are completed 2796 */ 2797 __refcount_add(skb->truesize, &sk->sk_wmem_alloc, &old_wmem); 2798 2799 /* (old_wmem == SK_WMEM_ALLOC_BIAS) if no other TX packet for this socket 2800 * is in a host queue (qdisc, NIC queue). 2801 * Set skb->ooo_okay so that netdev_pick_tx() can choose a TX queue 2802 * based on XPS for better performance. 2803 * Otherwise clear ooo_okay to not risk Out Of Order delivery. 2804 */ 2805 skb->ooo_okay = (old_wmem == SK_WMEM_ALLOC_BIAS); 2806 } 2807 EXPORT_SYMBOL(skb_set_owner_w); 2808 2809 static bool can_skb_orphan_partial(const struct sk_buff *skb) 2810 { 2811 /* Drivers depend on in-order delivery for crypto offload, 2812 * partial orphan breaks out-of-order-OK logic. 2813 */ 2814 if (skb_is_decrypted(skb)) 2815 return false; 2816 2817 return (skb->destructor == sock_wfree || 2818 (IS_ENABLED(CONFIG_INET) && skb->destructor == tcp_wfree)); 2819 } 2820 2821 /* This helper is used by netem, as it can hold packets in its 2822 * delay queue. We want to allow the owner socket to send more 2823 * packets, as if they were already TX completed by a typical driver. 2824 * But we also want to keep skb->sk set because some packet schedulers 2825 * rely on it (sch_fq for example). 2826 */ 2827 void skb_orphan_partial(struct sk_buff *skb) 2828 { 2829 if (skb_is_tcp_pure_ack(skb)) 2830 return; 2831 2832 if (can_skb_orphan_partial(skb) && skb_set_owner_sk_safe(skb, skb->sk)) 2833 return; 2834 2835 skb_orphan(skb); 2836 } 2837 EXPORT_SYMBOL(skb_orphan_partial); 2838 2839 /* 2840 * Read buffer destructor automatically called from kfree_skb. 2841 */ 2842 void sock_rfree(struct sk_buff *skb) 2843 { 2844 struct sock *sk = skb->sk; 2845 unsigned int len = skb->truesize; 2846 2847 atomic_sub(len, &sk->sk_rmem_alloc); 2848 sk_mem_uncharge(sk, len); 2849 } 2850 EXPORT_SYMBOL(sock_rfree); 2851 2852 /* 2853 * Buffer destructor for skbs that are not used directly in read or write 2854 * path, e.g. for error handler skbs. Automatically called from kfree_skb. 2855 */ 2856 void sock_efree(struct sk_buff *skb) 2857 { 2858 sock_put(skb->sk); 2859 } 2860 EXPORT_SYMBOL(sock_efree); 2861 2862 /* Buffer destructor for prefetch/receive path where reference count may 2863 * not be held, e.g. for listen sockets. 2864 */ 2865 #ifdef CONFIG_INET 2866 void sock_pfree(struct sk_buff *skb) 2867 { 2868 struct sock *sk = skb->sk; 2869 2870 if (!sk_is_refcounted(sk)) 2871 return; 2872 2873 if (sk->sk_state == TCP_NEW_SYN_RECV && inet_reqsk(sk)->syncookie) { 2874 inet_reqsk(sk)->rsk_listener = NULL; 2875 reqsk_free(inet_reqsk(sk)); 2876 return; 2877 } 2878 2879 sock_gen_put(sk); 2880 } 2881 EXPORT_SYMBOL(sock_pfree); 2882 #endif /* CONFIG_INET */ 2883 2884 /* 2885 * Allocate a skb from the socket's send buffer. 2886 */ 2887 struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force, 2888 gfp_t priority) 2889 { 2890 if (force || 2891 refcount_read(&sk->sk_wmem_alloc) < READ_ONCE(sk->sk_sndbuf)) { 2892 struct sk_buff *skb = alloc_skb(size, priority); 2893 2894 if (skb) { 2895 skb_set_owner_w(skb, sk); 2896 return skb; 2897 } 2898 } 2899 return NULL; 2900 } 2901 EXPORT_SYMBOL(sock_wmalloc); 2902 2903 static void sock_ofree(struct sk_buff *skb) 2904 { 2905 struct sock *sk = skb->sk; 2906 2907 atomic_sub(skb->truesize, &sk->sk_omem_alloc); 2908 } 2909 2910 struct sk_buff *sock_omalloc(struct sock *sk, unsigned long size, 2911 gfp_t priority) 2912 { 2913 struct sk_buff *skb; 2914 2915 /* small safe race: SKB_TRUESIZE may differ from final skb->truesize */ 2916 if (atomic_read(&sk->sk_omem_alloc) + SKB_TRUESIZE(size) > 2917 READ_ONCE(sock_net(sk)->core.sysctl_optmem_max)) 2918 return NULL; 2919 2920 skb = alloc_skb(size, priority); 2921 if (!skb) 2922 return NULL; 2923 2924 atomic_add(skb->truesize, &sk->sk_omem_alloc); 2925 skb->sk = sk; 2926 skb->destructor = sock_ofree; 2927 return skb; 2928 } 2929 2930 /* 2931 * Allocate a memory block from the socket's option memory buffer. 2932 */ 2933 void *sock_kmalloc(struct sock *sk, int size, gfp_t priority) 2934 { 2935 int optmem_max = READ_ONCE(sock_net(sk)->core.sysctl_optmem_max); 2936 2937 if ((unsigned int)size <= optmem_max && 2938 atomic_read(&sk->sk_omem_alloc) + size < optmem_max) { 2939 void *mem; 2940 /* First do the add, to avoid the race if kmalloc 2941 * might sleep. 2942 */ 2943 atomic_add(size, &sk->sk_omem_alloc); 2944 mem = kmalloc(size, priority); 2945 if (mem) 2946 return mem; 2947 atomic_sub(size, &sk->sk_omem_alloc); 2948 } 2949 return NULL; 2950 } 2951 EXPORT_SYMBOL(sock_kmalloc); 2952 2953 /* 2954 * Duplicate the input "src" memory block using the socket's 2955 * option memory buffer. 2956 */ 2957 void *sock_kmemdup(struct sock *sk, const void *src, 2958 int size, gfp_t priority) 2959 { 2960 void *mem; 2961 2962 mem = sock_kmalloc(sk, size, priority); 2963 if (mem) 2964 memcpy(mem, src, size); 2965 return mem; 2966 } 2967 EXPORT_SYMBOL(sock_kmemdup); 2968 2969 /* Free an option memory block. Note, we actually want the inline 2970 * here as this allows gcc to detect the nullify and fold away the 2971 * condition entirely. 2972 */ 2973 static inline void __sock_kfree_s(struct sock *sk, void *mem, int size, 2974 const bool nullify) 2975 { 2976 if (WARN_ON_ONCE(!mem)) 2977 return; 2978 if (nullify) 2979 kfree_sensitive(mem); 2980 else 2981 kfree(mem); 2982 atomic_sub(size, &sk->sk_omem_alloc); 2983 } 2984 2985 void sock_kfree_s(struct sock *sk, void *mem, int size) 2986 { 2987 __sock_kfree_s(sk, mem, size, false); 2988 } 2989 EXPORT_SYMBOL(sock_kfree_s); 2990 2991 void sock_kzfree_s(struct sock *sk, void *mem, int size) 2992 { 2993 __sock_kfree_s(sk, mem, size, true); 2994 } 2995 EXPORT_SYMBOL(sock_kzfree_s); 2996 2997 /** 2998 * sk_set_nospace - tell the transport a writer is waiting for space 2999 * @sk: socket 3000 * 3001 * Must be called before the final check of the available send space, 3002 * so that the transport can not miss the request and forget to call 3003 * sk->sk_write_space() once space is available again. 3004 */ 3005 void sk_set_nospace(struct sock *sk) 3006 { 3007 struct socket *sock = sk->sk_socket; 3008 3009 if (!sock) 3010 return; 3011 /* Set SOCK_NOSPACE before tp->tcp_nospace (paired with 3012 * sk_clear_nospace() clearing tp->tcp_nospace before SOCK_NOSPACE) 3013 * so a concurrent clear cannot leave SOCK_NOSPACE set with 3014 * tp->tcp_nospace cleared. 3015 */ 3016 set_bit(SOCK_NOSPACE, &sock->flags); 3017 tcp_set_nospace(sk); 3018 } 3019 EXPORT_SYMBOL(sk_set_nospace); 3020 3021 /** 3022 * sk_clear_nospace - tell the transport no writer is waiting for space 3023 * @sk: socket 3024 * 3025 * Called from ->sk_write_space() handlers, once send space has been 3026 * made available to writers. 3027 */ 3028 void sk_clear_nospace(struct sock *sk) 3029 { 3030 struct socket *sock = sk->sk_socket; 3031 3032 if (!sock) 3033 return; 3034 tcp_clear_nospace(sk); 3035 clear_bit(SOCK_NOSPACE, &sock->flags); 3036 } 3037 EXPORT_SYMBOL(sk_clear_nospace); 3038 3039 /* It is almost wait_for_tcp_memory minus release_sock/lock_sock. 3040 I think, these locks should be removed for datagram sockets. 3041 */ 3042 static long sock_wait_for_wmem(struct sock *sk, long timeo) 3043 { 3044 DEFINE_WAIT(wait); 3045 3046 sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk); 3047 for (;;) { 3048 if (!timeo) 3049 break; 3050 if (signal_pending(current)) 3051 break; 3052 sk_set_nospace(sk); 3053 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); 3054 if (refcount_read(&sk->sk_wmem_alloc) < READ_ONCE(sk->sk_sndbuf)) 3055 break; 3056 if (READ_ONCE(sk->sk_shutdown) & SEND_SHUTDOWN) 3057 break; 3058 if (READ_ONCE(sk->sk_err)) 3059 break; 3060 timeo = schedule_timeout(timeo); 3061 } 3062 finish_wait(sk_sleep(sk), &wait); 3063 return timeo; 3064 } 3065 3066 3067 /* 3068 * Generic send/receive buffer handlers 3069 */ 3070 3071 struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len, 3072 unsigned long data_len, int noblock, 3073 int *errcode, int max_page_order) 3074 { 3075 struct sk_buff *skb; 3076 long timeo; 3077 int err; 3078 3079 timeo = sock_sndtimeo(sk, noblock); 3080 for (;;) { 3081 err = sock_error(sk); 3082 if (err != 0) 3083 goto failure; 3084 3085 err = -EPIPE; 3086 if (READ_ONCE(sk->sk_shutdown) & SEND_SHUTDOWN) 3087 goto failure; 3088 3089 if (sk_wmem_alloc_get(sk) < READ_ONCE(sk->sk_sndbuf)) 3090 break; 3091 3092 sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk); 3093 sk_set_nospace(sk); 3094 err = -EAGAIN; 3095 if (!timeo) 3096 goto failure; 3097 if (signal_pending(current)) 3098 goto interrupted; 3099 timeo = sock_wait_for_wmem(sk, timeo); 3100 } 3101 skb = alloc_skb_with_frags(header_len, data_len, max_page_order, 3102 errcode, sk->sk_allocation); 3103 if (skb) 3104 skb_set_owner_w(skb, sk); 3105 return skb; 3106 3107 interrupted: 3108 err = sock_intr_errno(timeo); 3109 failure: 3110 *errcode = err; 3111 return NULL; 3112 } 3113 EXPORT_SYMBOL(sock_alloc_send_pskb); 3114 3115 int __sock_cmsg_send(struct sock *sk, struct cmsghdr *cmsg, 3116 struct sockcm_cookie *sockc) 3117 { 3118 u32 tsflags; 3119 3120 BUILD_BUG_ON(SOF_TIMESTAMPING_LAST == (1 << 31)); 3121 3122 switch (cmsg->cmsg_type) { 3123 case SO_MARK: 3124 if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_RAW) && 3125 !ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) 3126 return -EPERM; 3127 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) 3128 return -EINVAL; 3129 sockc->mark = *(u32 *)CMSG_DATA(cmsg); 3130 break; 3131 case SO_TIMESTAMPING_OLD: 3132 case SO_TIMESTAMPING_NEW: 3133 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) 3134 return -EINVAL; 3135 3136 tsflags = *(u32 *)CMSG_DATA(cmsg); 3137 if (tsflags & ~SOF_TIMESTAMPING_TX_RECORD_MASK) 3138 return -EINVAL; 3139 3140 sockc->tsflags &= ~SOF_TIMESTAMPING_TX_RECORD_MASK; 3141 sockc->tsflags |= tsflags; 3142 break; 3143 case SCM_TXTIME: 3144 { 3145 ktime_t tmin; 3146 u64 txtime; 3147 3148 if (!sock_flag(sk, SOCK_TXTIME)) 3149 return -EINVAL; 3150 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u64))) 3151 return -EINVAL; 3152 3153 txtime = get_unaligned((u64 *)CMSG_DATA(cmsg)); 3154 3155 /* Allow sending without a delivery time: zero special case */ 3156 if (!txtime) { 3157 sockc->transmit_time = 0; 3158 break; 3159 } 3160 3161 switch (sk->sk_clockid) { 3162 case CLOCK_MONOTONIC: 3163 tmin = 1; 3164 break; 3165 case CLOCK_REALTIME: 3166 tmin = max(ktime_mono_to_real(0), 1); 3167 break; 3168 case CLOCK_TAI: 3169 tmin = max(ktime_mono_to_any(0, TK_OFFS_TAI), 1); 3170 break; 3171 default: 3172 tmin = 1; 3173 WARN_ON_ONCE(1); 3174 break; 3175 } 3176 3177 sockc->transmit_time = max_t(ktime_t, txtime, tmin); 3178 break; 3179 } 3180 case SCM_TS_OPT_ID: 3181 if (sk_is_tcp(sk)) 3182 return -EINVAL; 3183 tsflags = READ_ONCE(sk->sk_tsflags); 3184 if (!(tsflags & SOF_TIMESTAMPING_OPT_ID)) 3185 return -EINVAL; 3186 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) 3187 return -EINVAL; 3188 sockc->ts_opt_id = *(u32 *)CMSG_DATA(cmsg); 3189 sockc->tsflags |= SOCKCM_FLAG_TS_OPT_ID; 3190 break; 3191 /* SCM_RIGHTS and SCM_CREDENTIALS are semantically in SOL_UNIX. */ 3192 case SCM_RIGHTS: 3193 case SCM_CREDENTIALS: 3194 break; 3195 case SO_PRIORITY: 3196 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) 3197 return -EINVAL; 3198 if (!sk_set_prio_allowed(sk, *(u32 *)CMSG_DATA(cmsg))) 3199 return -EPERM; 3200 sockc->priority = *(u32 *)CMSG_DATA(cmsg); 3201 break; 3202 case SCM_DEVMEM_DMABUF: 3203 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) 3204 return -EINVAL; 3205 sockc->dmabuf_id = *(u32 *)CMSG_DATA(cmsg); 3206 break; 3207 default: 3208 return -EINVAL; 3209 } 3210 return 0; 3211 } 3212 EXPORT_SYMBOL(__sock_cmsg_send); 3213 3214 int sock_cmsg_send(struct sock *sk, struct msghdr *msg, 3215 struct sockcm_cookie *sockc) 3216 { 3217 struct cmsghdr *cmsg; 3218 int ret; 3219 3220 for_each_cmsghdr(cmsg, msg) { 3221 if (!CMSG_OK(msg, cmsg)) 3222 return -EINVAL; 3223 if (cmsg->cmsg_level != SOL_SOCKET) 3224 continue; 3225 ret = __sock_cmsg_send(sk, cmsg, sockc); 3226 if (ret) 3227 return ret; 3228 } 3229 return 0; 3230 } 3231 EXPORT_SYMBOL(sock_cmsg_send); 3232 3233 static void sk_enter_memory_pressure(struct sock *sk) 3234 { 3235 if (!sk->sk_prot->enter_memory_pressure) 3236 return; 3237 3238 sk->sk_prot->enter_memory_pressure(sk); 3239 } 3240 3241 static void sk_leave_memory_pressure(struct sock *sk) 3242 { 3243 if (sk->sk_prot->leave_memory_pressure) { 3244 INDIRECT_CALL_INET_1(sk->sk_prot->leave_memory_pressure, 3245 tcp_leave_memory_pressure, sk); 3246 } else { 3247 unsigned long *memory_pressure = sk->sk_prot->memory_pressure; 3248 3249 if (memory_pressure && READ_ONCE(*memory_pressure)) 3250 WRITE_ONCE(*memory_pressure, 0); 3251 } 3252 } 3253 3254 DEFINE_STATIC_KEY_FALSE(net_high_order_alloc_disable_key); 3255 3256 /** 3257 * skb_page_frag_refill - check that a page_frag contains enough room 3258 * @sz: minimum size of the fragment we want to get 3259 * @pfrag: pointer to page_frag 3260 * @gfp: priority for memory allocation 3261 * 3262 * Note: While this allocator tries to use high order pages, there is 3263 * no guarantee that allocations succeed. Therefore, @sz MUST be 3264 * less or equal than PAGE_SIZE. 3265 */ 3266 bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp) 3267 { 3268 if (pfrag->page) { 3269 if (page_ref_count(pfrag->page) == 1) { 3270 pfrag->offset = 0; 3271 return true; 3272 } 3273 if (pfrag->offset + sz <= pfrag->size) 3274 return true; 3275 put_page(pfrag->page); 3276 } 3277 3278 pfrag->offset = 0; 3279 if (SKB_FRAG_PAGE_ORDER && 3280 !static_branch_unlikely(&net_high_order_alloc_disable_key)) { 3281 /* Avoid direct reclaim but allow kswapd to wake */ 3282 pfrag->page = alloc_pages((gfp & ~__GFP_DIRECT_RECLAIM) | 3283 __GFP_COMP | __GFP_NOWARN | 3284 __GFP_NORETRY, 3285 SKB_FRAG_PAGE_ORDER); 3286 if (likely(pfrag->page)) { 3287 pfrag->size = PAGE_SIZE << SKB_FRAG_PAGE_ORDER; 3288 return true; 3289 } 3290 } 3291 pfrag->page = alloc_page(gfp); 3292 if (likely(pfrag->page)) { 3293 pfrag->size = PAGE_SIZE; 3294 return true; 3295 } 3296 return false; 3297 } 3298 EXPORT_SYMBOL(skb_page_frag_refill); 3299 3300 bool sk_page_frag_refill(struct sock *sk, struct page_frag *pfrag) 3301 { 3302 if (likely(skb_page_frag_refill(32U, pfrag, sk->sk_allocation))) 3303 return true; 3304 3305 if (!sk->sk_bypass_prot_mem) 3306 sk_enter_memory_pressure(sk); 3307 3308 sk_stream_moderate_sndbuf(sk); 3309 3310 return false; 3311 } 3312 EXPORT_SYMBOL(sk_page_frag_refill); 3313 3314 static void __lock_sock(struct sock *sk) 3315 __releases(&sk->sk_lock.slock) 3316 __acquires(&sk->sk_lock.slock) 3317 { 3318 DEFINE_WAIT(wait); 3319 3320 for (;;) { 3321 prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait, 3322 TASK_UNINTERRUPTIBLE); 3323 spin_unlock_bh(&sk->sk_lock.slock); 3324 schedule(); 3325 spin_lock_bh(&sk->sk_lock.slock); 3326 if (!sock_owned_by_user(sk)) 3327 break; 3328 } 3329 finish_wait(&sk->sk_lock.wq, &wait); 3330 } 3331 3332 void __release_sock(struct sock *sk) 3333 __releases(&sk->sk_lock.slock) 3334 __acquires(&sk->sk_lock.slock) 3335 { 3336 struct sk_buff *skb, *next; 3337 int nb = 0; 3338 3339 while ((skb = sk->sk_backlog.head) != NULL) { 3340 sk->sk_backlog.head = sk->sk_backlog.tail = NULL; 3341 3342 spin_unlock_bh(&sk->sk_lock.slock); 3343 3344 do { 3345 next = skb->next; 3346 prefetch(next); 3347 DEBUG_NET_WARN_ON_ONCE(skb_dst_is_noref(skb)); 3348 skb_mark_not_on_list(skb); 3349 sk_backlog_rcv(sk, skb); 3350 3351 skb = next; 3352 3353 if (!(++nb & 15)) 3354 cond_resched(); 3355 } while (skb); 3356 3357 spin_lock_bh(&sk->sk_lock.slock); 3358 } 3359 3360 /* 3361 * Doing the zeroing here guarantee we can not loop forever 3362 * while a wild producer attempts to flood us. 3363 */ 3364 sk->sk_backlog.len = 0; 3365 } 3366 3367 void __sk_flush_backlog(struct sock *sk) 3368 { 3369 spin_lock_bh(&sk->sk_lock.slock); 3370 __release_sock(sk); 3371 3372 if (sk->sk_prot->release_cb) 3373 INDIRECT_CALL_INET_1(sk->sk_prot->release_cb, 3374 tcp_release_cb, sk); 3375 3376 spin_unlock_bh(&sk->sk_lock.slock); 3377 } 3378 EXPORT_SYMBOL_GPL(__sk_flush_backlog); 3379 3380 /** 3381 * sk_wait_data - wait for data to arrive at sk_receive_queue 3382 * @sk: sock to wait on 3383 * @timeo: for how long 3384 * @skb: last skb seen on sk_receive_queue 3385 * 3386 * Now socket state including sk->sk_err is changed only under lock, 3387 * hence we may omit checks after joining wait queue. 3388 * We check receive queue before schedule() only as optimization; 3389 * it is very likely that release_sock() added new data. 3390 */ 3391 int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb) 3392 { 3393 DEFINE_WAIT_FUNC(wait, woken_wake_function); 3394 int rc; 3395 3396 add_wait_queue(sk_sleep(sk), &wait); 3397 sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk); 3398 rc = sk_wait_event(sk, timeo, skb_peek_tail(&sk->sk_receive_queue) != skb, &wait); 3399 sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk); 3400 remove_wait_queue(sk_sleep(sk), &wait); 3401 return rc; 3402 } 3403 EXPORT_SYMBOL(sk_wait_data); 3404 3405 /** 3406 * __sk_mem_raise_allocated - increase memory_allocated 3407 * @sk: socket 3408 * @size: memory size to allocate 3409 * @amt: pages to allocate 3410 * @kind: allocation type 3411 * 3412 * Similar to __sk_mem_schedule(), but does not update sk_forward_alloc. 3413 * 3414 * Unlike the globally shared limits among the sockets under same protocol, 3415 * consuming the budget of a memcg won't have direct effect on other ones. 3416 * So be optimistic about memcg's tolerance, and leave the callers to decide 3417 * whether or not to raise allocated through sk_under_memory_pressure() or 3418 * its variants. 3419 */ 3420 int __sk_mem_raise_allocated(struct sock *sk, int size, int amt, int kind) 3421 { 3422 bool memcg_enabled = false, charged = false; 3423 struct proto *prot = sk->sk_prot; 3424 long allocated = 0; 3425 3426 if (!sk->sk_bypass_prot_mem) { 3427 sk_memory_allocated_add(sk, amt); 3428 allocated = sk_memory_allocated(sk); 3429 } 3430 3431 if (mem_cgroup_sk_enabled(sk)) { 3432 memcg_enabled = true; 3433 charged = mem_cgroup_sk_charge(sk, amt, gfp_memcg_charge()); 3434 if (!charged) 3435 goto suppress_allocation; 3436 } 3437 3438 if (sk->sk_bypass_prot_mem) 3439 return 1; 3440 3441 /* Under limit. */ 3442 if (allocated <= sk_prot_mem_limits(sk, 0)) { 3443 sk_leave_memory_pressure(sk); 3444 return 1; 3445 } 3446 3447 /* Under pressure. */ 3448 if (allocated > sk_prot_mem_limits(sk, 1)) 3449 sk_enter_memory_pressure(sk); 3450 3451 /* Over hard limit. */ 3452 if (allocated > sk_prot_mem_limits(sk, 2)) 3453 goto suppress_allocation; 3454 3455 /* Guarantee minimum buffer size under pressure (either global 3456 * or memcg) to make sure features described in RFC 7323 (TCP 3457 * Extensions for High Performance) work properly. 3458 * 3459 * This rule does NOT stand when exceeds global or memcg's hard 3460 * limit, or else a DoS attack can be taken place by spawning 3461 * lots of sockets whose usage are under minimum buffer size. 3462 */ 3463 if (kind == SK_MEM_RECV) { 3464 if (atomic_read(&sk->sk_rmem_alloc) < sk_get_rmem0(sk, prot)) 3465 return 1; 3466 3467 } else { /* SK_MEM_SEND */ 3468 int wmem0 = sk_get_wmem0(sk, prot); 3469 3470 if (sk->sk_type == SOCK_STREAM) { 3471 if (sk->sk_wmem_queued < wmem0) 3472 return 1; 3473 } else if (refcount_read(&sk->sk_wmem_alloc) < wmem0) { 3474 return 1; 3475 } 3476 } 3477 3478 if (sk_has_memory_pressure(sk)) { 3479 u64 alloc; 3480 3481 /* The following 'average' heuristic is within the 3482 * scope of global accounting, so it only makes 3483 * sense for global memory pressure. 3484 */ 3485 if (!sk_under_global_memory_pressure(sk)) 3486 return 1; 3487 3488 /* Try to be fair among all the sockets under global 3489 * pressure by allowing the ones that below average 3490 * usage to raise. 3491 */ 3492 alloc = sk_sockets_allocated_read_positive(sk); 3493 if (sk_prot_mem_limits(sk, 2) > alloc * 3494 sk_mem_pages(sk->sk_wmem_queued + 3495 atomic_read(&sk->sk_rmem_alloc) + 3496 sk->sk_forward_alloc)) 3497 return 1; 3498 } 3499 3500 suppress_allocation: 3501 3502 if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) { 3503 sk_stream_moderate_sndbuf(sk); 3504 3505 /* Fail only if socket is _under_ its sndbuf. 3506 * In this case we cannot block, so that we have to fail. 3507 */ 3508 if (sk->sk_wmem_queued + size >= sk->sk_sndbuf) { 3509 /* Force charge with __GFP_NOFAIL */ 3510 if (memcg_enabled && !charged) 3511 mem_cgroup_sk_charge(sk, amt, 3512 gfp_memcg_charge() | __GFP_NOFAIL); 3513 return 1; 3514 } 3515 } 3516 3517 trace_sock_exceed_buf_limit(sk, prot, allocated, kind); 3518 3519 if (!sk->sk_bypass_prot_mem) 3520 sk_memory_allocated_sub(sk, amt); 3521 3522 if (charged) 3523 mem_cgroup_sk_uncharge(sk, amt); 3524 3525 return 0; 3526 } 3527 3528 /** 3529 * __sk_mem_schedule - increase sk_forward_alloc and memory_allocated 3530 * @sk: socket 3531 * @size: memory size to allocate 3532 * @kind: allocation type 3533 * 3534 * If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means 3535 * rmem allocation. This function assumes that protocols which have 3536 * memory_pressure use sk_wmem_queued as write buffer accounting. 3537 */ 3538 int __sk_mem_schedule(struct sock *sk, int size, int kind) 3539 { 3540 int ret, amt = sk_mem_pages(size); 3541 3542 sk_forward_alloc_add(sk, amt << PAGE_SHIFT); 3543 ret = __sk_mem_raise_allocated(sk, size, amt, kind); 3544 if (!ret) 3545 sk_forward_alloc_add(sk, -(amt << PAGE_SHIFT)); 3546 return ret; 3547 } 3548 EXPORT_SYMBOL(__sk_mem_schedule); 3549 3550 /** 3551 * __sk_mem_reduce_allocated - reclaim memory_allocated 3552 * @sk: socket 3553 * @amount: number of quanta 3554 * 3555 * Similar to __sk_mem_reclaim(), but does not update sk_forward_alloc 3556 */ 3557 void __sk_mem_reduce_allocated(struct sock *sk, int amount) 3558 { 3559 if (mem_cgroup_sk_enabled(sk)) 3560 mem_cgroup_sk_uncharge(sk, amount); 3561 3562 if (sk->sk_bypass_prot_mem) 3563 return; 3564 3565 sk_memory_allocated_sub(sk, amount); 3566 3567 if (sk_under_global_memory_pressure(sk) && 3568 (sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0))) 3569 sk_leave_memory_pressure(sk); 3570 } 3571 3572 /** 3573 * __sk_mem_reclaim - reclaim sk_forward_alloc and memory_allocated 3574 * @sk: socket 3575 * @amount: number of bytes (rounded down to a PAGE_SIZE multiple) 3576 */ 3577 void __sk_mem_reclaim(struct sock *sk, int amount) 3578 { 3579 amount >>= PAGE_SHIFT; 3580 sk_forward_alloc_add(sk, -(amount << PAGE_SHIFT)); 3581 __sk_mem_reduce_allocated(sk, amount); 3582 } 3583 EXPORT_SYMBOL(__sk_mem_reclaim); 3584 3585 void __sk_charge(struct sock *sk, gfp_t gfp) 3586 { 3587 int amt; 3588 3589 gfp |= __GFP_NOFAIL; 3590 if (mem_cgroup_from_sk(sk)) { 3591 /* The socket has not been accepted yet, no need 3592 * to look at newsk->sk_wmem_queued. 3593 */ 3594 amt = sk_mem_pages(sk->sk_forward_alloc + 3595 atomic_read(&sk->sk_rmem_alloc)); 3596 if (amt) 3597 mem_cgroup_sk_charge(sk, amt, gfp); 3598 } 3599 3600 kmem_cache_charge(sk, gfp); 3601 } 3602 3603 int sk_set_peek_off(struct sock *sk, int val) 3604 { 3605 WRITE_ONCE(sk->sk_peek_off, val); 3606 return 0; 3607 } 3608 EXPORT_SYMBOL_GPL(sk_set_peek_off); 3609 3610 /* 3611 * Set of default routines for initialising struct proto_ops when 3612 * the protocol does not support a particular function. In certain 3613 * cases where it makes no sense for a protocol to have a "do nothing" 3614 * function, some default processing is provided. 3615 */ 3616 3617 int sock_no_bind(struct socket *sock, struct sockaddr_unsized *saddr, int len) 3618 { 3619 return -EOPNOTSUPP; 3620 } 3621 EXPORT_SYMBOL(sock_no_bind); 3622 3623 int sock_no_connect(struct socket *sock, struct sockaddr_unsized *saddr, 3624 int len, int flags) 3625 { 3626 return -EOPNOTSUPP; 3627 } 3628 EXPORT_SYMBOL(sock_no_connect); 3629 3630 int sock_no_socketpair(struct socket *sock1, struct socket *sock2) 3631 { 3632 return -EOPNOTSUPP; 3633 } 3634 EXPORT_SYMBOL(sock_no_socketpair); 3635 3636 int sock_no_accept(struct socket *sock, struct socket *newsock, 3637 struct proto_accept_arg *arg) 3638 { 3639 return -EOPNOTSUPP; 3640 } 3641 EXPORT_SYMBOL(sock_no_accept); 3642 3643 int sock_no_getname(struct socket *sock, struct sockaddr *saddr, 3644 int peer) 3645 { 3646 return -EOPNOTSUPP; 3647 } 3648 EXPORT_SYMBOL(sock_no_getname); 3649 3650 int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) 3651 { 3652 return -EOPNOTSUPP; 3653 } 3654 EXPORT_SYMBOL(sock_no_ioctl); 3655 3656 int sock_no_listen(struct socket *sock, int backlog) 3657 { 3658 return -EOPNOTSUPP; 3659 } 3660 EXPORT_SYMBOL(sock_no_listen); 3661 3662 int sock_no_shutdown(struct socket *sock, int how) 3663 { 3664 return -EOPNOTSUPP; 3665 } 3666 EXPORT_SYMBOL(sock_no_shutdown); 3667 3668 int sock_no_sendmsg(struct socket *sock, struct msghdr *m, size_t len) 3669 { 3670 return -EOPNOTSUPP; 3671 } 3672 EXPORT_SYMBOL(sock_no_sendmsg); 3673 3674 int sock_no_sendmsg_locked(struct sock *sk, struct msghdr *m, size_t len) 3675 { 3676 return -EOPNOTSUPP; 3677 } 3678 EXPORT_SYMBOL(sock_no_sendmsg_locked); 3679 3680 int sock_no_recvmsg(struct socket *sock, struct msghdr *m, size_t len, 3681 int flags) 3682 { 3683 return -EOPNOTSUPP; 3684 } 3685 EXPORT_SYMBOL(sock_no_recvmsg); 3686 3687 int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma) 3688 { 3689 /* Mirror missing mmap method error code */ 3690 return -ENODEV; 3691 } 3692 EXPORT_SYMBOL(sock_no_mmap); 3693 3694 /* 3695 * When a file is received (via SCM_RIGHTS, etc), we must bump the 3696 * various sock-based usage counts. 3697 */ 3698 void __receive_sock(struct file *file) 3699 { 3700 struct socket *sock; 3701 3702 sock = sock_from_file(file); 3703 if (sock) { 3704 sock_update_netprioidx(&sock->sk->sk_cgrp_data); 3705 sock_update_classid(&sock->sk->sk_cgrp_data); 3706 } 3707 } 3708 3709 /* 3710 * Default Socket Callbacks 3711 */ 3712 3713 static void sock_def_wakeup(struct sock *sk) 3714 { 3715 struct socket_wq *wq; 3716 3717 rcu_read_lock(); 3718 wq = rcu_dereference(sk->sk_wq); 3719 if (skwq_has_sleeper(wq)) 3720 wake_up_interruptible_all(&wq->wait); 3721 rcu_read_unlock(); 3722 } 3723 3724 static void sock_def_error_report(struct sock *sk) 3725 { 3726 struct socket_wq *wq; 3727 3728 rcu_read_lock(); 3729 wq = rcu_dereference(sk->sk_wq); 3730 if (skwq_has_sleeper(wq)) 3731 wake_up_interruptible_poll(&wq->wait, EPOLLERR); 3732 sk_wake_async_rcu(sk, SOCK_WAKE_IO, POLL_ERR); 3733 rcu_read_unlock(); 3734 } 3735 3736 void sock_def_readable(struct sock *sk) 3737 { 3738 struct socket_wq *wq; 3739 3740 trace_sk_data_ready(sk); 3741 3742 rcu_read_lock(); 3743 wq = rcu_dereference(sk->sk_wq); 3744 if (skwq_has_sleeper(wq)) 3745 wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN | EPOLLPRI | 3746 EPOLLRDNORM | EPOLLRDBAND); 3747 sk_wake_async_rcu(sk, SOCK_WAKE_WAITD, POLL_IN); 3748 rcu_read_unlock(); 3749 } 3750 3751 static void sock_def_write_space(struct sock *sk) 3752 { 3753 struct socket_wq *wq; 3754 3755 rcu_read_lock(); 3756 3757 /* Do not wake up a writer until he can make "significant" 3758 * progress. --DaveM 3759 */ 3760 if (sock_writeable(sk)) { 3761 wq = rcu_dereference(sk->sk_wq); 3762 if (skwq_has_sleeper(wq)) 3763 wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT | 3764 EPOLLWRNORM | EPOLLWRBAND); 3765 3766 /* Should agree with poll, otherwise some programs break */ 3767 sk_wake_async_rcu(sk, SOCK_WAKE_SPACE, POLL_OUT); 3768 } 3769 3770 rcu_read_unlock(); 3771 } 3772 3773 /* An optimised version of sock_def_write_space(), should only be called 3774 * for SOCK_RCU_FREE sockets under RCU read section and after putting 3775 * ->sk_wmem_alloc. 3776 */ 3777 static void sock_def_write_space_wfree(struct sock *sk, int wmem_alloc) 3778 { 3779 /* Do not wake up a writer until he can make "significant" 3780 * progress. --DaveM 3781 */ 3782 if (__sock_writeable(sk, wmem_alloc)) { 3783 struct socket_wq *wq = rcu_dereference(sk->sk_wq); 3784 3785 /* rely on refcount_sub from sock_wfree() */ 3786 smp_mb__after_atomic(); 3787 if (wq && waitqueue_active(&wq->wait)) 3788 wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT | 3789 EPOLLWRNORM | EPOLLWRBAND); 3790 3791 /* Should agree with poll, otherwise some programs break */ 3792 sk_wake_async_rcu(sk, SOCK_WAKE_SPACE, POLL_OUT); 3793 } 3794 } 3795 3796 static void sock_def_destruct(struct sock *sk) 3797 { 3798 } 3799 3800 void sk_send_sigurg(struct sock *sk) 3801 { 3802 if (sk->sk_socket && sk->sk_socket->file) 3803 if (send_sigurg(sk->sk_socket->file)) 3804 sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI); 3805 } 3806 EXPORT_SYMBOL(sk_send_sigurg); 3807 3808 void sk_reset_timer(struct sock *sk, struct timer_list* timer, 3809 unsigned long expires) 3810 { 3811 if (!mod_timer(timer, expires)) 3812 sock_hold(sk); 3813 } 3814 EXPORT_SYMBOL(sk_reset_timer); 3815 3816 void sk_stop_timer(struct sock *sk, struct timer_list* timer) 3817 { 3818 if (timer_delete(timer)) 3819 __sock_put(sk); 3820 } 3821 EXPORT_SYMBOL(sk_stop_timer); 3822 3823 void sk_stop_timer_sync(struct sock *sk, struct timer_list *timer) 3824 { 3825 if (timer_delete_sync(timer)) 3826 __sock_put(sk); 3827 } 3828 EXPORT_SYMBOL(sk_stop_timer_sync); 3829 3830 void sock_init_data_uid(struct socket *sock, struct sock *sk, kuid_t uid) 3831 { 3832 sk_init_common(sk); 3833 sk->sk_send_head = NULL; 3834 3835 timer_setup(&sk->sk_timer, NULL, 0); 3836 3837 sk->sk_allocation = GFP_KERNEL; 3838 sk->sk_rcvbuf = READ_ONCE(sysctl_rmem_default); 3839 sk->sk_sndbuf = READ_ONCE(sysctl_wmem_default); 3840 sk->sk_state = TCP_CLOSE; 3841 sk->sk_use_task_frag = true; 3842 sk_set_socket(sk, sock); 3843 3844 sock_set_flag(sk, SOCK_ZAPPED); 3845 3846 if (sock) { 3847 sk->sk_type = sock->type; 3848 RCU_INIT_POINTER(sk->sk_wq, &sock->wq); 3849 sock->sk = sk; 3850 } else { 3851 RCU_INIT_POINTER(sk->sk_wq, NULL); 3852 } 3853 sk->sk_uid = uid; 3854 3855 sk->sk_state_change = sock_def_wakeup; 3856 sk->sk_data_ready = sock_def_readable; 3857 sk->sk_write_space = sock_def_write_space; 3858 sk->sk_error_report = sock_def_error_report; 3859 sk->sk_destruct = sock_def_destruct; 3860 3861 sk->sk_frag.page = NULL; 3862 sk->sk_frag.offset = 0; 3863 sk->sk_peek_off = -1; 3864 3865 memset(sk->sk_peer_pid, 0, sizeof(sk->sk_peer_pid)); 3866 sk->sk_peer_cred = NULL; 3867 spin_lock_init(&sk->sk_peer_lock); 3868 3869 sk->sk_write_pending = 0; 3870 sk->sk_rcvlowat = 1; 3871 sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT; 3872 sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT; 3873 3874 sk->sk_stamp = SK_DEFAULT_STAMP; 3875 #if BITS_PER_LONG==32 3876 seqlock_init(&sk->sk_stamp_seq); 3877 #endif 3878 atomic_set(&sk->sk_zckey, 0); 3879 3880 #ifdef CONFIG_NET_RX_BUSY_POLL 3881 sk->sk_napi_id = 0; 3882 sk->sk_ll_usec = READ_ONCE(sysctl_net_busy_read); 3883 #endif 3884 3885 sk->sk_max_pacing_rate = ~0UL; 3886 sk->sk_pacing_rate = ~0UL; 3887 WRITE_ONCE(sk->sk_pacing_shift, 10); 3888 sk->sk_incoming_cpu = -1; 3889 3890 sk_rx_queue_clear(sk); 3891 /* 3892 * Before updating sk_refcnt, we must commit prior changes to memory 3893 * (Documentation/RCU/rculist_nulls.rst for details) 3894 */ 3895 smp_wmb(); 3896 refcount_set(&sk->sk_refcnt, 1); 3897 sk_drops_reset(sk); 3898 } 3899 EXPORT_SYMBOL(sock_init_data_uid); 3900 3901 void sock_init_data(struct socket *sock, struct sock *sk) 3902 { 3903 kuid_t uid = sock ? 3904 SOCK_INODE(sock)->i_uid : 3905 make_kuid(sock_net(sk)->user_ns, 0); 3906 3907 sock_init_data_uid(sock, sk, uid); 3908 } 3909 EXPORT_SYMBOL(sock_init_data); 3910 3911 void noinline lock_sock_nested(struct sock *sk, int subclass) 3912 { 3913 /* The sk_lock has mutex_lock() semantics here. */ 3914 mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_); 3915 3916 might_sleep(); 3917 #ifdef CONFIG_64BIT 3918 if (sizeof(struct slock_owned) == sizeof(long)) { 3919 socket_lock_t tmp = { 3920 .slock = __SPIN_LOCK_UNLOCKED(tmp.slock), 3921 .owned = 1, 3922 }; 3923 socket_lock_t old = { 3924 .slock = __SPIN_LOCK_UNLOCKED(old.slock), 3925 .owned = 0, 3926 }; 3927 3928 if (likely(try_cmpxchg(&sk->sk_lock.combined, 3929 &old.combined, tmp.combined))) 3930 return; 3931 } 3932 #endif 3933 spin_lock_bh(&sk->sk_lock.slock); 3934 if (unlikely(sock_owned_by_user_nocheck(sk))) 3935 __lock_sock(sk); 3936 sk->sk_lock.owned = 1; 3937 spin_unlock_bh(&sk->sk_lock.slock); 3938 } 3939 EXPORT_SYMBOL(lock_sock_nested); 3940 3941 void release_sock(struct sock *sk) 3942 { 3943 spin_lock_bh(&sk->sk_lock.slock); 3944 3945 if (unlikely(sk->sk_backlog.tail)) 3946 __release_sock(sk); 3947 3948 if (sk->sk_prot->release_cb) { 3949 if (!tcp_release_cb_cond(sk)) 3950 sk->sk_prot->release_cb(sk); 3951 } 3952 sock_release_ownership(sk); 3953 if (unlikely(waitqueue_active(&sk->sk_lock.wq))) 3954 wake_up(&sk->sk_lock.wq); 3955 3956 spin_unlock_bh(&sk->sk_lock.slock); 3957 } 3958 EXPORT_SYMBOL(release_sock); 3959 3960 bool __lock_sock_fast(struct sock *sk) __acquires(&sk->sk_lock.slock) 3961 { 3962 might_sleep(); 3963 spin_lock_bh(&sk->sk_lock.slock); 3964 3965 if (likely(!sock_owned_by_user_nocheck(sk))) { 3966 /* 3967 * Fast path return with bottom halves disabled and 3968 * sock::sk_lock.slock held. 3969 * 3970 * The 'mutex' is not contended and holding 3971 * sock::sk_lock.slock prevents all other lockers to 3972 * proceed so the corresponding unlock_sock_fast() can 3973 * avoid the slow path of release_sock() completely and 3974 * just release slock. 3975 * 3976 * From a semantical POV this is equivalent to 'acquiring' 3977 * the 'mutex', hence the corresponding lockdep 3978 * mutex_release() has to happen in the fast path of 3979 * unlock_sock_fast(). 3980 */ 3981 return false; 3982 } 3983 3984 __lock_sock(sk); 3985 sk->sk_lock.owned = 1; 3986 __acquire(&sk->sk_lock.slock); 3987 spin_unlock_bh(&sk->sk_lock.slock); 3988 return true; 3989 } 3990 EXPORT_SYMBOL(__lock_sock_fast); 3991 3992 int sock_gettstamp(struct socket *sock, void __user *userstamp, 3993 bool timeval, bool time32) 3994 { 3995 struct sock *sk = sock->sk; 3996 struct timespec64 ts; 3997 3998 /* sk->sk_flags must only be changed under the socket lock, 3999 * because sock_set_flag() uses non atomic operations. 4000 */ 4001 if (!sock_flag(sk, SOCK_TIMESTAMP)) { 4002 lock_sock(sk); 4003 sock_enable_timestamp(sk, SOCK_TIMESTAMP); 4004 release_sock(sk); 4005 } 4006 ts = ktime_to_timespec64(sock_read_timestamp(sk)); 4007 if (ts.tv_sec == -1) 4008 return -ENOENT; 4009 if (ts.tv_sec == 0) { 4010 ktime_t kt = ktime_get_real(); 4011 sock_write_timestamp(sk, kt); 4012 ts = ktime_to_timespec64(kt); 4013 } 4014 4015 if (timeval) 4016 ts.tv_nsec /= 1000; 4017 4018 #ifdef CONFIG_COMPAT_32BIT_TIME 4019 if (time32) 4020 return put_old_timespec32(&ts, userstamp); 4021 #endif 4022 #ifdef CONFIG_SPARC64 4023 /* beware of padding in sparc64 timeval */ 4024 if (timeval && !in_compat_syscall()) { 4025 struct __kernel_old_timeval __user tv = { 4026 .tv_sec = ts.tv_sec, 4027 .tv_usec = ts.tv_nsec, 4028 }; 4029 if (copy_to_user(userstamp, &tv, sizeof(tv))) 4030 return -EFAULT; 4031 return 0; 4032 } 4033 #endif 4034 return put_timespec64(&ts, userstamp); 4035 } 4036 EXPORT_SYMBOL(sock_gettstamp); 4037 4038 void sock_enable_timestamp(struct sock *sk, enum sock_flags flag) 4039 { 4040 if (!sock_flag(sk, flag)) { 4041 unsigned long previous_flags = sk->sk_flags; 4042 4043 sock_set_flag(sk, flag); 4044 /* 4045 * we just set one of the two flags which require net 4046 * time stamping, but time stamping might have been on 4047 * already because of the other one 4048 */ 4049 if (sock_needs_netstamp(sk) && 4050 !(previous_flags & SK_FLAGS_TIMESTAMP)) 4051 net_enable_timestamp(); 4052 } 4053 } 4054 4055 int sock_recv_errqueue(struct sock *sk, struct msghdr *msg, int len, 4056 int level, int type) 4057 { 4058 struct sock_extended_err ee; 4059 struct sk_buff *skb; 4060 int copied, err; 4061 4062 err = -EAGAIN; 4063 skb = sock_dequeue_err_skb(sk); 4064 if (skb == NULL) 4065 goto out; 4066 4067 copied = skb->len; 4068 if (copied > len) { 4069 msg->msg_flags |= MSG_TRUNC; 4070 copied = len; 4071 } 4072 err = skb_copy_datagram_msg(skb, 0, msg, copied); 4073 if (err) 4074 goto out_free_skb; 4075 4076 sock_recv_timestamp(msg, sk, skb); 4077 4078 /* We must use a bounce buffer for CONFIG_HARDENED_USERCOPY=y */ 4079 ee = SKB_EXT_ERR(skb)->ee; 4080 put_cmsg(msg, level, type, sizeof(ee), &ee); 4081 4082 msg->msg_flags |= MSG_ERRQUEUE; 4083 err = copied; 4084 4085 out_free_skb: 4086 kfree_skb(skb); 4087 out: 4088 return err; 4089 } 4090 EXPORT_SYMBOL(sock_recv_errqueue); 4091 4092 /* 4093 * Get a socket option on an socket. 4094 * 4095 * FIX: POSIX 1003.1g is very ambiguous here. It states that 4096 * asynchronous errors should be reported by getsockopt. We assume 4097 * this means if you specify SO_ERROR (otherwise what is the point of it). 4098 */ 4099 int sock_common_getsockopt(struct socket *sock, int level, int optname, 4100 char __user *optval, int __user *optlen) 4101 { 4102 struct sock *sk = sock->sk; 4103 4104 return READ_ONCE(sk->sk_prot)->getsockopt(sk, level, optname, optval, optlen); 4105 } 4106 EXPORT_SYMBOL(sock_common_getsockopt); 4107 4108 int sock_common_recvmsg(struct socket *sock, struct msghdr *msg, size_t size, 4109 int flags) 4110 { 4111 struct sock *sk = sock->sk; 4112 4113 return sk->sk_prot->recvmsg(sk, msg, size, flags); 4114 } 4115 EXPORT_SYMBOL(sock_common_recvmsg); 4116 4117 /* 4118 * Set socket options on an inet socket. 4119 */ 4120 int sock_common_setsockopt(struct socket *sock, int level, int optname, 4121 sockptr_t optval, unsigned int optlen) 4122 { 4123 struct sock *sk = sock->sk; 4124 4125 return READ_ONCE(sk->sk_prot)->setsockopt(sk, level, optname, optval, optlen); 4126 } 4127 EXPORT_SYMBOL(sock_common_setsockopt); 4128 4129 void sk_common_release(struct sock *sk) 4130 { 4131 if (sk->sk_prot->destroy) 4132 sk->sk_prot->destroy(sk); 4133 4134 /* 4135 * Observation: when sk_common_release is called, processes have 4136 * no access to socket. But net still has. 4137 * Step one, detach it from networking: 4138 * 4139 * A. Remove from hash tables. 4140 */ 4141 4142 sk->sk_prot->unhash(sk); 4143 4144 /* 4145 * In this point socket cannot receive new packets, but it is possible 4146 * that some packets are in flight because some CPU runs receiver and 4147 * did hash table lookup before we unhashed socket. They will achieve 4148 * receive queue and will be purged by socket destructor. 4149 * 4150 * Also we still have packets pending on receive queue and probably, 4151 * our own packets waiting in device queues. sock_destroy will drain 4152 * receive queue, but transmitted packets will delay socket destruction 4153 * until the last reference will be released. 4154 */ 4155 4156 sock_orphan(sk); 4157 4158 xfrm_sk_free_policy(sk); 4159 4160 sock_put(sk); 4161 } 4162 EXPORT_SYMBOL(sk_common_release); 4163 4164 void sk_get_meminfo(const struct sock *sk, u32 *mem) 4165 { 4166 memset(mem, 0, sizeof(*mem) * SK_MEMINFO_VARS); 4167 4168 mem[SK_MEMINFO_RMEM_ALLOC] = sk_rmem_alloc_get(sk); 4169 mem[SK_MEMINFO_RCVBUF] = READ_ONCE(sk->sk_rcvbuf); 4170 mem[SK_MEMINFO_WMEM_ALLOC] = sk_wmem_alloc_get(sk); 4171 mem[SK_MEMINFO_SNDBUF] = READ_ONCE(sk->sk_sndbuf); 4172 mem[SK_MEMINFO_FWD_ALLOC] = READ_ONCE(sk->sk_forward_alloc); 4173 mem[SK_MEMINFO_WMEM_QUEUED] = READ_ONCE(sk->sk_wmem_queued); 4174 mem[SK_MEMINFO_OPTMEM] = atomic_read(&sk->sk_omem_alloc); 4175 mem[SK_MEMINFO_BACKLOG] = READ_ONCE(sk->sk_backlog.len); 4176 mem[SK_MEMINFO_DROPS] = sk_drops_read(sk); 4177 } 4178 4179 #ifdef CONFIG_PROC_FS 4180 static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR); 4181 4182 int sock_prot_inuse_get(struct net *net, struct proto *prot) 4183 { 4184 int cpu, idx = prot->inuse_idx; 4185 int res = 0; 4186 4187 for_each_possible_cpu(cpu) 4188 res += per_cpu_ptr(net->core.prot_inuse, cpu)->val[idx]; 4189 4190 return res >= 0 ? res : 0; 4191 } 4192 EXPORT_SYMBOL_GPL(sock_prot_inuse_get); 4193 4194 int sock_inuse_get(struct net *net) 4195 { 4196 int cpu, res = 0; 4197 4198 for_each_possible_cpu(cpu) 4199 res += per_cpu_ptr(net->core.prot_inuse, cpu)->all; 4200 4201 return res; 4202 } 4203 4204 EXPORT_SYMBOL_GPL(sock_inuse_get); 4205 4206 static int __net_init sock_inuse_init_net(struct net *net) 4207 { 4208 net->core.prot_inuse = alloc_percpu(struct prot_inuse); 4209 if (net->core.prot_inuse == NULL) 4210 return -ENOMEM; 4211 return 0; 4212 } 4213 4214 static void __net_exit sock_inuse_exit_net(struct net *net) 4215 { 4216 free_percpu(net->core.prot_inuse); 4217 } 4218 4219 static struct pernet_operations net_inuse_ops = { 4220 .init = sock_inuse_init_net, 4221 .exit = sock_inuse_exit_net, 4222 }; 4223 4224 static __init int net_inuse_init(void) 4225 { 4226 if (register_pernet_subsys(&net_inuse_ops)) 4227 panic("Cannot initialize net inuse counters"); 4228 4229 return 0; 4230 } 4231 4232 core_initcall(net_inuse_init); 4233 4234 static int assign_proto_idx(struct proto *prot) 4235 { 4236 prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR); 4237 4238 if (unlikely(prot->inuse_idx == PROTO_INUSE_NR)) { 4239 pr_err("PROTO_INUSE_NR exhausted\n"); 4240 return -ENOSPC; 4241 } 4242 4243 set_bit(prot->inuse_idx, proto_inuse_idx); 4244 return 0; 4245 } 4246 4247 static void release_proto_idx(struct proto *prot) 4248 { 4249 if (prot->inuse_idx != PROTO_INUSE_NR) 4250 clear_bit(prot->inuse_idx, proto_inuse_idx); 4251 } 4252 #else 4253 static inline int assign_proto_idx(struct proto *prot) 4254 { 4255 return 0; 4256 } 4257 4258 static inline void release_proto_idx(struct proto *prot) 4259 { 4260 } 4261 4262 #endif 4263 4264 static void tw_prot_cleanup(struct timewait_sock_ops *twsk_prot) 4265 { 4266 if (!twsk_prot) 4267 return; 4268 kfree(twsk_prot->twsk_slab_name); 4269 twsk_prot->twsk_slab_name = NULL; 4270 kmem_cache_destroy(twsk_prot->twsk_slab); 4271 twsk_prot->twsk_slab = NULL; 4272 } 4273 4274 static int tw_prot_init(const struct proto *prot) 4275 { 4276 struct timewait_sock_ops *twsk_prot = prot->twsk_prot; 4277 4278 if (!twsk_prot) 4279 return 0; 4280 4281 twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s", 4282 prot->name); 4283 if (!twsk_prot->twsk_slab_name) 4284 return -ENOMEM; 4285 4286 twsk_prot->twsk_slab = 4287 kmem_cache_create(twsk_prot->twsk_slab_name, 4288 twsk_prot->twsk_obj_size, 0, 4289 SLAB_ACCOUNT | prot->slab_flags, 4290 NULL); 4291 if (!twsk_prot->twsk_slab) { 4292 pr_crit("%s: Can't create timewait sock SLAB cache!\n", 4293 prot->name); 4294 return -ENOMEM; 4295 } 4296 4297 return 0; 4298 } 4299 4300 static void req_prot_cleanup(struct request_sock_ops *rsk_prot) 4301 { 4302 if (!rsk_prot) 4303 return; 4304 kfree(rsk_prot->slab_name); 4305 rsk_prot->slab_name = NULL; 4306 kmem_cache_destroy(rsk_prot->slab); 4307 rsk_prot->slab = NULL; 4308 } 4309 4310 static int req_prot_init(const struct proto *prot) 4311 { 4312 struct request_sock_ops *rsk_prot = prot->rsk_prot; 4313 4314 if (!rsk_prot) 4315 return 0; 4316 4317 rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s", 4318 prot->name); 4319 if (!rsk_prot->slab_name) 4320 return -ENOMEM; 4321 4322 rsk_prot->slab = kmem_cache_create(rsk_prot->slab_name, 4323 rsk_prot->obj_size, 0, 4324 SLAB_ACCOUNT | prot->slab_flags, 4325 NULL); 4326 4327 if (!rsk_prot->slab) { 4328 pr_crit("%s: Can't create request sock SLAB cache!\n", 4329 prot->name); 4330 return -ENOMEM; 4331 } 4332 return 0; 4333 } 4334 4335 int proto_register(struct proto *prot, int alloc_slab) 4336 { 4337 int ret = -ENOBUFS; 4338 4339 if (prot->memory_allocated && !prot->sysctl_mem) { 4340 pr_err("%s: missing sysctl_mem\n", prot->name); 4341 return -EINVAL; 4342 } 4343 if (prot->memory_allocated && !prot->per_cpu_fw_alloc) { 4344 pr_err("%s: missing per_cpu_fw_alloc\n", prot->name); 4345 return -EINVAL; 4346 } 4347 if (alloc_slab) { 4348 struct kmem_cache_args args = { 4349 .useroffset = prot->useroffset, 4350 .usersize = prot->usersize, 4351 .freeptr_offset = prot->freeptr_offset, 4352 .use_freeptr_offset = !!prot->freeptr_offset, 4353 }; 4354 4355 prot->slab = kmem_cache_create(prot->name, prot->obj_size, 4356 &args, 4357 SLAB_HWCACHE_ALIGN | SLAB_ACCOUNT | 4358 prot->slab_flags); 4359 if (prot->slab == NULL) { 4360 pr_crit("%s: Can't create sock SLAB cache!\n", 4361 prot->name); 4362 goto out; 4363 } 4364 4365 if (req_prot_init(prot)) 4366 goto out_free_request_sock_slab; 4367 4368 if (tw_prot_init(prot)) 4369 goto out_free_timewait_sock_slab; 4370 } 4371 4372 mutex_lock(&proto_list_mutex); 4373 ret = assign_proto_idx(prot); 4374 if (ret) { 4375 mutex_unlock(&proto_list_mutex); 4376 goto out_free_timewait_sock_slab; 4377 } 4378 list_add(&prot->node, &proto_list); 4379 mutex_unlock(&proto_list_mutex); 4380 return ret; 4381 4382 out_free_timewait_sock_slab: 4383 if (alloc_slab) 4384 tw_prot_cleanup(prot->twsk_prot); 4385 out_free_request_sock_slab: 4386 if (alloc_slab) { 4387 req_prot_cleanup(prot->rsk_prot); 4388 4389 kmem_cache_destroy(prot->slab); 4390 prot->slab = NULL; 4391 } 4392 out: 4393 return ret; 4394 } 4395 EXPORT_SYMBOL(proto_register); 4396 4397 void proto_unregister(struct proto *prot) 4398 { 4399 mutex_lock(&proto_list_mutex); 4400 release_proto_idx(prot); 4401 list_del(&prot->node); 4402 mutex_unlock(&proto_list_mutex); 4403 4404 kmem_cache_destroy(prot->slab); 4405 prot->slab = NULL; 4406 4407 req_prot_cleanup(prot->rsk_prot); 4408 tw_prot_cleanup(prot->twsk_prot); 4409 } 4410 EXPORT_SYMBOL(proto_unregister); 4411 4412 int sock_load_diag_module(int family, int protocol) 4413 { 4414 if (!protocol) { 4415 if (!sock_is_registered(family)) 4416 return -ENOENT; 4417 4418 return request_module("net-pf-%d-proto-%d-type-%d", PF_NETLINK, 4419 NETLINK_SOCK_DIAG, family); 4420 } 4421 4422 #ifdef CONFIG_INET 4423 if (family == AF_INET && 4424 protocol != IPPROTO_RAW && 4425 protocol < MAX_INET_PROTOS && 4426 !rcu_access_pointer(inet_protos[protocol])) 4427 return -ENOENT; 4428 #endif 4429 4430 return request_module("net-pf-%d-proto-%d-type-%d-%d", PF_NETLINK, 4431 NETLINK_SOCK_DIAG, family, protocol); 4432 } 4433 EXPORT_SYMBOL(sock_load_diag_module); 4434 4435 #ifdef CONFIG_PROC_FS 4436 static void *proto_seq_start(struct seq_file *seq, loff_t *pos) 4437 __acquires(proto_list_mutex) 4438 { 4439 mutex_lock(&proto_list_mutex); 4440 return seq_list_start_head(&proto_list, *pos); 4441 } 4442 4443 static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos) 4444 { 4445 return seq_list_next(v, &proto_list, pos); 4446 } 4447 4448 static void proto_seq_stop(struct seq_file *seq, void *v) 4449 __releases(proto_list_mutex) 4450 { 4451 mutex_unlock(&proto_list_mutex); 4452 } 4453 4454 static char proto_method_implemented(const void *method) 4455 { 4456 return method == NULL ? 'n' : 'y'; 4457 } 4458 static long sock_prot_memory_allocated(struct proto *proto) 4459 { 4460 return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L; 4461 } 4462 4463 static const char *sock_prot_memory_pressure(struct proto *proto) 4464 { 4465 return proto->memory_pressure != NULL ? 4466 proto_memory_pressure(proto) ? "yes" : "no" : "NI"; 4467 } 4468 4469 static void proto_seq_printf(struct seq_file *seq, struct proto *proto) 4470 { 4471 4472 seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s " 4473 "%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n", 4474 proto->name, 4475 proto->obj_size, 4476 sock_prot_inuse_get(seq_file_net(seq), proto), 4477 sock_prot_memory_allocated(proto), 4478 sock_prot_memory_pressure(proto), 4479 proto->max_header, 4480 proto->slab == NULL ? "no" : "yes", 4481 module_name(proto->owner), 4482 proto_method_implemented(proto->close), 4483 proto_method_implemented(proto->connect), 4484 proto_method_implemented(proto->disconnect), 4485 proto_method_implemented(proto->accept), 4486 proto_method_implemented(proto->ioctl), 4487 proto_method_implemented(proto->init), 4488 proto_method_implemented(proto->destroy), 4489 proto_method_implemented(proto->shutdown), 4490 proto_method_implemented(proto->setsockopt), 4491 proto_method_implemented(proto->getsockopt), 4492 proto_method_implemented(proto->sendmsg), 4493 proto_method_implemented(proto->recvmsg), 4494 proto_method_implemented(proto->bind), 4495 proto_method_implemented(proto->backlog_rcv), 4496 proto_method_implemented(proto->hash), 4497 proto_method_implemented(proto->unhash), 4498 proto_method_implemented(proto->get_port), 4499 proto_method_implemented(proto->enter_memory_pressure)); 4500 } 4501 4502 static int proto_seq_show(struct seq_file *seq, void *v) 4503 { 4504 if (v == &proto_list) 4505 seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s", 4506 "protocol", 4507 "size", 4508 "sockets", 4509 "memory", 4510 "press", 4511 "maxhdr", 4512 "slab", 4513 "module", 4514 "cl co di ac io in de sh ss gs se re bi br ha uh gp em\n"); 4515 else 4516 proto_seq_printf(seq, list_entry(v, struct proto, node)); 4517 return 0; 4518 } 4519 4520 static const struct seq_operations proto_seq_ops = { 4521 .start = proto_seq_start, 4522 .next = proto_seq_next, 4523 .stop = proto_seq_stop, 4524 .show = proto_seq_show, 4525 }; 4526 4527 static __net_init int proto_init_net(struct net *net) 4528 { 4529 if (!proc_create_net("protocols", 0444, net->proc_net, &proto_seq_ops, 4530 sizeof(struct seq_net_private))) 4531 return -ENOMEM; 4532 4533 return 0; 4534 } 4535 4536 static __net_exit void proto_exit_net(struct net *net) 4537 { 4538 remove_proc_entry("protocols", net->proc_net); 4539 } 4540 4541 4542 static __net_initdata struct pernet_operations proto_net_ops = { 4543 .init = proto_init_net, 4544 .exit = proto_exit_net, 4545 }; 4546 4547 static int __init proto_init(void) 4548 { 4549 return register_pernet_subsys(&proto_net_ops); 4550 } 4551 4552 subsys_initcall(proto_init); 4553 4554 #endif /* PROC_FS */ 4555 4556 #ifdef CONFIG_NET_RX_BUSY_POLL 4557 bool sk_busy_loop_end(void *p, unsigned long start_time) 4558 { 4559 struct sock *sk = p; 4560 4561 if (!skb_queue_empty_lockless(&sk->sk_receive_queue)) 4562 return true; 4563 4564 if (sk_is_udp(sk) && 4565 !skb_queue_empty_lockless(&udp_sk(sk)->reader_queue)) 4566 return true; 4567 4568 return sk_busy_loop_timeout(sk, start_time); 4569 } 4570 EXPORT_SYMBOL(sk_busy_loop_end); 4571 #endif /* CONFIG_NET_RX_BUSY_POLL */ 4572 4573 int sock_bind_add(struct sock *sk, struct sockaddr_unsized *addr, int addr_len) 4574 { 4575 if (!sk->sk_prot->bind_add) 4576 return -EOPNOTSUPP; 4577 return sk->sk_prot->bind_add(sk, addr, addr_len); 4578 } 4579 EXPORT_SYMBOL(sock_bind_add); 4580 4581 /* Copy 'size' bytes from userspace and return `size` back to userspace */ 4582 int sock_ioctl_inout(struct sock *sk, unsigned int cmd, 4583 void __user *arg, void *karg, size_t size) 4584 { 4585 int ret; 4586 4587 if (copy_from_user(karg, arg, size)) 4588 return -EFAULT; 4589 4590 ret = READ_ONCE(sk->sk_prot)->ioctl(sk, cmd, karg); 4591 if (ret) 4592 return ret; 4593 4594 if (copy_to_user(arg, karg, size)) 4595 return -EFAULT; 4596 4597 return 0; 4598 } 4599 EXPORT_SYMBOL(sock_ioctl_inout); 4600 4601 /* This is the most common ioctl prep function, where the result (4 bytes) is 4602 * copied back to userspace if the ioctl() returns successfully. No input is 4603 * copied from userspace as input argument. 4604 */ 4605 static int sock_ioctl_out(struct sock *sk, unsigned int cmd, void __user *arg) 4606 { 4607 int ret, karg = 0; 4608 4609 ret = READ_ONCE(sk->sk_prot)->ioctl(sk, cmd, &karg); 4610 if (ret) 4611 return ret; 4612 4613 return put_user(karg, (int __user *)arg); 4614 } 4615 4616 /* A wrapper around sock ioctls, which copies the data from userspace 4617 * (depending on the protocol/ioctl), and copies back the result to userspace. 4618 * The main motivation for this function is to pass kernel memory to the 4619 * protocol ioctl callbacks, instead of userspace memory. 4620 */ 4621 int sk_ioctl(struct sock *sk, unsigned int cmd, void __user *arg) 4622 { 4623 int rc = 1; 4624 4625 if (sk->sk_type == SOCK_RAW && sk->sk_family == AF_INET) 4626 rc = ipmr_sk_ioctl(sk, cmd, arg); 4627 else if (sk->sk_type == SOCK_RAW && sk->sk_family == AF_INET6) 4628 rc = ip6mr_sk_ioctl(sk, cmd, arg); 4629 else if (sk_is_phonet(sk)) 4630 rc = phonet_sk_ioctl(sk, cmd, arg); 4631 4632 /* If ioctl was processed, returns its value */ 4633 if (rc <= 0) 4634 return rc; 4635 4636 /* Otherwise call the default handler */ 4637 return sock_ioctl_out(sk, cmd, arg); 4638 } 4639 EXPORT_SYMBOL(sk_ioctl); 4640 4641 static int __init sock_struct_check(void) 4642 { 4643 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_drops); 4644 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_peek_off); 4645 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_error_queue); 4646 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_receive_queue); 4647 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_backlog); 4648 4649 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rx_dst); 4650 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rx_dst_ifindex); 4651 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rx_dst_cookie); 4652 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rcvbuf); 4653 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_filter); 4654 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_wq); 4655 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_data_ready); 4656 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rcvtimeo); 4657 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rcvlowat); 4658 4659 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rxtx, sk_err); 4660 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rxtx, sk_socket); 4661 #ifdef CONFIG_MEMCG 4662 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rxtx, sk_memcg); 4663 #endif 4664 4665 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rxtx, sk_lock); 4666 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rxtx, sk_reserved_mem); 4667 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rxtx, sk_forward_alloc); 4668 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rxtx, sk_tsflags); 4669 4670 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_omem_alloc); 4671 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_omem_alloc); 4672 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_err_soft); 4673 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_wmem_queued); 4674 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_wmem_alloc); 4675 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_tsq_flags); 4676 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_send_head); 4677 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_write_queue); 4678 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_write_pending); 4679 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_frag); 4680 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_timer); 4681 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_pacing_rate); 4682 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_zckey); 4683 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_tskey); 4684 4685 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_dst_pending_confirm); 4686 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_pacing_status); 4687 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_max_pacing_rate); 4688 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_sndtimeo); 4689 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_priority); 4690 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_mark); 4691 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_uid); 4692 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_protocol); 4693 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_dst_cache); 4694 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_route_caps); 4695 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_gso_type); 4696 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_gso_max_size); 4697 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_allocation); 4698 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_txhash); 4699 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_sndbuf); 4700 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_gso_max_segs); 4701 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_pacing_shift); 4702 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_use_task_frag); 4703 return 0; 4704 } 4705 4706 core_initcall(sock_struct_check); 4707