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) 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_KERNEL); 2434 sock_inuse_add(net, 1); 2435 } 2436 EXPORT_SYMBOL_GPL(sk_net_refcnt_upgrade); 2437 2438 void sk_destruct(struct sock *sk) 2439 { 2440 bool use_call_rcu = sock_flag(sk, SOCK_RCU_FREE); 2441 2442 if (rcu_access_pointer(sk->sk_reuseport_cb)) { 2443 reuseport_detach_sock(sk); 2444 use_call_rcu = true; 2445 } 2446 2447 if (use_call_rcu) 2448 call_rcu(&sk->sk_rcu, __sk_destruct); 2449 else 2450 __sk_destruct(&sk->sk_rcu); 2451 } 2452 2453 static void __sk_free(struct sock *sk) 2454 { 2455 if (likely(sk->sk_net_refcnt)) 2456 sock_inuse_add(sock_net(sk), -1); 2457 2458 if (unlikely(sk->sk_net_refcnt && sock_diag_has_destroy_listeners(sk))) 2459 sock_diag_broadcast_destroy(sk); 2460 else 2461 sk_destruct(sk); 2462 } 2463 2464 void sk_free(struct sock *sk) 2465 { 2466 /* 2467 * We subtract one from sk_wmem_alloc and can know if 2468 * some packets are still in some tx queue. 2469 * If not null, sock_wfree() will call __sk_free(sk) later 2470 */ 2471 if (refcount_dec_and_test(&sk->sk_wmem_alloc)) 2472 __sk_free(sk); 2473 } 2474 EXPORT_SYMBOL(sk_free); 2475 2476 static void sk_init_common(struct sock *sk) 2477 { 2478 skb_queue_head_init(&sk->sk_receive_queue); 2479 skb_queue_head_init(&sk->sk_write_queue); 2480 skb_queue_head_init(&sk->sk_error_queue); 2481 2482 rwlock_init(&sk->sk_callback_lock); 2483 lockdep_set_class_and_name(&sk->sk_receive_queue.lock, 2484 af_rlock_keys + sk->sk_family, 2485 af_family_rlock_key_strings[sk->sk_family]); 2486 lockdep_set_class_and_name(&sk->sk_write_queue.lock, 2487 af_wlock_keys + sk->sk_family, 2488 af_family_wlock_key_strings[sk->sk_family]); 2489 lockdep_set_class_and_name(&sk->sk_error_queue.lock, 2490 af_elock_keys + sk->sk_family, 2491 af_family_elock_key_strings[sk->sk_family]); 2492 if (sk->sk_kern_sock) 2493 lockdep_set_class_and_name(&sk->sk_callback_lock, 2494 af_kern_callback_keys + sk->sk_family, 2495 af_family_kern_clock_key_strings[sk->sk_family]); 2496 else 2497 lockdep_set_class_and_name(&sk->sk_callback_lock, 2498 af_callback_keys + sk->sk_family, 2499 af_family_clock_key_strings[sk->sk_family]); 2500 } 2501 2502 /** 2503 * sk_clone - clone a socket 2504 * @sk: the socket to clone 2505 * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) 2506 * @lock: if true, lock the cloned sk 2507 * 2508 * If @lock is true, the clone is locked by bh_lock_sock(), and 2509 * caller must unlock socket even in error path by bh_unlock_sock(). 2510 */ 2511 struct sock *sk_clone(const struct sock *sk, const gfp_t priority, 2512 bool lock) 2513 { 2514 struct proto *prot = READ_ONCE(sk->sk_prot); 2515 struct sk_filter *filter; 2516 bool is_charged = true; 2517 struct sock *newsk; 2518 2519 newsk = sk_prot_alloc(prot, priority, sk->sk_family); 2520 if (!newsk) 2521 goto out; 2522 2523 sock_copy(newsk, sk); 2524 2525 newsk->sk_prot_creator = prot; 2526 #ifdef CONFIG_BPF_SYSCALL 2527 RCU_INIT_POINTER(newsk->sk_bpf_storage, NULL); 2528 #endif 2529 #if IS_ENABLED(CONFIG_INET_PSP) 2530 DEBUG_NET_WARN_ON_ONCE(rcu_access_pointer(sk->psp_assoc)); 2531 #endif 2532 2533 /* SANITY */ 2534 if (likely(newsk->sk_net_refcnt)) { 2535 get_net_track(sock_net(newsk), &newsk->ns_tracker, priority); 2536 sock_inuse_add(sock_net(newsk), 1); 2537 } else { 2538 /* Kernel sockets are not elevating the struct net refcount. 2539 * Instead, use a tracker to more easily detect if a layer 2540 * is not properly dismantling its kernel sockets at netns 2541 * destroy time. 2542 */ 2543 net_passive_inc(sock_net(newsk)); 2544 __netns_tracker_alloc(sock_net(newsk), &newsk->ns_tracker, 2545 false, priority); 2546 } 2547 2548 sk_node_init(&newsk->sk_node); 2549 sock_lock_init(newsk); 2550 spin_lock_init(&newsk->sk_peer_lock); 2551 2552 if (lock) 2553 bh_lock_sock(newsk); 2554 2555 newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL; 2556 newsk->sk_backlog.len = 0; 2557 2558 atomic_set(&newsk->sk_rmem_alloc, 0); 2559 2560 refcount_set(&newsk->sk_wmem_alloc, SK_WMEM_ALLOC_BIAS); 2561 2562 atomic_set(&newsk->sk_omem_alloc, 0); 2563 sk_init_common(newsk); 2564 2565 newsk->sk_dst_cache = NULL; 2566 newsk->sk_dst_pending_confirm = 0; 2567 newsk->sk_wmem_queued = 0; 2568 newsk->sk_forward_alloc = 0; 2569 newsk->sk_reserved_mem = 0; 2570 DEBUG_NET_WARN_ON_ONCE(newsk->sk_drop_counters); 2571 sk_drops_reset(newsk); 2572 newsk->sk_send_head = NULL; 2573 newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK; 2574 atomic_set(&newsk->sk_zckey, 0); 2575 2576 sock_reset_flag(newsk, SOCK_DONE); 2577 2578 #ifdef CONFIG_MEMCG 2579 /* sk->sk_memcg will be populated at accept() time */ 2580 newsk->sk_memcg = NULL; 2581 #endif 2582 2583 cgroup_sk_clone(&newsk->sk_cgrp_data); 2584 2585 RCU_INIT_POINTER(newsk->sk_reuseport_cb, NULL); 2586 2587 if (sock_needs_netstamp(sk) && newsk->sk_flags & SK_FLAGS_TIMESTAMP) 2588 net_enable_timestamp(); 2589 2590 rcu_read_lock(); 2591 filter = rcu_dereference(sk->sk_filter); 2592 if (filter != NULL) 2593 /* though it's an empty new sock, the charging may fail 2594 * if sysctl_optmem_max was changed between creation of 2595 * original socket and cloning 2596 */ 2597 is_charged = sk_filter_charge(newsk, filter); 2598 RCU_INIT_POINTER(newsk->sk_filter, filter); 2599 rcu_read_unlock(); 2600 2601 if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) { 2602 /* We need to make sure that we don't uncharge the new 2603 * socket if we couldn't charge it in the first place 2604 * as otherwise we uncharge the parent's filter. 2605 */ 2606 if (!is_charged) 2607 RCU_INIT_POINTER(newsk->sk_filter, NULL); 2608 2609 goto free; 2610 } 2611 2612 if (bpf_sk_storage_clone(sk, newsk)) 2613 goto free; 2614 2615 /* Clear sk_user_data if parent had the pointer tagged 2616 * as not suitable for copying when cloning. 2617 */ 2618 if (sk_user_data_is_nocopy(newsk)) 2619 newsk->sk_user_data = NULL; 2620 2621 newsk->sk_err = 0; 2622 newsk->sk_err_soft = 0; 2623 newsk->sk_priority = 0; 2624 newsk->sk_incoming_cpu = raw_smp_processor_id(); 2625 2626 /* Before updating sk_refcnt, we must commit prior changes to memory 2627 * (Documentation/RCU/rculist_nulls.rst for details) 2628 */ 2629 smp_wmb(); 2630 refcount_set(&newsk->sk_refcnt, 2); 2631 2632 sk_set_socket(newsk, NULL); 2633 sk_tx_queue_clear(newsk); 2634 sk_rx_queue_clear(newsk); 2635 RCU_INIT_POINTER(newsk->sk_wq, NULL); 2636 2637 if (newsk->sk_prot->sockets_allocated) 2638 sk_sockets_allocated_inc(newsk); 2639 out: 2640 return newsk; 2641 free: 2642 /* It is still raw copy of parent, so invalidate 2643 * destructor and make plain sk_free() 2644 */ 2645 newsk->sk_destruct = NULL; 2646 if (lock) 2647 bh_unlock_sock(newsk); 2648 sk_free(newsk); 2649 newsk = NULL; 2650 goto out; 2651 } 2652 EXPORT_SYMBOL_GPL(sk_clone); 2653 2654 static u32 sk_dst_gso_max_size(struct sock *sk, const struct net_device *dev) 2655 { 2656 bool is_ipv6 = false; 2657 u32 max_size; 2658 2659 #if IS_ENABLED(CONFIG_IPV6) 2660 is_ipv6 = (sk->sk_family == AF_INET6 && 2661 !ipv6_addr_v4mapped(&sk->sk_v6_rcv_saddr)); 2662 #endif 2663 /* pairs with the WRITE_ONCE() in netif_set_gso(_ipv4)_max_size() */ 2664 max_size = is_ipv6 ? READ_ONCE(dev->gso_max_size) : 2665 READ_ONCE(dev->gso_ipv4_max_size); 2666 if (max_size > GSO_LEGACY_MAX_SIZE && !sk_is_tcp(sk)) 2667 max_size = GSO_LEGACY_MAX_SIZE; 2668 2669 return max_size - (MAX_TCP_HEADER + 1); 2670 } 2671 2672 void sk_setup_caps(struct sock *sk, struct dst_entry *dst) 2673 { 2674 const struct net_device *dev; 2675 u32 max_segs = 1; 2676 2677 rcu_read_lock(); 2678 dev = dst_dev_rcu(dst); 2679 sk->sk_route_caps = dev->features; 2680 if (sk_is_tcp(sk)) { 2681 struct inet_connection_sock *icsk = inet_csk(sk); 2682 2683 sk->sk_route_caps |= NETIF_F_GSO; 2684 icsk->icsk_ack.dst_quick_ack = dst_metric(dst, RTAX_QUICKACK); 2685 } 2686 if (sk->sk_route_caps & NETIF_F_GSO) 2687 sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE; 2688 if (unlikely(sk->sk_gso_disabled)) 2689 sk->sk_route_caps &= ~NETIF_F_GSO_MASK; 2690 if (sk_can_gso(sk)) { 2691 if (dst->header_len && !xfrm_dst_offload_ok(dst)) { 2692 sk->sk_route_caps &= ~NETIF_F_GSO_MASK; 2693 } else { 2694 sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM; 2695 sk->sk_gso_max_size = sk_dst_gso_max_size(sk, dev); 2696 /* pairs with the WRITE_ONCE() in netif_set_gso_max_segs() */ 2697 max_segs = max_t(u32, READ_ONCE(dev->gso_max_segs), 1); 2698 } 2699 } 2700 sk->sk_gso_max_segs = max_segs; 2701 sk_dst_set(sk, dst); 2702 rcu_read_unlock(); 2703 } 2704 EXPORT_SYMBOL_GPL(sk_setup_caps); 2705 2706 bool sk_has_decrypt_user(const struct sock *sk) 2707 { 2708 return psp_sk_assoc(sk) || 2709 (sk_is_inet(sk) && inet_csk_has_ulp(sk)); /* for tls */ 2710 } 2711 2712 /* 2713 * Simple resource managers for sockets. 2714 */ 2715 2716 2717 /* 2718 * Write buffer destructor automatically called from kfree_skb. 2719 */ 2720 void sock_wfree(struct sk_buff *skb) 2721 { 2722 unsigned int len = skb->truesize; 2723 struct sock *sk = skb->sk; 2724 bool free; 2725 int old; 2726 2727 if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) { 2728 void (*sk_write_space)(struct sock *sk); 2729 2730 sk_write_space = READ_ONCE(sk->sk_write_space); 2731 2732 if (sock_flag(sk, SOCK_RCU_FREE) && 2733 sk_write_space == sock_def_write_space) { 2734 rcu_read_lock(); 2735 free = __refcount_sub_and_test(len, &sk->sk_wmem_alloc, 2736 &old); 2737 sock_def_write_space_wfree(sk, old - len); 2738 rcu_read_unlock(); 2739 if (unlikely(free)) 2740 __sk_free(sk); 2741 return; 2742 } 2743 2744 /* 2745 * Keep a reference on sk_wmem_alloc, this will be released 2746 * after sk_write_space() call 2747 */ 2748 WARN_ON(refcount_sub_and_test(len - 1, &sk->sk_wmem_alloc)); 2749 sk_write_space(sk); 2750 len = 1; 2751 } 2752 /* 2753 * if sk_wmem_alloc reaches 0, we must finish what sk_free() 2754 * could not do because of in-flight packets 2755 */ 2756 if (refcount_sub_and_test(len, &sk->sk_wmem_alloc)) 2757 __sk_free(sk); 2758 } 2759 EXPORT_SYMBOL(sock_wfree); 2760 2761 /* This variant of sock_wfree() is used by TCP, 2762 * since it sets SOCK_USE_WRITE_QUEUE. 2763 */ 2764 #ifdef CONFIG_INET 2765 void __sock_wfree(struct sk_buff *skb) 2766 { 2767 struct sock *sk = skb->sk; 2768 2769 if (refcount_sub_and_test(skb->truesize, &sk->sk_wmem_alloc)) 2770 __sk_free(sk); 2771 } 2772 EXPORT_SYMBOL_GPL(__sock_wfree); 2773 #endif 2774 2775 void skb_set_owner_w(struct sk_buff *skb, struct sock *sk) 2776 { 2777 int old_wmem; 2778 2779 skb_orphan(skb); 2780 #ifdef CONFIG_INET 2781 if (unlikely(!sk_fullsock(sk))) 2782 return skb_set_owner_edemux(skb, sk); 2783 #endif 2784 skb->sk = sk; 2785 skb->destructor = sock_wfree; 2786 skb_set_hash_from_sk(skb, sk); 2787 /* 2788 * We used to take a refcount on sk, but following operation 2789 * is enough to guarantee sk_free() won't free this sock until 2790 * all in-flight packets are completed 2791 */ 2792 __refcount_add(skb->truesize, &sk->sk_wmem_alloc, &old_wmem); 2793 2794 /* (old_wmem == SK_WMEM_ALLOC_BIAS) if no other TX packet for this socket 2795 * is in a host queue (qdisc, NIC queue). 2796 * Set skb->ooo_okay so that netdev_pick_tx() can choose a TX queue 2797 * based on XPS for better performance. 2798 * Otherwise clear ooo_okay to not risk Out Of Order delivery. 2799 */ 2800 skb->ooo_okay = (old_wmem == SK_WMEM_ALLOC_BIAS); 2801 } 2802 EXPORT_SYMBOL(skb_set_owner_w); 2803 2804 static bool can_skb_orphan_partial(const struct sk_buff *skb) 2805 { 2806 /* Drivers depend on in-order delivery for crypto offload, 2807 * partial orphan breaks out-of-order-OK logic. 2808 */ 2809 if (skb_is_decrypted(skb)) 2810 return false; 2811 2812 return (skb->destructor == sock_wfree || 2813 (IS_ENABLED(CONFIG_INET) && skb->destructor == tcp_wfree)); 2814 } 2815 2816 /* This helper is used by netem, as it can hold packets in its 2817 * delay queue. We want to allow the owner socket to send more 2818 * packets, as if they were already TX completed by a typical driver. 2819 * But we also want to keep skb->sk set because some packet schedulers 2820 * rely on it (sch_fq for example). 2821 */ 2822 void skb_orphan_partial(struct sk_buff *skb) 2823 { 2824 if (skb_is_tcp_pure_ack(skb)) 2825 return; 2826 2827 if (can_skb_orphan_partial(skb) && skb_set_owner_sk_safe(skb, skb->sk)) 2828 return; 2829 2830 skb_orphan(skb); 2831 } 2832 EXPORT_SYMBOL(skb_orphan_partial); 2833 2834 /* 2835 * Read buffer destructor automatically called from kfree_skb. 2836 */ 2837 void sock_rfree(struct sk_buff *skb) 2838 { 2839 struct sock *sk = skb->sk; 2840 unsigned int len = skb->truesize; 2841 2842 atomic_sub(len, &sk->sk_rmem_alloc); 2843 sk_mem_uncharge(sk, len); 2844 } 2845 EXPORT_SYMBOL(sock_rfree); 2846 2847 /* 2848 * Buffer destructor for skbs that are not used directly in read or write 2849 * path, e.g. for error handler skbs. Automatically called from kfree_skb. 2850 */ 2851 void sock_efree(struct sk_buff *skb) 2852 { 2853 sock_put(skb->sk); 2854 } 2855 EXPORT_SYMBOL(sock_efree); 2856 2857 /* Buffer destructor for prefetch/receive path where reference count may 2858 * not be held, e.g. for listen sockets. 2859 */ 2860 #ifdef CONFIG_INET 2861 void sock_pfree(struct sk_buff *skb) 2862 { 2863 struct sock *sk = skb->sk; 2864 2865 if (!sk_is_refcounted(sk)) 2866 return; 2867 2868 if (sk->sk_state == TCP_NEW_SYN_RECV && inet_reqsk(sk)->syncookie) { 2869 inet_reqsk(sk)->rsk_listener = NULL; 2870 reqsk_free(inet_reqsk(sk)); 2871 return; 2872 } 2873 2874 sock_gen_put(sk); 2875 } 2876 EXPORT_SYMBOL(sock_pfree); 2877 #endif /* CONFIG_INET */ 2878 2879 /* 2880 * Allocate a skb from the socket's send buffer. 2881 */ 2882 struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force, 2883 gfp_t priority) 2884 { 2885 if (force || 2886 refcount_read(&sk->sk_wmem_alloc) < READ_ONCE(sk->sk_sndbuf)) { 2887 struct sk_buff *skb = alloc_skb(size, priority); 2888 2889 if (skb) { 2890 skb_set_owner_w(skb, sk); 2891 return skb; 2892 } 2893 } 2894 return NULL; 2895 } 2896 EXPORT_SYMBOL(sock_wmalloc); 2897 2898 static void sock_ofree(struct sk_buff *skb) 2899 { 2900 struct sock *sk = skb->sk; 2901 2902 atomic_sub(skb->truesize, &sk->sk_omem_alloc); 2903 } 2904 2905 struct sk_buff *sock_omalloc(struct sock *sk, unsigned long size, 2906 gfp_t priority) 2907 { 2908 struct sk_buff *skb; 2909 2910 /* small safe race: SKB_TRUESIZE may differ from final skb->truesize */ 2911 if (atomic_read(&sk->sk_omem_alloc) + SKB_TRUESIZE(size) > 2912 READ_ONCE(sock_net(sk)->core.sysctl_optmem_max)) 2913 return NULL; 2914 2915 skb = alloc_skb(size, priority); 2916 if (!skb) 2917 return NULL; 2918 2919 atomic_add(skb->truesize, &sk->sk_omem_alloc); 2920 skb->sk = sk; 2921 skb->destructor = sock_ofree; 2922 return skb; 2923 } 2924 2925 /* 2926 * Allocate a memory block from the socket's option memory buffer. 2927 */ 2928 void *sock_kmalloc(struct sock *sk, int size, gfp_t priority) 2929 { 2930 int optmem_max = READ_ONCE(sock_net(sk)->core.sysctl_optmem_max); 2931 2932 if ((unsigned int)size <= optmem_max && 2933 atomic_read(&sk->sk_omem_alloc) + size < optmem_max) { 2934 void *mem; 2935 /* First do the add, to avoid the race if kmalloc 2936 * might sleep. 2937 */ 2938 atomic_add(size, &sk->sk_omem_alloc); 2939 mem = kmalloc(size, priority); 2940 if (mem) 2941 return mem; 2942 atomic_sub(size, &sk->sk_omem_alloc); 2943 } 2944 return NULL; 2945 } 2946 EXPORT_SYMBOL(sock_kmalloc); 2947 2948 /* 2949 * Duplicate the input "src" memory block using the socket's 2950 * option memory buffer. 2951 */ 2952 void *sock_kmemdup(struct sock *sk, const void *src, 2953 int size, gfp_t priority) 2954 { 2955 void *mem; 2956 2957 mem = sock_kmalloc(sk, size, priority); 2958 if (mem) 2959 memcpy(mem, src, size); 2960 return mem; 2961 } 2962 EXPORT_SYMBOL(sock_kmemdup); 2963 2964 /* Free an option memory block. Note, we actually want the inline 2965 * here as this allows gcc to detect the nullify and fold away the 2966 * condition entirely. 2967 */ 2968 static inline void __sock_kfree_s(struct sock *sk, void *mem, int size, 2969 const bool nullify) 2970 { 2971 if (WARN_ON_ONCE(!mem)) 2972 return; 2973 if (nullify) 2974 kfree_sensitive(mem); 2975 else 2976 kfree(mem); 2977 atomic_sub(size, &sk->sk_omem_alloc); 2978 } 2979 2980 void sock_kfree_s(struct sock *sk, void *mem, int size) 2981 { 2982 __sock_kfree_s(sk, mem, size, false); 2983 } 2984 EXPORT_SYMBOL(sock_kfree_s); 2985 2986 void sock_kzfree_s(struct sock *sk, void *mem, int size) 2987 { 2988 __sock_kfree_s(sk, mem, size, true); 2989 } 2990 EXPORT_SYMBOL(sock_kzfree_s); 2991 2992 /** 2993 * sk_set_nospace - tell the transport a writer is waiting for space 2994 * @sk: socket 2995 * 2996 * Must be called before the final check of the available send space, 2997 * so that the transport can not miss the request and forget to call 2998 * sk->sk_write_space() once space is available again. 2999 */ 3000 void sk_set_nospace(struct sock *sk) 3001 { 3002 struct socket *sock = sk->sk_socket; 3003 3004 if (!sock) 3005 return; 3006 /* Set SOCK_NOSPACE before tp->tcp_nospace (paired with 3007 * sk_clear_nospace() clearing tp->tcp_nospace before SOCK_NOSPACE) 3008 * so a concurrent clear cannot leave SOCK_NOSPACE set with 3009 * tp->tcp_nospace cleared. 3010 */ 3011 set_bit(SOCK_NOSPACE, &sock->flags); 3012 tcp_set_nospace(sk); 3013 } 3014 EXPORT_SYMBOL(sk_set_nospace); 3015 3016 /** 3017 * sk_clear_nospace - tell the transport no writer is waiting for space 3018 * @sk: socket 3019 * 3020 * Called from ->sk_write_space() handlers, once send space has been 3021 * made available to writers. 3022 */ 3023 void sk_clear_nospace(struct sock *sk) 3024 { 3025 struct socket *sock = sk->sk_socket; 3026 3027 if (!sock) 3028 return; 3029 tcp_clear_nospace(sk); 3030 clear_bit(SOCK_NOSPACE, &sock->flags); 3031 } 3032 EXPORT_SYMBOL(sk_clear_nospace); 3033 3034 /* It is almost wait_for_tcp_memory minus release_sock/lock_sock. 3035 I think, these locks should be removed for datagram sockets. 3036 */ 3037 static long sock_wait_for_wmem(struct sock *sk, long timeo) 3038 { 3039 DEFINE_WAIT(wait); 3040 3041 sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk); 3042 for (;;) { 3043 if (!timeo) 3044 break; 3045 if (signal_pending(current)) 3046 break; 3047 sk_set_nospace(sk); 3048 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); 3049 if (refcount_read(&sk->sk_wmem_alloc) < READ_ONCE(sk->sk_sndbuf)) 3050 break; 3051 if (READ_ONCE(sk->sk_shutdown) & SEND_SHUTDOWN) 3052 break; 3053 if (READ_ONCE(sk->sk_err)) 3054 break; 3055 timeo = schedule_timeout(timeo); 3056 } 3057 finish_wait(sk_sleep(sk), &wait); 3058 return timeo; 3059 } 3060 3061 3062 /* 3063 * Generic send/receive buffer handlers 3064 */ 3065 3066 struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len, 3067 unsigned long data_len, int noblock, 3068 int *errcode, int max_page_order) 3069 { 3070 struct sk_buff *skb; 3071 long timeo; 3072 int err; 3073 3074 timeo = sock_sndtimeo(sk, noblock); 3075 for (;;) { 3076 err = sock_error(sk); 3077 if (err != 0) 3078 goto failure; 3079 3080 err = -EPIPE; 3081 if (READ_ONCE(sk->sk_shutdown) & SEND_SHUTDOWN) 3082 goto failure; 3083 3084 if (sk_wmem_alloc_get(sk) < READ_ONCE(sk->sk_sndbuf)) 3085 break; 3086 3087 sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk); 3088 sk_set_nospace(sk); 3089 err = -EAGAIN; 3090 if (!timeo) 3091 goto failure; 3092 if (signal_pending(current)) 3093 goto interrupted; 3094 timeo = sock_wait_for_wmem(sk, timeo); 3095 } 3096 skb = alloc_skb_with_frags(header_len, data_len, max_page_order, 3097 errcode, sk->sk_allocation); 3098 if (skb) 3099 skb_set_owner_w(skb, sk); 3100 return skb; 3101 3102 interrupted: 3103 err = sock_intr_errno(timeo); 3104 failure: 3105 *errcode = err; 3106 return NULL; 3107 } 3108 EXPORT_SYMBOL(sock_alloc_send_pskb); 3109 3110 int __sock_cmsg_send(struct sock *sk, struct cmsghdr *cmsg, 3111 struct sockcm_cookie *sockc) 3112 { 3113 u32 tsflags; 3114 3115 BUILD_BUG_ON(SOF_TIMESTAMPING_LAST == (1 << 31)); 3116 3117 switch (cmsg->cmsg_type) { 3118 case SO_MARK: 3119 if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_RAW) && 3120 !ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) 3121 return -EPERM; 3122 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) 3123 return -EINVAL; 3124 sockc->mark = *(u32 *)CMSG_DATA(cmsg); 3125 break; 3126 case SO_TIMESTAMPING_OLD: 3127 case SO_TIMESTAMPING_NEW: 3128 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) 3129 return -EINVAL; 3130 3131 tsflags = *(u32 *)CMSG_DATA(cmsg); 3132 if (tsflags & ~SOF_TIMESTAMPING_TX_RECORD_MASK) 3133 return -EINVAL; 3134 3135 sockc->tsflags &= ~SOF_TIMESTAMPING_TX_RECORD_MASK; 3136 sockc->tsflags |= tsflags; 3137 break; 3138 case SCM_TXTIME: 3139 { 3140 ktime_t tmin; 3141 u64 txtime; 3142 3143 if (!sock_flag(sk, SOCK_TXTIME)) 3144 return -EINVAL; 3145 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u64))) 3146 return -EINVAL; 3147 3148 txtime = get_unaligned((u64 *)CMSG_DATA(cmsg)); 3149 3150 /* Allow sending without a delivery time: zero special case */ 3151 if (!txtime) { 3152 sockc->transmit_time = 0; 3153 break; 3154 } 3155 3156 switch (sk->sk_clockid) { 3157 case CLOCK_MONOTONIC: 3158 tmin = 1; 3159 break; 3160 case CLOCK_REALTIME: 3161 tmin = max(ktime_mono_to_real(0), 1); 3162 break; 3163 case CLOCK_TAI: 3164 tmin = max(ktime_mono_to_any(0, TK_OFFS_TAI), 1); 3165 break; 3166 default: 3167 tmin = 1; 3168 WARN_ON_ONCE(1); 3169 break; 3170 } 3171 3172 sockc->transmit_time = max_t(ktime_t, txtime, tmin); 3173 break; 3174 } 3175 case SCM_TS_OPT_ID: 3176 if (sk_is_tcp(sk)) 3177 return -EINVAL; 3178 tsflags = READ_ONCE(sk->sk_tsflags); 3179 if (!(tsflags & SOF_TIMESTAMPING_OPT_ID)) 3180 return -EINVAL; 3181 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) 3182 return -EINVAL; 3183 sockc->ts_opt_id = *(u32 *)CMSG_DATA(cmsg); 3184 sockc->tsflags |= SOCKCM_FLAG_TS_OPT_ID; 3185 break; 3186 /* SCM_RIGHTS and SCM_CREDENTIALS are semantically in SOL_UNIX. */ 3187 case SCM_RIGHTS: 3188 case SCM_CREDENTIALS: 3189 break; 3190 case SO_PRIORITY: 3191 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) 3192 return -EINVAL; 3193 if (!sk_set_prio_allowed(sk, *(u32 *)CMSG_DATA(cmsg))) 3194 return -EPERM; 3195 sockc->priority = *(u32 *)CMSG_DATA(cmsg); 3196 break; 3197 case SCM_DEVMEM_DMABUF: 3198 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) 3199 return -EINVAL; 3200 sockc->dmabuf_id = *(u32 *)CMSG_DATA(cmsg); 3201 break; 3202 default: 3203 return -EINVAL; 3204 } 3205 return 0; 3206 } 3207 EXPORT_SYMBOL(__sock_cmsg_send); 3208 3209 int sock_cmsg_send(struct sock *sk, struct msghdr *msg, 3210 struct sockcm_cookie *sockc) 3211 { 3212 struct cmsghdr *cmsg; 3213 int ret; 3214 3215 for_each_cmsghdr(cmsg, msg) { 3216 if (!CMSG_OK(msg, cmsg)) 3217 return -EINVAL; 3218 if (cmsg->cmsg_level != SOL_SOCKET) 3219 continue; 3220 ret = __sock_cmsg_send(sk, cmsg, sockc); 3221 if (ret) 3222 return ret; 3223 } 3224 return 0; 3225 } 3226 EXPORT_SYMBOL(sock_cmsg_send); 3227 3228 static void sk_enter_memory_pressure(struct sock *sk) 3229 { 3230 if (!sk->sk_prot->enter_memory_pressure) 3231 return; 3232 3233 sk->sk_prot->enter_memory_pressure(sk); 3234 } 3235 3236 static void sk_leave_memory_pressure(struct sock *sk) 3237 { 3238 if (sk->sk_prot->leave_memory_pressure) { 3239 INDIRECT_CALL_INET_1(sk->sk_prot->leave_memory_pressure, 3240 tcp_leave_memory_pressure, sk); 3241 } else { 3242 unsigned long *memory_pressure = sk->sk_prot->memory_pressure; 3243 3244 if (memory_pressure && READ_ONCE(*memory_pressure)) 3245 WRITE_ONCE(*memory_pressure, 0); 3246 } 3247 } 3248 3249 DEFINE_STATIC_KEY_FALSE(net_high_order_alloc_disable_key); 3250 3251 /** 3252 * skb_page_frag_refill - check that a page_frag contains enough room 3253 * @sz: minimum size of the fragment we want to get 3254 * @pfrag: pointer to page_frag 3255 * @gfp: priority for memory allocation 3256 * 3257 * Note: While this allocator tries to use high order pages, there is 3258 * no guarantee that allocations succeed. Therefore, @sz MUST be 3259 * less or equal than PAGE_SIZE. 3260 */ 3261 bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp) 3262 { 3263 if (pfrag->page) { 3264 if (page_ref_count(pfrag->page) == 1) { 3265 pfrag->offset = 0; 3266 return true; 3267 } 3268 if (pfrag->offset + sz <= pfrag->size) 3269 return true; 3270 put_page(pfrag->page); 3271 } 3272 3273 pfrag->offset = 0; 3274 if (SKB_FRAG_PAGE_ORDER && 3275 !static_branch_unlikely(&net_high_order_alloc_disable_key)) { 3276 /* Avoid direct reclaim but allow kswapd to wake */ 3277 pfrag->page = alloc_pages((gfp & ~__GFP_DIRECT_RECLAIM) | 3278 __GFP_COMP | __GFP_NOWARN | 3279 __GFP_NORETRY, 3280 SKB_FRAG_PAGE_ORDER); 3281 if (likely(pfrag->page)) { 3282 pfrag->size = PAGE_SIZE << SKB_FRAG_PAGE_ORDER; 3283 return true; 3284 } 3285 } 3286 pfrag->page = alloc_page(gfp); 3287 if (likely(pfrag->page)) { 3288 pfrag->size = PAGE_SIZE; 3289 return true; 3290 } 3291 return false; 3292 } 3293 EXPORT_SYMBOL(skb_page_frag_refill); 3294 3295 bool sk_page_frag_refill(struct sock *sk, struct page_frag *pfrag) 3296 { 3297 if (likely(skb_page_frag_refill(32U, pfrag, sk->sk_allocation))) 3298 return true; 3299 3300 if (!sk->sk_bypass_prot_mem) 3301 sk_enter_memory_pressure(sk); 3302 3303 sk_stream_moderate_sndbuf(sk); 3304 3305 return false; 3306 } 3307 EXPORT_SYMBOL(sk_page_frag_refill); 3308 3309 static void __lock_sock(struct sock *sk) 3310 __releases(&sk->sk_lock.slock) 3311 __acquires(&sk->sk_lock.slock) 3312 { 3313 DEFINE_WAIT(wait); 3314 3315 for (;;) { 3316 prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait, 3317 TASK_UNINTERRUPTIBLE); 3318 spin_unlock_bh(&sk->sk_lock.slock); 3319 schedule(); 3320 spin_lock_bh(&sk->sk_lock.slock); 3321 if (!sock_owned_by_user(sk)) 3322 break; 3323 } 3324 finish_wait(&sk->sk_lock.wq, &wait); 3325 } 3326 3327 void __release_sock(struct sock *sk) 3328 __releases(&sk->sk_lock.slock) 3329 __acquires(&sk->sk_lock.slock) 3330 { 3331 struct sk_buff *skb, *next; 3332 int nb = 0; 3333 3334 while ((skb = sk->sk_backlog.head) != NULL) { 3335 sk->sk_backlog.head = sk->sk_backlog.tail = NULL; 3336 3337 spin_unlock_bh(&sk->sk_lock.slock); 3338 3339 do { 3340 next = skb->next; 3341 prefetch(next); 3342 DEBUG_NET_WARN_ON_ONCE(skb_dst_is_noref(skb)); 3343 skb_mark_not_on_list(skb); 3344 sk_backlog_rcv(sk, skb); 3345 3346 skb = next; 3347 3348 if (!(++nb & 15)) 3349 cond_resched(); 3350 } while (skb); 3351 3352 spin_lock_bh(&sk->sk_lock.slock); 3353 } 3354 3355 /* 3356 * Doing the zeroing here guarantee we can not loop forever 3357 * while a wild producer attempts to flood us. 3358 */ 3359 sk->sk_backlog.len = 0; 3360 } 3361 3362 void __sk_flush_backlog(struct sock *sk) 3363 { 3364 spin_lock_bh(&sk->sk_lock.slock); 3365 __release_sock(sk); 3366 3367 if (sk->sk_prot->release_cb) 3368 INDIRECT_CALL_INET_1(sk->sk_prot->release_cb, 3369 tcp_release_cb, sk); 3370 3371 spin_unlock_bh(&sk->sk_lock.slock); 3372 } 3373 EXPORT_SYMBOL_GPL(__sk_flush_backlog); 3374 3375 /** 3376 * sk_wait_data - wait for data to arrive at sk_receive_queue 3377 * @sk: sock to wait on 3378 * @timeo: for how long 3379 * @skb: last skb seen on sk_receive_queue 3380 * 3381 * Now socket state including sk->sk_err is changed only under lock, 3382 * hence we may omit checks after joining wait queue. 3383 * We check receive queue before schedule() only as optimization; 3384 * it is very likely that release_sock() added new data. 3385 */ 3386 int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb) 3387 { 3388 DEFINE_WAIT_FUNC(wait, woken_wake_function); 3389 int rc; 3390 3391 add_wait_queue(sk_sleep(sk), &wait); 3392 sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk); 3393 rc = sk_wait_event(sk, timeo, skb_peek_tail(&sk->sk_receive_queue) != skb, &wait); 3394 sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk); 3395 remove_wait_queue(sk_sleep(sk), &wait); 3396 return rc; 3397 } 3398 EXPORT_SYMBOL(sk_wait_data); 3399 3400 /** 3401 * __sk_mem_raise_allocated - increase memory_allocated 3402 * @sk: socket 3403 * @size: memory size to allocate 3404 * @amt: pages to allocate 3405 * @kind: allocation type 3406 * 3407 * Similar to __sk_mem_schedule(), but does not update sk_forward_alloc. 3408 * 3409 * Unlike the globally shared limits among the sockets under same protocol, 3410 * consuming the budget of a memcg won't have direct effect on other ones. 3411 * So be optimistic about memcg's tolerance, and leave the callers to decide 3412 * whether or not to raise allocated through sk_under_memory_pressure() or 3413 * its variants. 3414 */ 3415 int __sk_mem_raise_allocated(struct sock *sk, int size, int amt, int kind) 3416 { 3417 bool memcg_enabled = false, charged = false; 3418 struct proto *prot = sk->sk_prot; 3419 long allocated = 0; 3420 3421 if (!sk->sk_bypass_prot_mem) { 3422 sk_memory_allocated_add(sk, amt); 3423 allocated = sk_memory_allocated(sk); 3424 } 3425 3426 if (mem_cgroup_sk_enabled(sk)) { 3427 memcg_enabled = true; 3428 charged = mem_cgroup_sk_charge(sk, amt, gfp_memcg_charge()); 3429 if (!charged) 3430 goto suppress_allocation; 3431 } 3432 3433 if (sk->sk_bypass_prot_mem) 3434 return 1; 3435 3436 /* Under limit. */ 3437 if (allocated <= sk_prot_mem_limits(sk, 0)) { 3438 sk_leave_memory_pressure(sk); 3439 return 1; 3440 } 3441 3442 /* Under pressure. */ 3443 if (allocated > sk_prot_mem_limits(sk, 1)) 3444 sk_enter_memory_pressure(sk); 3445 3446 /* Over hard limit. */ 3447 if (allocated > sk_prot_mem_limits(sk, 2)) 3448 goto suppress_allocation; 3449 3450 /* Guarantee minimum buffer size under pressure (either global 3451 * or memcg) to make sure features described in RFC 7323 (TCP 3452 * Extensions for High Performance) work properly. 3453 * 3454 * This rule does NOT stand when exceeds global or memcg's hard 3455 * limit, or else a DoS attack can be taken place by spawning 3456 * lots of sockets whose usage are under minimum buffer size. 3457 */ 3458 if (kind == SK_MEM_RECV) { 3459 if (atomic_read(&sk->sk_rmem_alloc) < sk_get_rmem0(sk, prot)) 3460 return 1; 3461 3462 } else { /* SK_MEM_SEND */ 3463 int wmem0 = sk_get_wmem0(sk, prot); 3464 3465 if (sk->sk_type == SOCK_STREAM) { 3466 if (sk->sk_wmem_queued < wmem0) 3467 return 1; 3468 } else if (refcount_read(&sk->sk_wmem_alloc) < wmem0) { 3469 return 1; 3470 } 3471 } 3472 3473 if (sk_has_memory_pressure(sk)) { 3474 u64 alloc; 3475 3476 /* The following 'average' heuristic is within the 3477 * scope of global accounting, so it only makes 3478 * sense for global memory pressure. 3479 */ 3480 if (!sk_under_global_memory_pressure(sk)) 3481 return 1; 3482 3483 /* Try to be fair among all the sockets under global 3484 * pressure by allowing the ones that below average 3485 * usage to raise. 3486 */ 3487 alloc = sk_sockets_allocated_read_positive(sk); 3488 if (sk_prot_mem_limits(sk, 2) > alloc * 3489 sk_mem_pages(sk->sk_wmem_queued + 3490 atomic_read(&sk->sk_rmem_alloc) + 3491 sk->sk_forward_alloc)) 3492 return 1; 3493 } 3494 3495 suppress_allocation: 3496 3497 if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) { 3498 sk_stream_moderate_sndbuf(sk); 3499 3500 /* Fail only if socket is _under_ its sndbuf. 3501 * In this case we cannot block, so that we have to fail. 3502 */ 3503 if (sk->sk_wmem_queued + size >= sk->sk_sndbuf) { 3504 /* Force charge with __GFP_NOFAIL */ 3505 if (memcg_enabled && !charged) 3506 mem_cgroup_sk_charge(sk, amt, 3507 gfp_memcg_charge() | __GFP_NOFAIL); 3508 return 1; 3509 } 3510 } 3511 3512 trace_sock_exceed_buf_limit(sk, prot, allocated, kind); 3513 3514 if (!sk->sk_bypass_prot_mem) 3515 sk_memory_allocated_sub(sk, amt); 3516 3517 if (charged) 3518 mem_cgroup_sk_uncharge(sk, amt); 3519 3520 return 0; 3521 } 3522 3523 /** 3524 * __sk_mem_schedule - increase sk_forward_alloc and memory_allocated 3525 * @sk: socket 3526 * @size: memory size to allocate 3527 * @kind: allocation type 3528 * 3529 * If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means 3530 * rmem allocation. This function assumes that protocols which have 3531 * memory_pressure use sk_wmem_queued as write buffer accounting. 3532 */ 3533 int __sk_mem_schedule(struct sock *sk, int size, int kind) 3534 { 3535 int ret, amt = sk_mem_pages(size); 3536 3537 sk_forward_alloc_add(sk, amt << PAGE_SHIFT); 3538 ret = __sk_mem_raise_allocated(sk, size, amt, kind); 3539 if (!ret) 3540 sk_forward_alloc_add(sk, -(amt << PAGE_SHIFT)); 3541 return ret; 3542 } 3543 EXPORT_SYMBOL(__sk_mem_schedule); 3544 3545 /** 3546 * __sk_mem_reduce_allocated - reclaim memory_allocated 3547 * @sk: socket 3548 * @amount: number of quanta 3549 * 3550 * Similar to __sk_mem_reclaim(), but does not update sk_forward_alloc 3551 */ 3552 void __sk_mem_reduce_allocated(struct sock *sk, int amount) 3553 { 3554 if (mem_cgroup_sk_enabled(sk)) 3555 mem_cgroup_sk_uncharge(sk, amount); 3556 3557 if (sk->sk_bypass_prot_mem) 3558 return; 3559 3560 sk_memory_allocated_sub(sk, amount); 3561 3562 if (sk_under_global_memory_pressure(sk) && 3563 (sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0))) 3564 sk_leave_memory_pressure(sk); 3565 } 3566 3567 /** 3568 * __sk_mem_reclaim - reclaim sk_forward_alloc and memory_allocated 3569 * @sk: socket 3570 * @amount: number of bytes (rounded down to a PAGE_SIZE multiple) 3571 */ 3572 void __sk_mem_reclaim(struct sock *sk, int amount) 3573 { 3574 amount >>= PAGE_SHIFT; 3575 sk_forward_alloc_add(sk, -(amount << PAGE_SHIFT)); 3576 __sk_mem_reduce_allocated(sk, amount); 3577 } 3578 EXPORT_SYMBOL(__sk_mem_reclaim); 3579 3580 void __sk_charge(struct sock *sk, gfp_t gfp) 3581 { 3582 int amt; 3583 3584 gfp |= __GFP_NOFAIL; 3585 if (mem_cgroup_from_sk(sk)) { 3586 /* The socket has not been accepted yet, no need 3587 * to look at newsk->sk_wmem_queued. 3588 */ 3589 amt = sk_mem_pages(sk->sk_forward_alloc + 3590 atomic_read(&sk->sk_rmem_alloc)); 3591 if (amt) 3592 mem_cgroup_sk_charge(sk, amt, gfp); 3593 } 3594 3595 kmem_cache_charge(sk, gfp); 3596 } 3597 3598 int sk_set_peek_off(struct sock *sk, int val) 3599 { 3600 WRITE_ONCE(sk->sk_peek_off, val); 3601 return 0; 3602 } 3603 EXPORT_SYMBOL_GPL(sk_set_peek_off); 3604 3605 /* 3606 * Set of default routines for initialising struct proto_ops when 3607 * the protocol does not support a particular function. In certain 3608 * cases where it makes no sense for a protocol to have a "do nothing" 3609 * function, some default processing is provided. 3610 */ 3611 3612 int sock_no_bind(struct socket *sock, struct sockaddr_unsized *saddr, int len) 3613 { 3614 return -EOPNOTSUPP; 3615 } 3616 EXPORT_SYMBOL(sock_no_bind); 3617 3618 int sock_no_connect(struct socket *sock, struct sockaddr_unsized *saddr, 3619 int len, int flags) 3620 { 3621 return -EOPNOTSUPP; 3622 } 3623 EXPORT_SYMBOL(sock_no_connect); 3624 3625 int sock_no_socketpair(struct socket *sock1, struct socket *sock2) 3626 { 3627 return -EOPNOTSUPP; 3628 } 3629 EXPORT_SYMBOL(sock_no_socketpair); 3630 3631 int sock_no_accept(struct socket *sock, struct socket *newsock, 3632 struct proto_accept_arg *arg) 3633 { 3634 return -EOPNOTSUPP; 3635 } 3636 EXPORT_SYMBOL(sock_no_accept); 3637 3638 int sock_no_getname(struct socket *sock, struct sockaddr *saddr, 3639 int peer) 3640 { 3641 return -EOPNOTSUPP; 3642 } 3643 EXPORT_SYMBOL(sock_no_getname); 3644 3645 int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) 3646 { 3647 return -EOPNOTSUPP; 3648 } 3649 EXPORT_SYMBOL(sock_no_ioctl); 3650 3651 int sock_no_listen(struct socket *sock, int backlog) 3652 { 3653 return -EOPNOTSUPP; 3654 } 3655 EXPORT_SYMBOL(sock_no_listen); 3656 3657 int sock_no_shutdown(struct socket *sock, int how) 3658 { 3659 return -EOPNOTSUPP; 3660 } 3661 EXPORT_SYMBOL(sock_no_shutdown); 3662 3663 int sock_no_sendmsg(struct socket *sock, struct msghdr *m, size_t len) 3664 { 3665 return -EOPNOTSUPP; 3666 } 3667 EXPORT_SYMBOL(sock_no_sendmsg); 3668 3669 int sock_no_sendmsg_locked(struct sock *sk, struct msghdr *m, size_t len) 3670 { 3671 return -EOPNOTSUPP; 3672 } 3673 EXPORT_SYMBOL(sock_no_sendmsg_locked); 3674 3675 int sock_no_recvmsg(struct socket *sock, struct msghdr *m, size_t len, 3676 int flags) 3677 { 3678 return -EOPNOTSUPP; 3679 } 3680 EXPORT_SYMBOL(sock_no_recvmsg); 3681 3682 int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma) 3683 { 3684 /* Mirror missing mmap method error code */ 3685 return -ENODEV; 3686 } 3687 EXPORT_SYMBOL(sock_no_mmap); 3688 3689 /* 3690 * When a file is received (via SCM_RIGHTS, etc), we must bump the 3691 * various sock-based usage counts. 3692 */ 3693 void __receive_sock(struct file *file) 3694 { 3695 struct socket *sock; 3696 3697 sock = sock_from_file(file); 3698 if (sock) { 3699 sock_update_netprioidx(&sock->sk->sk_cgrp_data); 3700 sock_update_classid(&sock->sk->sk_cgrp_data); 3701 } 3702 } 3703 3704 /* 3705 * Default Socket Callbacks 3706 */ 3707 3708 static void sock_def_wakeup(struct sock *sk) 3709 { 3710 struct socket_wq *wq; 3711 3712 rcu_read_lock(); 3713 wq = rcu_dereference(sk->sk_wq); 3714 if (skwq_has_sleeper(wq)) 3715 wake_up_interruptible_all(&wq->wait); 3716 rcu_read_unlock(); 3717 } 3718 3719 static void sock_def_error_report(struct sock *sk) 3720 { 3721 struct socket_wq *wq; 3722 3723 rcu_read_lock(); 3724 wq = rcu_dereference(sk->sk_wq); 3725 if (skwq_has_sleeper(wq)) 3726 wake_up_interruptible_poll(&wq->wait, EPOLLERR); 3727 sk_wake_async_rcu(sk, SOCK_WAKE_IO, POLL_ERR); 3728 rcu_read_unlock(); 3729 } 3730 3731 void sock_def_readable(struct sock *sk) 3732 { 3733 struct socket_wq *wq; 3734 3735 trace_sk_data_ready(sk); 3736 3737 rcu_read_lock(); 3738 wq = rcu_dereference(sk->sk_wq); 3739 if (skwq_has_sleeper(wq)) 3740 wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN | EPOLLPRI | 3741 EPOLLRDNORM | EPOLLRDBAND); 3742 sk_wake_async_rcu(sk, SOCK_WAKE_WAITD, POLL_IN); 3743 rcu_read_unlock(); 3744 } 3745 3746 static void sock_def_write_space(struct sock *sk) 3747 { 3748 struct socket_wq *wq; 3749 3750 rcu_read_lock(); 3751 3752 /* Do not wake up a writer until he can make "significant" 3753 * progress. --DaveM 3754 */ 3755 if (sock_writeable(sk)) { 3756 wq = rcu_dereference(sk->sk_wq); 3757 if (skwq_has_sleeper(wq)) 3758 wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT | 3759 EPOLLWRNORM | EPOLLWRBAND); 3760 3761 /* Should agree with poll, otherwise some programs break */ 3762 sk_wake_async_rcu(sk, SOCK_WAKE_SPACE, POLL_OUT); 3763 } 3764 3765 rcu_read_unlock(); 3766 } 3767 3768 /* An optimised version of sock_def_write_space(), should only be called 3769 * for SOCK_RCU_FREE sockets under RCU read section and after putting 3770 * ->sk_wmem_alloc. 3771 */ 3772 static void sock_def_write_space_wfree(struct sock *sk, int wmem_alloc) 3773 { 3774 /* Do not wake up a writer until he can make "significant" 3775 * progress. --DaveM 3776 */ 3777 if (__sock_writeable(sk, wmem_alloc)) { 3778 struct socket_wq *wq = rcu_dereference(sk->sk_wq); 3779 3780 /* rely on refcount_sub from sock_wfree() */ 3781 smp_mb__after_atomic(); 3782 if (wq && waitqueue_active(&wq->wait)) 3783 wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT | 3784 EPOLLWRNORM | EPOLLWRBAND); 3785 3786 /* Should agree with poll, otherwise some programs break */ 3787 sk_wake_async_rcu(sk, SOCK_WAKE_SPACE, POLL_OUT); 3788 } 3789 } 3790 3791 static void sock_def_destruct(struct sock *sk) 3792 { 3793 } 3794 3795 void sk_send_sigurg(struct sock *sk) 3796 { 3797 if (sk->sk_socket && sk->sk_socket->file) 3798 if (send_sigurg(sk->sk_socket->file)) 3799 sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI); 3800 } 3801 EXPORT_SYMBOL(sk_send_sigurg); 3802 3803 void sk_reset_timer(struct sock *sk, struct timer_list* timer, 3804 unsigned long expires) 3805 { 3806 if (!mod_timer(timer, expires)) 3807 sock_hold(sk); 3808 } 3809 EXPORT_SYMBOL(sk_reset_timer); 3810 3811 void sk_stop_timer(struct sock *sk, struct timer_list* timer) 3812 { 3813 if (timer_delete(timer)) 3814 __sock_put(sk); 3815 } 3816 EXPORT_SYMBOL(sk_stop_timer); 3817 3818 void sk_stop_timer_sync(struct sock *sk, struct timer_list *timer) 3819 { 3820 if (timer_delete_sync(timer)) 3821 __sock_put(sk); 3822 } 3823 EXPORT_SYMBOL(sk_stop_timer_sync); 3824 3825 void sock_init_data_uid(struct socket *sock, struct sock *sk, kuid_t uid) 3826 { 3827 sk_init_common(sk); 3828 sk->sk_send_head = NULL; 3829 3830 timer_setup(&sk->sk_timer, NULL, 0); 3831 3832 sk->sk_allocation = GFP_KERNEL; 3833 sk->sk_rcvbuf = READ_ONCE(sysctl_rmem_default); 3834 sk->sk_sndbuf = READ_ONCE(sysctl_wmem_default); 3835 sk->sk_state = TCP_CLOSE; 3836 sk->sk_use_task_frag = true; 3837 sk_set_socket(sk, sock); 3838 3839 sock_set_flag(sk, SOCK_ZAPPED); 3840 3841 if (sock) { 3842 sk->sk_type = sock->type; 3843 RCU_INIT_POINTER(sk->sk_wq, &sock->wq); 3844 sock->sk = sk; 3845 } else { 3846 RCU_INIT_POINTER(sk->sk_wq, NULL); 3847 } 3848 sk->sk_uid = uid; 3849 3850 sk->sk_state_change = sock_def_wakeup; 3851 sk->sk_data_ready = sock_def_readable; 3852 sk->sk_write_space = sock_def_write_space; 3853 sk->sk_error_report = sock_def_error_report; 3854 sk->sk_destruct = sock_def_destruct; 3855 3856 sk->sk_frag.page = NULL; 3857 sk->sk_frag.offset = 0; 3858 sk->sk_peek_off = -1; 3859 3860 memset(sk->sk_peer_pid, 0, sizeof(sk->sk_peer_pid)); 3861 sk->sk_peer_cred = NULL; 3862 spin_lock_init(&sk->sk_peer_lock); 3863 3864 sk->sk_write_pending = 0; 3865 sk->sk_rcvlowat = 1; 3866 sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT; 3867 sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT; 3868 3869 sk->sk_stamp = SK_DEFAULT_STAMP; 3870 #if BITS_PER_LONG==32 3871 seqlock_init(&sk->sk_stamp_seq); 3872 #endif 3873 atomic_set(&sk->sk_zckey, 0); 3874 3875 #ifdef CONFIG_NET_RX_BUSY_POLL 3876 sk->sk_napi_id = 0; 3877 sk->sk_ll_usec = READ_ONCE(sysctl_net_busy_read); 3878 #endif 3879 3880 sk->sk_max_pacing_rate = ~0UL; 3881 sk->sk_pacing_rate = ~0UL; 3882 WRITE_ONCE(sk->sk_pacing_shift, 10); 3883 sk->sk_incoming_cpu = -1; 3884 3885 sk_rx_queue_clear(sk); 3886 /* 3887 * Before updating sk_refcnt, we must commit prior changes to memory 3888 * (Documentation/RCU/rculist_nulls.rst for details) 3889 */ 3890 smp_wmb(); 3891 refcount_set(&sk->sk_refcnt, 1); 3892 sk_drops_reset(sk); 3893 } 3894 EXPORT_SYMBOL(sock_init_data_uid); 3895 3896 void sock_init_data(struct socket *sock, struct sock *sk) 3897 { 3898 kuid_t uid = sock ? 3899 SOCK_INODE(sock)->i_uid : 3900 make_kuid(sock_net(sk)->user_ns, 0); 3901 3902 sock_init_data_uid(sock, sk, uid); 3903 } 3904 EXPORT_SYMBOL(sock_init_data); 3905 3906 void noinline lock_sock_nested(struct sock *sk, int subclass) 3907 { 3908 /* The sk_lock has mutex_lock() semantics here. */ 3909 mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_); 3910 3911 might_sleep(); 3912 #ifdef CONFIG_64BIT 3913 if (sizeof(struct slock_owned) == sizeof(long)) { 3914 socket_lock_t tmp = { 3915 .slock = __SPIN_LOCK_UNLOCKED(tmp.slock), 3916 .owned = 1, 3917 }; 3918 socket_lock_t old = { 3919 .slock = __SPIN_LOCK_UNLOCKED(old.slock), 3920 .owned = 0, 3921 }; 3922 3923 if (likely(try_cmpxchg(&sk->sk_lock.combined, 3924 &old.combined, tmp.combined))) 3925 return; 3926 } 3927 #endif 3928 spin_lock_bh(&sk->sk_lock.slock); 3929 if (unlikely(sock_owned_by_user_nocheck(sk))) 3930 __lock_sock(sk); 3931 sk->sk_lock.owned = 1; 3932 spin_unlock_bh(&sk->sk_lock.slock); 3933 } 3934 EXPORT_SYMBOL(lock_sock_nested); 3935 3936 void release_sock(struct sock *sk) 3937 { 3938 spin_lock_bh(&sk->sk_lock.slock); 3939 3940 if (unlikely(sk->sk_backlog.tail)) 3941 __release_sock(sk); 3942 3943 if (sk->sk_prot->release_cb) { 3944 if (!tcp_release_cb_cond(sk)) 3945 sk->sk_prot->release_cb(sk); 3946 } 3947 sock_release_ownership(sk); 3948 if (unlikely(waitqueue_active(&sk->sk_lock.wq))) 3949 wake_up(&sk->sk_lock.wq); 3950 3951 spin_unlock_bh(&sk->sk_lock.slock); 3952 } 3953 EXPORT_SYMBOL(release_sock); 3954 3955 bool __lock_sock_fast(struct sock *sk) __acquires(&sk->sk_lock.slock) 3956 { 3957 might_sleep(); 3958 spin_lock_bh(&sk->sk_lock.slock); 3959 3960 if (likely(!sock_owned_by_user_nocheck(sk))) { 3961 /* 3962 * Fast path return with bottom halves disabled and 3963 * sock::sk_lock.slock held. 3964 * 3965 * The 'mutex' is not contended and holding 3966 * sock::sk_lock.slock prevents all other lockers to 3967 * proceed so the corresponding unlock_sock_fast() can 3968 * avoid the slow path of release_sock() completely and 3969 * just release slock. 3970 * 3971 * From a semantical POV this is equivalent to 'acquiring' 3972 * the 'mutex', hence the corresponding lockdep 3973 * mutex_release() has to happen in the fast path of 3974 * unlock_sock_fast(). 3975 */ 3976 return false; 3977 } 3978 3979 __lock_sock(sk); 3980 sk->sk_lock.owned = 1; 3981 __acquire(&sk->sk_lock.slock); 3982 spin_unlock_bh(&sk->sk_lock.slock); 3983 return true; 3984 } 3985 EXPORT_SYMBOL(__lock_sock_fast); 3986 3987 int sock_gettstamp(struct socket *sock, void __user *userstamp, 3988 bool timeval, bool time32) 3989 { 3990 struct sock *sk = sock->sk; 3991 struct timespec64 ts; 3992 3993 /* sk->sk_flags must only be changed under the socket lock, 3994 * because sock_set_flag() uses non atomic operations. 3995 */ 3996 if (!sock_flag(sk, SOCK_TIMESTAMP)) { 3997 lock_sock(sk); 3998 sock_enable_timestamp(sk, SOCK_TIMESTAMP); 3999 release_sock(sk); 4000 } 4001 ts = ktime_to_timespec64(sock_read_timestamp(sk)); 4002 if (ts.tv_sec == -1) 4003 return -ENOENT; 4004 if (ts.tv_sec == 0) { 4005 ktime_t kt = ktime_get_real(); 4006 sock_write_timestamp(sk, kt); 4007 ts = ktime_to_timespec64(kt); 4008 } 4009 4010 if (timeval) 4011 ts.tv_nsec /= 1000; 4012 4013 #ifdef CONFIG_COMPAT_32BIT_TIME 4014 if (time32) 4015 return put_old_timespec32(&ts, userstamp); 4016 #endif 4017 #ifdef CONFIG_SPARC64 4018 /* beware of padding in sparc64 timeval */ 4019 if (timeval && !in_compat_syscall()) { 4020 struct __kernel_old_timeval __user tv = { 4021 .tv_sec = ts.tv_sec, 4022 .tv_usec = ts.tv_nsec, 4023 }; 4024 if (copy_to_user(userstamp, &tv, sizeof(tv))) 4025 return -EFAULT; 4026 return 0; 4027 } 4028 #endif 4029 return put_timespec64(&ts, userstamp); 4030 } 4031 EXPORT_SYMBOL(sock_gettstamp); 4032 4033 void sock_enable_timestamp(struct sock *sk, enum sock_flags flag) 4034 { 4035 if (!sock_flag(sk, flag)) { 4036 unsigned long previous_flags = sk->sk_flags; 4037 4038 sock_set_flag(sk, flag); 4039 /* 4040 * we just set one of the two flags which require net 4041 * time stamping, but time stamping might have been on 4042 * already because of the other one 4043 */ 4044 if (sock_needs_netstamp(sk) && 4045 !(previous_flags & SK_FLAGS_TIMESTAMP)) 4046 net_enable_timestamp(); 4047 } 4048 } 4049 4050 int sock_recv_errqueue(struct sock *sk, struct msghdr *msg, int len, 4051 int level, int type) 4052 { 4053 struct sock_extended_err ee; 4054 struct sk_buff *skb; 4055 int copied, err; 4056 4057 err = -EAGAIN; 4058 skb = sock_dequeue_err_skb(sk); 4059 if (skb == NULL) 4060 goto out; 4061 4062 copied = skb->len; 4063 if (copied > len) { 4064 msg->msg_flags |= MSG_TRUNC; 4065 copied = len; 4066 } 4067 err = skb_copy_datagram_msg(skb, 0, msg, copied); 4068 if (err) 4069 goto out_free_skb; 4070 4071 sock_recv_timestamp(msg, sk, skb); 4072 4073 /* We must use a bounce buffer for CONFIG_HARDENED_USERCOPY=y */ 4074 ee = SKB_EXT_ERR(skb)->ee; 4075 put_cmsg(msg, level, type, sizeof(ee), &ee); 4076 4077 msg->msg_flags |= MSG_ERRQUEUE; 4078 err = copied; 4079 4080 out_free_skb: 4081 kfree_skb(skb); 4082 out: 4083 return err; 4084 } 4085 EXPORT_SYMBOL(sock_recv_errqueue); 4086 4087 /* 4088 * Get a socket option on an socket. 4089 * 4090 * FIX: POSIX 1003.1g is very ambiguous here. It states that 4091 * asynchronous errors should be reported by getsockopt. We assume 4092 * this means if you specify SO_ERROR (otherwise what is the point of it). 4093 */ 4094 int sock_common_getsockopt(struct socket *sock, int level, int optname, 4095 char __user *optval, int __user *optlen) 4096 { 4097 struct sock *sk = sock->sk; 4098 4099 return READ_ONCE(sk->sk_prot)->getsockopt(sk, level, optname, optval, optlen); 4100 } 4101 EXPORT_SYMBOL(sock_common_getsockopt); 4102 4103 int sock_common_recvmsg(struct socket *sock, struct msghdr *msg, size_t size, 4104 int flags) 4105 { 4106 struct sock *sk = sock->sk; 4107 4108 return sk->sk_prot->recvmsg(sk, msg, size, flags); 4109 } 4110 EXPORT_SYMBOL(sock_common_recvmsg); 4111 4112 /* 4113 * Set socket options on an inet socket. 4114 */ 4115 int sock_common_setsockopt(struct socket *sock, int level, int optname, 4116 sockptr_t optval, unsigned int optlen) 4117 { 4118 struct sock *sk = sock->sk; 4119 4120 return READ_ONCE(sk->sk_prot)->setsockopt(sk, level, optname, optval, optlen); 4121 } 4122 EXPORT_SYMBOL(sock_common_setsockopt); 4123 4124 void sk_common_release(struct sock *sk) 4125 { 4126 if (sk->sk_prot->destroy) 4127 sk->sk_prot->destroy(sk); 4128 4129 /* 4130 * Observation: when sk_common_release is called, processes have 4131 * no access to socket. But net still has. 4132 * Step one, detach it from networking: 4133 * 4134 * A. Remove from hash tables. 4135 */ 4136 4137 sk->sk_prot->unhash(sk); 4138 4139 /* 4140 * In this point socket cannot receive new packets, but it is possible 4141 * that some packets are in flight because some CPU runs receiver and 4142 * did hash table lookup before we unhashed socket. They will achieve 4143 * receive queue and will be purged by socket destructor. 4144 * 4145 * Also we still have packets pending on receive queue and probably, 4146 * our own packets waiting in device queues. sock_destroy will drain 4147 * receive queue, but transmitted packets will delay socket destruction 4148 * until the last reference will be released. 4149 */ 4150 4151 sock_orphan(sk); 4152 4153 xfrm_sk_free_policy(sk); 4154 4155 sock_put(sk); 4156 } 4157 EXPORT_SYMBOL(sk_common_release); 4158 4159 void sk_get_meminfo(const struct sock *sk, u32 *mem) 4160 { 4161 memset(mem, 0, sizeof(*mem) * SK_MEMINFO_VARS); 4162 4163 mem[SK_MEMINFO_RMEM_ALLOC] = sk_rmem_alloc_get(sk); 4164 mem[SK_MEMINFO_RCVBUF] = READ_ONCE(sk->sk_rcvbuf); 4165 mem[SK_MEMINFO_WMEM_ALLOC] = sk_wmem_alloc_get(sk); 4166 mem[SK_MEMINFO_SNDBUF] = READ_ONCE(sk->sk_sndbuf); 4167 mem[SK_MEMINFO_FWD_ALLOC] = READ_ONCE(sk->sk_forward_alloc); 4168 mem[SK_MEMINFO_WMEM_QUEUED] = READ_ONCE(sk->sk_wmem_queued); 4169 mem[SK_MEMINFO_OPTMEM] = atomic_read(&sk->sk_omem_alloc); 4170 mem[SK_MEMINFO_BACKLOG] = READ_ONCE(sk->sk_backlog.len); 4171 mem[SK_MEMINFO_DROPS] = sk_drops_read(sk); 4172 } 4173 4174 #ifdef CONFIG_PROC_FS 4175 static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR); 4176 4177 int sock_prot_inuse_get(struct net *net, struct proto *prot) 4178 { 4179 int cpu, idx = prot->inuse_idx; 4180 int res = 0; 4181 4182 for_each_possible_cpu(cpu) 4183 res += per_cpu_ptr(net->core.prot_inuse, cpu)->val[idx]; 4184 4185 return res >= 0 ? res : 0; 4186 } 4187 EXPORT_SYMBOL_GPL(sock_prot_inuse_get); 4188 4189 int sock_inuse_get(struct net *net) 4190 { 4191 int cpu, res = 0; 4192 4193 for_each_possible_cpu(cpu) 4194 res += per_cpu_ptr(net->core.prot_inuse, cpu)->all; 4195 4196 return res; 4197 } 4198 4199 EXPORT_SYMBOL_GPL(sock_inuse_get); 4200 4201 static int __net_init sock_inuse_init_net(struct net *net) 4202 { 4203 net->core.prot_inuse = alloc_percpu(struct prot_inuse); 4204 if (net->core.prot_inuse == NULL) 4205 return -ENOMEM; 4206 return 0; 4207 } 4208 4209 static void __net_exit sock_inuse_exit_net(struct net *net) 4210 { 4211 free_percpu(net->core.prot_inuse); 4212 } 4213 4214 static struct pernet_operations net_inuse_ops = { 4215 .init = sock_inuse_init_net, 4216 .exit = sock_inuse_exit_net, 4217 }; 4218 4219 static __init int net_inuse_init(void) 4220 { 4221 if (register_pernet_subsys(&net_inuse_ops)) 4222 panic("Cannot initialize net inuse counters"); 4223 4224 return 0; 4225 } 4226 4227 core_initcall(net_inuse_init); 4228 4229 static int assign_proto_idx(struct proto *prot) 4230 { 4231 prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR); 4232 4233 if (unlikely(prot->inuse_idx == PROTO_INUSE_NR)) { 4234 pr_err("PROTO_INUSE_NR exhausted\n"); 4235 return -ENOSPC; 4236 } 4237 4238 set_bit(prot->inuse_idx, proto_inuse_idx); 4239 return 0; 4240 } 4241 4242 static void release_proto_idx(struct proto *prot) 4243 { 4244 if (prot->inuse_idx != PROTO_INUSE_NR) 4245 clear_bit(prot->inuse_idx, proto_inuse_idx); 4246 } 4247 #else 4248 static inline int assign_proto_idx(struct proto *prot) 4249 { 4250 return 0; 4251 } 4252 4253 static inline void release_proto_idx(struct proto *prot) 4254 { 4255 } 4256 4257 #endif 4258 4259 static void tw_prot_cleanup(struct timewait_sock_ops *twsk_prot) 4260 { 4261 if (!twsk_prot) 4262 return; 4263 kfree(twsk_prot->twsk_slab_name); 4264 twsk_prot->twsk_slab_name = NULL; 4265 kmem_cache_destroy(twsk_prot->twsk_slab); 4266 twsk_prot->twsk_slab = NULL; 4267 } 4268 4269 static int tw_prot_init(const struct proto *prot) 4270 { 4271 struct timewait_sock_ops *twsk_prot = prot->twsk_prot; 4272 4273 if (!twsk_prot) 4274 return 0; 4275 4276 twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s", 4277 prot->name); 4278 if (!twsk_prot->twsk_slab_name) 4279 return -ENOMEM; 4280 4281 twsk_prot->twsk_slab = 4282 kmem_cache_create(twsk_prot->twsk_slab_name, 4283 twsk_prot->twsk_obj_size, 0, 4284 SLAB_ACCOUNT | prot->slab_flags, 4285 NULL); 4286 if (!twsk_prot->twsk_slab) { 4287 pr_crit("%s: Can't create timewait sock SLAB cache!\n", 4288 prot->name); 4289 return -ENOMEM; 4290 } 4291 4292 return 0; 4293 } 4294 4295 static void req_prot_cleanup(struct request_sock_ops *rsk_prot) 4296 { 4297 if (!rsk_prot) 4298 return; 4299 kfree(rsk_prot->slab_name); 4300 rsk_prot->slab_name = NULL; 4301 kmem_cache_destroy(rsk_prot->slab); 4302 rsk_prot->slab = NULL; 4303 } 4304 4305 static int req_prot_init(const struct proto *prot) 4306 { 4307 struct request_sock_ops *rsk_prot = prot->rsk_prot; 4308 4309 if (!rsk_prot) 4310 return 0; 4311 4312 rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s", 4313 prot->name); 4314 if (!rsk_prot->slab_name) 4315 return -ENOMEM; 4316 4317 rsk_prot->slab = kmem_cache_create(rsk_prot->slab_name, 4318 rsk_prot->obj_size, 0, 4319 SLAB_ACCOUNT | prot->slab_flags, 4320 NULL); 4321 4322 if (!rsk_prot->slab) { 4323 pr_crit("%s: Can't create request sock SLAB cache!\n", 4324 prot->name); 4325 return -ENOMEM; 4326 } 4327 return 0; 4328 } 4329 4330 int proto_register(struct proto *prot, int alloc_slab) 4331 { 4332 int ret = -ENOBUFS; 4333 4334 if (prot->memory_allocated && !prot->sysctl_mem) { 4335 pr_err("%s: missing sysctl_mem\n", prot->name); 4336 return -EINVAL; 4337 } 4338 if (prot->memory_allocated && !prot->per_cpu_fw_alloc) { 4339 pr_err("%s: missing per_cpu_fw_alloc\n", prot->name); 4340 return -EINVAL; 4341 } 4342 if (alloc_slab) { 4343 struct kmem_cache_args args = { 4344 .useroffset = prot->useroffset, 4345 .usersize = prot->usersize, 4346 .freeptr_offset = prot->freeptr_offset, 4347 .use_freeptr_offset = !!prot->freeptr_offset, 4348 }; 4349 4350 prot->slab = kmem_cache_create(prot->name, prot->obj_size, 4351 &args, 4352 SLAB_HWCACHE_ALIGN | SLAB_ACCOUNT | 4353 prot->slab_flags); 4354 if (prot->slab == NULL) { 4355 pr_crit("%s: Can't create sock SLAB cache!\n", 4356 prot->name); 4357 goto out; 4358 } 4359 4360 if (req_prot_init(prot)) 4361 goto out_free_request_sock_slab; 4362 4363 if (tw_prot_init(prot)) 4364 goto out_free_timewait_sock_slab; 4365 } 4366 4367 mutex_lock(&proto_list_mutex); 4368 ret = assign_proto_idx(prot); 4369 if (ret) { 4370 mutex_unlock(&proto_list_mutex); 4371 goto out_free_timewait_sock_slab; 4372 } 4373 list_add(&prot->node, &proto_list); 4374 mutex_unlock(&proto_list_mutex); 4375 return ret; 4376 4377 out_free_timewait_sock_slab: 4378 if (alloc_slab) 4379 tw_prot_cleanup(prot->twsk_prot); 4380 out_free_request_sock_slab: 4381 if (alloc_slab) { 4382 req_prot_cleanup(prot->rsk_prot); 4383 4384 kmem_cache_destroy(prot->slab); 4385 prot->slab = NULL; 4386 } 4387 out: 4388 return ret; 4389 } 4390 EXPORT_SYMBOL(proto_register); 4391 4392 void proto_unregister(struct proto *prot) 4393 { 4394 mutex_lock(&proto_list_mutex); 4395 release_proto_idx(prot); 4396 list_del(&prot->node); 4397 mutex_unlock(&proto_list_mutex); 4398 4399 kmem_cache_destroy(prot->slab); 4400 prot->slab = NULL; 4401 4402 req_prot_cleanup(prot->rsk_prot); 4403 tw_prot_cleanup(prot->twsk_prot); 4404 } 4405 EXPORT_SYMBOL(proto_unregister); 4406 4407 int sock_load_diag_module(int family, int protocol) 4408 { 4409 if (!protocol) { 4410 if (!sock_is_registered(family)) 4411 return -ENOENT; 4412 4413 return request_module("net-pf-%d-proto-%d-type-%d", PF_NETLINK, 4414 NETLINK_SOCK_DIAG, family); 4415 } 4416 4417 #ifdef CONFIG_INET 4418 if (family == AF_INET && 4419 protocol != IPPROTO_RAW && 4420 protocol < MAX_INET_PROTOS && 4421 !rcu_access_pointer(inet_protos[protocol])) 4422 return -ENOENT; 4423 #endif 4424 4425 return request_module("net-pf-%d-proto-%d-type-%d-%d", PF_NETLINK, 4426 NETLINK_SOCK_DIAG, family, protocol); 4427 } 4428 EXPORT_SYMBOL(sock_load_diag_module); 4429 4430 #ifdef CONFIG_PROC_FS 4431 static void *proto_seq_start(struct seq_file *seq, loff_t *pos) 4432 __acquires(proto_list_mutex) 4433 { 4434 mutex_lock(&proto_list_mutex); 4435 return seq_list_start_head(&proto_list, *pos); 4436 } 4437 4438 static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos) 4439 { 4440 return seq_list_next(v, &proto_list, pos); 4441 } 4442 4443 static void proto_seq_stop(struct seq_file *seq, void *v) 4444 __releases(proto_list_mutex) 4445 { 4446 mutex_unlock(&proto_list_mutex); 4447 } 4448 4449 static char proto_method_implemented(const void *method) 4450 { 4451 return method == NULL ? 'n' : 'y'; 4452 } 4453 static long sock_prot_memory_allocated(struct proto *proto) 4454 { 4455 return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L; 4456 } 4457 4458 static const char *sock_prot_memory_pressure(struct proto *proto) 4459 { 4460 return proto->memory_pressure != NULL ? 4461 proto_memory_pressure(proto) ? "yes" : "no" : "NI"; 4462 } 4463 4464 static void proto_seq_printf(struct seq_file *seq, struct proto *proto) 4465 { 4466 4467 seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s " 4468 "%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n", 4469 proto->name, 4470 proto->obj_size, 4471 sock_prot_inuse_get(seq_file_net(seq), proto), 4472 sock_prot_memory_allocated(proto), 4473 sock_prot_memory_pressure(proto), 4474 proto->max_header, 4475 proto->slab == NULL ? "no" : "yes", 4476 module_name(proto->owner), 4477 proto_method_implemented(proto->close), 4478 proto_method_implemented(proto->connect), 4479 proto_method_implemented(proto->disconnect), 4480 proto_method_implemented(proto->accept), 4481 proto_method_implemented(proto->ioctl), 4482 proto_method_implemented(proto->init), 4483 proto_method_implemented(proto->destroy), 4484 proto_method_implemented(proto->shutdown), 4485 proto_method_implemented(proto->setsockopt), 4486 proto_method_implemented(proto->getsockopt), 4487 proto_method_implemented(proto->sendmsg), 4488 proto_method_implemented(proto->recvmsg), 4489 proto_method_implemented(proto->bind), 4490 proto_method_implemented(proto->backlog_rcv), 4491 proto_method_implemented(proto->hash), 4492 proto_method_implemented(proto->unhash), 4493 proto_method_implemented(proto->get_port), 4494 proto_method_implemented(proto->enter_memory_pressure)); 4495 } 4496 4497 static int proto_seq_show(struct seq_file *seq, void *v) 4498 { 4499 if (v == &proto_list) 4500 seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s", 4501 "protocol", 4502 "size", 4503 "sockets", 4504 "memory", 4505 "press", 4506 "maxhdr", 4507 "slab", 4508 "module", 4509 "cl co di ac io in de sh ss gs se re bi br ha uh gp em\n"); 4510 else 4511 proto_seq_printf(seq, list_entry(v, struct proto, node)); 4512 return 0; 4513 } 4514 4515 static const struct seq_operations proto_seq_ops = { 4516 .start = proto_seq_start, 4517 .next = proto_seq_next, 4518 .stop = proto_seq_stop, 4519 .show = proto_seq_show, 4520 }; 4521 4522 static __net_init int proto_init_net(struct net *net) 4523 { 4524 if (!proc_create_net("protocols", 0444, net->proc_net, &proto_seq_ops, 4525 sizeof(struct seq_net_private))) 4526 return -ENOMEM; 4527 4528 return 0; 4529 } 4530 4531 static __net_exit void proto_exit_net(struct net *net) 4532 { 4533 remove_proc_entry("protocols", net->proc_net); 4534 } 4535 4536 4537 static __net_initdata struct pernet_operations proto_net_ops = { 4538 .init = proto_init_net, 4539 .exit = proto_exit_net, 4540 }; 4541 4542 static int __init proto_init(void) 4543 { 4544 return register_pernet_subsys(&proto_net_ops); 4545 } 4546 4547 subsys_initcall(proto_init); 4548 4549 #endif /* PROC_FS */ 4550 4551 #ifdef CONFIG_NET_RX_BUSY_POLL 4552 bool sk_busy_loop_end(void *p, unsigned long start_time) 4553 { 4554 struct sock *sk = p; 4555 4556 if (!skb_queue_empty_lockless(&sk->sk_receive_queue)) 4557 return true; 4558 4559 if (sk_is_udp(sk) && 4560 !skb_queue_empty_lockless(&udp_sk(sk)->reader_queue)) 4561 return true; 4562 4563 return sk_busy_loop_timeout(sk, start_time); 4564 } 4565 EXPORT_SYMBOL(sk_busy_loop_end); 4566 #endif /* CONFIG_NET_RX_BUSY_POLL */ 4567 4568 int sock_bind_add(struct sock *sk, struct sockaddr_unsized *addr, int addr_len) 4569 { 4570 if (!sk->sk_prot->bind_add) 4571 return -EOPNOTSUPP; 4572 return sk->sk_prot->bind_add(sk, addr, addr_len); 4573 } 4574 EXPORT_SYMBOL(sock_bind_add); 4575 4576 /* Copy 'size' bytes from userspace and return `size` back to userspace */ 4577 int sock_ioctl_inout(struct sock *sk, unsigned int cmd, 4578 void __user *arg, void *karg, size_t size) 4579 { 4580 int ret; 4581 4582 if (copy_from_user(karg, arg, size)) 4583 return -EFAULT; 4584 4585 ret = READ_ONCE(sk->sk_prot)->ioctl(sk, cmd, karg); 4586 if (ret) 4587 return ret; 4588 4589 if (copy_to_user(arg, karg, size)) 4590 return -EFAULT; 4591 4592 return 0; 4593 } 4594 EXPORT_SYMBOL(sock_ioctl_inout); 4595 4596 /* This is the most common ioctl prep function, where the result (4 bytes) is 4597 * copied back to userspace if the ioctl() returns successfully. No input is 4598 * copied from userspace as input argument. 4599 */ 4600 static int sock_ioctl_out(struct sock *sk, unsigned int cmd, void __user *arg) 4601 { 4602 int ret, karg = 0; 4603 4604 ret = READ_ONCE(sk->sk_prot)->ioctl(sk, cmd, &karg); 4605 if (ret) 4606 return ret; 4607 4608 return put_user(karg, (int __user *)arg); 4609 } 4610 4611 /* A wrapper around sock ioctls, which copies the data from userspace 4612 * (depending on the protocol/ioctl), and copies back the result to userspace. 4613 * The main motivation for this function is to pass kernel memory to the 4614 * protocol ioctl callbacks, instead of userspace memory. 4615 */ 4616 int sk_ioctl(struct sock *sk, unsigned int cmd, void __user *arg) 4617 { 4618 int rc = 1; 4619 4620 if (sk->sk_type == SOCK_RAW && sk->sk_family == AF_INET) 4621 rc = ipmr_sk_ioctl(sk, cmd, arg); 4622 else if (sk->sk_type == SOCK_RAW && sk->sk_family == AF_INET6) 4623 rc = ip6mr_sk_ioctl(sk, cmd, arg); 4624 else if (sk_is_phonet(sk)) 4625 rc = phonet_sk_ioctl(sk, cmd, arg); 4626 4627 /* If ioctl was processed, returns its value */ 4628 if (rc <= 0) 4629 return rc; 4630 4631 /* Otherwise call the default handler */ 4632 return sock_ioctl_out(sk, cmd, arg); 4633 } 4634 EXPORT_SYMBOL(sk_ioctl); 4635 4636 static int __init sock_struct_check(void) 4637 { 4638 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_drops); 4639 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_peek_off); 4640 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_error_queue); 4641 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_receive_queue); 4642 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rx, sk_backlog); 4643 4644 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rx_dst); 4645 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rx_dst_ifindex); 4646 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rx_dst_cookie); 4647 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rcvbuf); 4648 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_filter); 4649 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_wq); 4650 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_data_ready); 4651 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rcvtimeo); 4652 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rx, sk_rcvlowat); 4653 4654 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rxtx, sk_err); 4655 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rxtx, sk_socket); 4656 #ifdef CONFIG_MEMCG 4657 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_rxtx, sk_memcg); 4658 #endif 4659 4660 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rxtx, sk_lock); 4661 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rxtx, sk_reserved_mem); 4662 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rxtx, sk_forward_alloc); 4663 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_rxtx, sk_tsflags); 4664 4665 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_omem_alloc); 4666 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_omem_alloc); 4667 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_err_soft); 4668 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_wmem_queued); 4669 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_wmem_alloc); 4670 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_tsq_flags); 4671 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_send_head); 4672 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_write_queue); 4673 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_write_pending); 4674 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_frag); 4675 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_timer); 4676 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_pacing_rate); 4677 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_zckey); 4678 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_write_tx, sk_tskey); 4679 4680 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_dst_pending_confirm); 4681 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_pacing_status); 4682 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_max_pacing_rate); 4683 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_sndtimeo); 4684 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_priority); 4685 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_mark); 4686 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_uid); 4687 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_protocol); 4688 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_dst_cache); 4689 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_route_caps); 4690 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_gso_type); 4691 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_gso_max_size); 4692 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_allocation); 4693 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_txhash); 4694 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_sndbuf); 4695 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_gso_max_segs); 4696 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_pacing_shift); 4697 CACHELINE_ASSERT_GROUP_MEMBER(struct sock, sock_read_tx, sk_use_task_frag); 4698 return 0; 4699 } 4700 4701 core_initcall(sock_struct_check); 4702