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 * Implementation of the Transmission Control Protocol(TCP). 8 * 9 * Authors: Ross Biro 10 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> 11 * Mark Evans, <evansmp@uhura.aston.ac.uk> 12 * Corey Minyard <wf-rch!minyard@relay.EU.net> 13 * Florian La Roche, <flla@stud.uni-sb.de> 14 * Charles Hedrick, <hedrick@klinzhai.rutgers.edu> 15 * Linus Torvalds, <torvalds@cs.helsinki.fi> 16 * Alan Cox, <gw4pts@gw4pts.ampr.org> 17 * Matthew Dillon, <dillon@apollo.west.oic.com> 18 * Arnt Gulbrandsen, <agulbra@nvg.unit.no> 19 * Jorge Cwik, <jorge@laser.satlink.net> 20 * 21 * Fixes: 22 * Alan Cox : Numerous verify_area() calls 23 * Alan Cox : Set the ACK bit on a reset 24 * Alan Cox : Stopped it crashing if it closed while 25 * sk->inuse=1 and was trying to connect 26 * (tcp_err()). 27 * Alan Cox : All icmp error handling was broken 28 * pointers passed where wrong and the 29 * socket was looked up backwards. Nobody 30 * tested any icmp error code obviously. 31 * Alan Cox : tcp_err() now handled properly. It 32 * wakes people on errors. poll 33 * behaves and the icmp error race 34 * has gone by moving it into sock.c 35 * Alan Cox : tcp_send_reset() fixed to work for 36 * everything not just packets for 37 * unknown sockets. 38 * Alan Cox : tcp option processing. 39 * Alan Cox : Reset tweaked (still not 100%) [Had 40 * syn rule wrong] 41 * Herp Rosmanith : More reset fixes 42 * Alan Cox : No longer acks invalid rst frames. 43 * Acking any kind of RST is right out. 44 * Alan Cox : Sets an ignore me flag on an rst 45 * receive otherwise odd bits of prattle 46 * escape still 47 * Alan Cox : Fixed another acking RST frame bug. 48 * Should stop LAN workplace lockups. 49 * Alan Cox : Some tidyups using the new skb list 50 * facilities 51 * Alan Cox : sk->keepopen now seems to work 52 * Alan Cox : Pulls options out correctly on accepts 53 * Alan Cox : Fixed assorted sk->rqueue->next errors 54 * Alan Cox : PSH doesn't end a TCP read. Switched a 55 * bit to skb ops. 56 * Alan Cox : Tidied tcp_data to avoid a potential 57 * nasty. 58 * Alan Cox : Added some better commenting, as the 59 * tcp is hard to follow 60 * Alan Cox : Removed incorrect check for 20 * psh 61 * Michael O'Reilly : ack < copied bug fix. 62 * Johannes Stille : Misc tcp fixes (not all in yet). 63 * Alan Cox : FIN with no memory -> CRASH 64 * Alan Cox : Added socket option proto entries. 65 * Also added awareness of them to accept. 66 * Alan Cox : Added TCP options (SOL_TCP) 67 * Alan Cox : Switched wakeup calls to callbacks, 68 * so the kernel can layer network 69 * sockets. 70 * Alan Cox : Use ip_tos/ip_ttl settings. 71 * Alan Cox : Handle FIN (more) properly (we hope). 72 * Alan Cox : RST frames sent on unsynchronised 73 * state ack error. 74 * Alan Cox : Put in missing check for SYN bit. 75 * Alan Cox : Added tcp_select_window() aka NET2E 76 * window non shrink trick. 77 * Alan Cox : Added a couple of small NET2E timer 78 * fixes 79 * Charles Hedrick : TCP fixes 80 * Toomas Tamm : TCP window fixes 81 * Alan Cox : Small URG fix to rlogin ^C ack fight 82 * Charles Hedrick : Rewrote most of it to actually work 83 * Linus : Rewrote tcp_read() and URG handling 84 * completely 85 * Gerhard Koerting: Fixed some missing timer handling 86 * Matthew Dillon : Reworked TCP machine states as per RFC 87 * Gerhard Koerting: PC/TCP workarounds 88 * Adam Caldwell : Assorted timer/timing errors 89 * Matthew Dillon : Fixed another RST bug 90 * Alan Cox : Move to kernel side addressing changes. 91 * Alan Cox : Beginning work on TCP fastpathing 92 * (not yet usable) 93 * Arnt Gulbrandsen: Turbocharged tcp_check() routine. 94 * Alan Cox : TCP fast path debugging 95 * Alan Cox : Window clamping 96 * Michael Riepe : Bug in tcp_check() 97 * Matt Dillon : More TCP improvements and RST bug fixes 98 * Matt Dillon : Yet more small nasties remove from the 99 * TCP code (Be very nice to this man if 100 * tcp finally works 100%) 8) 101 * Alan Cox : BSD accept semantics. 102 * Alan Cox : Reset on closedown bug. 103 * Peter De Schrijver : ENOTCONN check missing in tcp_sendto(). 104 * Michael Pall : Handle poll() after URG properly in 105 * all cases. 106 * Michael Pall : Undo the last fix in tcp_read_urg() 107 * (multi URG PUSH broke rlogin). 108 * Michael Pall : Fix the multi URG PUSH problem in 109 * tcp_readable(), poll() after URG 110 * works now. 111 * Michael Pall : recv(...,MSG_OOB) never blocks in the 112 * BSD api. 113 * Alan Cox : Changed the semantics of sk->socket to 114 * fix a race and a signal problem with 115 * accept() and async I/O. 116 * Alan Cox : Relaxed the rules on tcp_sendto(). 117 * Yury Shevchuk : Really fixed accept() blocking problem. 118 * Craig I. Hagan : Allow for BSD compatible TIME_WAIT for 119 * clients/servers which listen in on 120 * fixed ports. 121 * Alan Cox : Cleaned the above up and shrank it to 122 * a sensible code size. 123 * Alan Cox : Self connect lockup fix. 124 * Alan Cox : No connect to multicast. 125 * Ross Biro : Close unaccepted children on master 126 * socket close. 127 * Alan Cox : Reset tracing code. 128 * Alan Cox : Spurious resets on shutdown. 129 * Alan Cox : Giant 15 minute/60 second timer error 130 * Alan Cox : Small whoops in polling before an 131 * accept. 132 * Alan Cox : Kept the state trace facility since 133 * it's handy for debugging. 134 * Alan Cox : More reset handler fixes. 135 * Alan Cox : Started rewriting the code based on 136 * the RFC's for other useful protocol 137 * references see: Comer, KA9Q NOS, and 138 * for a reference on the difference 139 * between specifications and how BSD 140 * works see the 4.4lite source. 141 * A.N.Kuznetsov : Don't time wait on completion of tidy 142 * close. 143 * Linus Torvalds : Fin/Shutdown & copied_seq changes. 144 * Linus Torvalds : Fixed BSD port reuse to work first syn 145 * Alan Cox : Reimplemented timers as per the RFC 146 * and using multiple timers for sanity. 147 * Alan Cox : Small bug fixes, and a lot of new 148 * comments. 149 * Alan Cox : Fixed dual reader crash by locking 150 * the buffers (much like datagram.c) 151 * Alan Cox : Fixed stuck sockets in probe. A probe 152 * now gets fed up of retrying without 153 * (even a no space) answer. 154 * Alan Cox : Extracted closing code better 155 * Alan Cox : Fixed the closing state machine to 156 * resemble the RFC. 157 * Alan Cox : More 'per spec' fixes. 158 * Jorge Cwik : Even faster checksumming. 159 * Alan Cox : tcp_data() doesn't ack illegal PSH 160 * only frames. At least one pc tcp stack 161 * generates them. 162 * Alan Cox : Cache last socket. 163 * Alan Cox : Per route irtt. 164 * Matt Day : poll()->select() match BSD precisely on error 165 * Alan Cox : New buffers 166 * Marc Tamsky : Various sk->prot->retransmits and 167 * sk->retransmits misupdating fixed. 168 * Fixed tcp_write_timeout: stuck close, 169 * and TCP syn retries gets used now. 170 * Mark Yarvis : In tcp_read_wakeup(), don't send an 171 * ack if state is TCP_CLOSED. 172 * Alan Cox : Look up device on a retransmit - routes may 173 * change. Doesn't yet cope with MSS shrink right 174 * but it's a start! 175 * Marc Tamsky : Closing in closing fixes. 176 * Mike Shaver : RFC1122 verifications. 177 * Alan Cox : rcv_saddr errors. 178 * Alan Cox : Block double connect(). 179 * Alan Cox : Small hooks for enSKIP. 180 * Alexey Kuznetsov: Path MTU discovery. 181 * Alan Cox : Support soft errors. 182 * Alan Cox : Fix MTU discovery pathological case 183 * when the remote claims no mtu! 184 * Marc Tamsky : TCP_CLOSE fix. 185 * Colin (G3TNE) : Send a reset on syn ack replies in 186 * window but wrong (fixes NT lpd problems) 187 * Pedro Roque : Better TCP window handling, delayed ack. 188 * Joerg Reuter : No modification of locked buffers in 189 * tcp_do_retransmit() 190 * Eric Schenk : Changed receiver side silly window 191 * avoidance algorithm to BSD style 192 * algorithm. This doubles throughput 193 * against machines running Solaris, 194 * and seems to result in general 195 * improvement. 196 * Stefan Magdalinski : adjusted tcp_readable() to fix FIONREAD 197 * Willy Konynenberg : Transparent proxying support. 198 * Mike McLagan : Routing by source 199 * Keith Owens : Do proper merging with partial SKB's in 200 * tcp_do_sendmsg to avoid burstiness. 201 * Eric Schenk : Fix fast close down bug with 202 * shutdown() followed by close(). 203 * Andi Kleen : Make poll agree with SIGIO 204 * Salvatore Sanfilippo : Support SO_LINGER with linger == 1 and 205 * lingertime == 0 (RFC 793 ABORT Call) 206 * Hirokazu Takahashi : Use copy_from_user() instead of 207 * csum_and_copy_from_user() if possible. 208 * 209 * Description of States: 210 * 211 * TCP_SYN_SENT sent a connection request, waiting for ack 212 * 213 * TCP_SYN_RECV received a connection request, sent ack, 214 * waiting for final ack in three-way handshake. 215 * 216 * TCP_ESTABLISHED connection established 217 * 218 * TCP_FIN_WAIT1 our side has shutdown, waiting to complete 219 * transmission of remaining buffered data 220 * 221 * TCP_FIN_WAIT2 all buffered data sent, waiting for remote 222 * to shutdown 223 * 224 * TCP_CLOSING both sides have shutdown but we still have 225 * data we have to finish sending 226 * 227 * TCP_TIME_WAIT timeout to catch resent junk before entering 228 * closed, can only be entered from FIN_WAIT2 229 * or CLOSING. Required because the other end 230 * may not have gotten our last ACK causing it 231 * to retransmit the data packet (which we ignore) 232 * 233 * TCP_CLOSE_WAIT remote side has shutdown and is waiting for 234 * us to finish writing our data and to shutdown 235 * (we have to close() to move on to LAST_ACK) 236 * 237 * TCP_LAST_ACK out side has shutdown after remote has 238 * shutdown. There may still be data in our 239 * buffer that we have to finish sending 240 * 241 * TCP_CLOSE socket is finished 242 */ 243 244 #define pr_fmt(fmt) "TCP: " fmt 245 246 #include <crypto/hash.h> 247 #include <linux/kernel.h> 248 #include <linux/module.h> 249 #include <linux/types.h> 250 #include <linux/fcntl.h> 251 #include <linux/poll.h> 252 #include <linux/inet_diag.h> 253 #include <linux/init.h> 254 #include <linux/fs.h> 255 #include <linux/skbuff.h> 256 #include <linux/scatterlist.h> 257 #include <linux/splice.h> 258 #include <linux/net.h> 259 #include <linux/socket.h> 260 #include <linux/random.h> 261 #include <linux/memblock.h> 262 #include <linux/highmem.h> 263 #include <linux/cache.h> 264 #include <linux/err.h> 265 #include <linux/time.h> 266 #include <linux/slab.h> 267 #include <linux/errqueue.h> 268 #include <linux/static_key.h> 269 #include <linux/btf.h> 270 271 #include <net/icmp.h> 272 #include <net/inet_common.h> 273 #include <net/inet_ecn.h> 274 #include <net/tcp.h> 275 #include <net/tcp_ecn.h> 276 #include <net/mptcp.h> 277 #include <net/proto_memory.h> 278 #include <net/xfrm.h> 279 #include <net/ip.h> 280 #include <net/psp.h> 281 #include <net/sock.h> 282 #include <net/rstreason.h> 283 284 #include <linux/uaccess.h> 285 #include <asm/ioctls.h> 286 #include <net/busy_poll.h> 287 #include <net/hotdata.h> 288 #include <trace/events/tcp.h> 289 #include <net/rps.h> 290 291 #include "../core/devmem.h" 292 293 /* Track pending CMSGs. */ 294 enum { 295 TCP_CMSG_INQ = 1, 296 TCP_CMSG_TS = 2 297 }; 298 299 DEFINE_PER_CPU(unsigned int, tcp_orphan_count); 300 EXPORT_PER_CPU_SYMBOL_GPL(tcp_orphan_count); 301 302 DEFINE_PER_CPU(u32, tcp_tw_isn); 303 EXPORT_PER_CPU_SYMBOL_GPL(tcp_tw_isn); 304 305 long sysctl_tcp_mem[3] __read_mostly; 306 EXPORT_IPV6_MOD(sysctl_tcp_mem); 307 308 DEFINE_PER_CPU(int, tcp_memory_per_cpu_fw_alloc); 309 EXPORT_PER_CPU_SYMBOL_GPL(tcp_memory_per_cpu_fw_alloc); 310 311 #if IS_ENABLED(CONFIG_SMC) 312 DEFINE_STATIC_KEY_FALSE(tcp_have_smc); 313 EXPORT_SYMBOL(tcp_have_smc); 314 #endif 315 316 /* 317 * Current number of TCP sockets. 318 */ 319 struct percpu_counter tcp_sockets_allocated ____cacheline_aligned_in_smp; 320 EXPORT_IPV6_MOD(tcp_sockets_allocated); 321 322 /* 323 * TCP splice context 324 */ 325 struct tcp_splice_state { 326 struct pipe_inode_info *pipe; 327 size_t len; 328 unsigned int flags; 329 }; 330 331 /* 332 * Pressure flag: try to collapse. 333 * Technical note: it is used by multiple contexts non atomically. 334 * All the __sk_mem_schedule() is of this nature: accounting 335 * is strict, actions are advisory and have some latency. 336 */ 337 unsigned long tcp_memory_pressure __read_mostly; 338 EXPORT_SYMBOL_GPL(tcp_memory_pressure); 339 340 void tcp_enter_memory_pressure(struct sock *sk) 341 { 342 unsigned long val; 343 344 if (READ_ONCE(tcp_memory_pressure)) 345 return; 346 val = jiffies; 347 348 if (!val) 349 val--; 350 if (!cmpxchg(&tcp_memory_pressure, 0, val)) 351 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES); 352 } 353 EXPORT_IPV6_MOD_GPL(tcp_enter_memory_pressure); 354 355 void tcp_leave_memory_pressure(struct sock *sk) 356 { 357 unsigned long val; 358 359 if (!READ_ONCE(tcp_memory_pressure)) 360 return; 361 val = xchg(&tcp_memory_pressure, 0); 362 if (val) 363 NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURESCHRONO, 364 jiffies_to_msecs(jiffies - val)); 365 } 366 EXPORT_IPV6_MOD_GPL(tcp_leave_memory_pressure); 367 368 /* Convert seconds to retransmits based on initial and max timeout */ 369 static u8 secs_to_retrans(int seconds, int timeout, int rto_max) 370 { 371 u8 res = 0; 372 373 if (seconds > 0) { 374 int period = timeout; 375 376 res = 1; 377 while (seconds > period && res < 255) { 378 res++; 379 timeout <<= 1; 380 if (timeout > rto_max) 381 timeout = rto_max; 382 period += timeout; 383 } 384 } 385 return res; 386 } 387 388 /* Convert retransmits to seconds based on initial and max timeout */ 389 static int retrans_to_secs(u8 retrans, int timeout, int rto_max) 390 { 391 int period = 0; 392 393 if (retrans > 0) { 394 period = timeout; 395 while (--retrans) { 396 timeout <<= 1; 397 if (timeout > rto_max) 398 timeout = rto_max; 399 period += timeout; 400 } 401 } 402 return period; 403 } 404 405 static u64 tcp_compute_delivery_rate(const struct tcp_sock *tp) 406 { 407 u32 rate = READ_ONCE(tp->rate_delivered); 408 u32 intv = READ_ONCE(tp->rate_interval_us); 409 u64 rate64 = 0; 410 411 if (rate && intv) { 412 rate64 = (u64)rate * tp->mss_cache * USEC_PER_SEC; 413 do_div(rate64, intv); 414 } 415 return rate64; 416 } 417 418 #ifdef CONFIG_TCP_MD5SIG 419 void tcp_md5_destruct_sock(struct sock *sk) 420 { 421 struct tcp_sock *tp = tcp_sk(sk); 422 423 if (tp->md5sig_info) { 424 425 tcp_clear_md5_list(sk); 426 kfree(rcu_replace_pointer(tp->md5sig_info, NULL, 1)); 427 static_branch_slow_dec_deferred(&tcp_md5_needed); 428 tcp_md5_release_sigpool(); 429 } 430 } 431 EXPORT_IPV6_MOD_GPL(tcp_md5_destruct_sock); 432 #endif 433 434 /* Address-family independent initialization for a tcp_sock. 435 * 436 * NOTE: A lot of things set to zero explicitly by call to 437 * sk_alloc() so need not be done here. 438 */ 439 void tcp_init_sock(struct sock *sk) 440 { 441 struct inet_connection_sock *icsk = inet_csk(sk); 442 struct tcp_sock *tp = tcp_sk(sk); 443 int rto_min_us, rto_max_ms; 444 445 tp->out_of_order_queue = RB_ROOT; 446 sk->tcp_rtx_queue = RB_ROOT; 447 tcp_init_xmit_timers(sk); 448 INIT_LIST_HEAD(&tp->tsq_node); 449 INIT_LIST_HEAD(&tp->tsorted_sent_queue); 450 451 icsk->icsk_rto = TCP_TIMEOUT_INIT; 452 453 rto_max_ms = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rto_max_ms); 454 icsk->icsk_rto_max = msecs_to_jiffies(rto_max_ms); 455 456 rto_min_us = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rto_min_us); 457 icsk->icsk_rto_min = usecs_to_jiffies(rto_min_us); 458 icsk->icsk_delack_max = TCP_DELACK_MAX; 459 tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT); 460 minmax_reset(&tp->rtt_min, tcp_jiffies32, ~0U); 461 462 /* So many TCP implementations out there (incorrectly) count the 463 * initial SYN frame in their delayed-ACK and congestion control 464 * algorithms that we must have the following bandaid to talk 465 * efficiently to them. -DaveM 466 */ 467 tcp_snd_cwnd_set(tp, TCP_INIT_CWND); 468 469 /* There's a bubble in the pipe until at least the first ACK. */ 470 tp->app_limited = ~0U; 471 tp->rate_app_limited = 1; 472 473 /* See draft-stevens-tcpca-spec-01 for discussion of the 474 * initialization of these values. 475 */ 476 tp->snd_ssthresh = TCP_INFINITE_SSTHRESH; 477 tp->snd_cwnd_clamp = ~0; 478 tp->mss_cache = TCP_MSS_DEFAULT; 479 480 tp->reordering = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reordering); 481 tcp_assign_congestion_control(sk); 482 483 tp->tsoffset = 0; 484 tp->rack.reo_wnd_steps = 1; 485 486 sk->sk_write_space = sk_stream_write_space; 487 sock_set_flag(sk, SOCK_USE_WRITE_QUEUE); 488 489 icsk->icsk_sync_mss = tcp_sync_mss; 490 491 WRITE_ONCE(sk->sk_sndbuf, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_wmem[1])); 492 WRITE_ONCE(sk->sk_rcvbuf, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[1])); 493 tcp_scaling_ratio_init(sk); 494 495 set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags); 496 sk_sockets_allocated_inc(sk); 497 xa_init_flags(&sk->sk_user_frags, XA_FLAGS_ALLOC1); 498 } 499 EXPORT_IPV6_MOD(tcp_init_sock); 500 501 static void tcp_tx_timestamp(struct sock *sk, struct sockcm_cookie *sockc) 502 { 503 struct sk_buff *skb = tcp_write_queue_tail(sk); 504 u32 tsflags = sockc->tsflags; 505 506 if (tsflags && skb) { 507 struct skb_shared_info *shinfo = skb_shinfo(skb); 508 struct tcp_skb_cb *tcb = TCP_SKB_CB(skb); 509 510 sock_tx_timestamp(sk, sockc, &shinfo->tx_flags); 511 if (tsflags & SOF_TIMESTAMPING_TX_ACK) 512 tcb->txstamp_ack |= TSTAMP_ACK_SK; 513 if (tsflags & SOF_TIMESTAMPING_TX_RECORD_MASK) 514 shinfo->tskey = TCP_SKB_CB(skb)->seq + skb->len - 1; 515 } 516 517 if (cgroup_bpf_enabled(CGROUP_SOCK_OPS) && 518 SK_BPF_CB_FLAG_TEST(sk, SK_BPF_CB_TX_TIMESTAMPING) && skb) 519 bpf_skops_tx_timestamping(sk, skb, BPF_SOCK_OPS_TSTAMP_SENDMSG_CB); 520 } 521 522 static bool tcp_stream_is_readable(struct sock *sk, int target) 523 { 524 if (tcp_epollin_ready(sk, target)) 525 return true; 526 return sk_is_readable(sk); 527 } 528 529 /* 530 * Wait for a TCP event. 531 * 532 * Note that we don't need to lock the socket, as the upper poll layers 533 * take care of normal races (between the test and the event) and we don't 534 * go look at any of the socket buffers directly. 535 */ 536 __poll_t tcp_poll(struct file *file, struct socket *sock, poll_table *wait) 537 { 538 __poll_t mask; 539 struct sock *sk = sock->sk; 540 const struct tcp_sock *tp = tcp_sk(sk); 541 u8 shutdown; 542 int state; 543 544 sock_poll_wait(file, sock, wait); 545 546 state = inet_sk_state_load(sk); 547 if (state == TCP_LISTEN) 548 return inet_csk_listen_poll(sk); 549 550 /* Socket is not locked. We are protected from async events 551 * by poll logic and correct handling of state changes 552 * made by other threads is impossible in any case. 553 */ 554 555 mask = 0; 556 557 /* 558 * EPOLLHUP is certainly not done right. But poll() doesn't 559 * have a notion of HUP in just one direction, and for a 560 * socket the read side is more interesting. 561 * 562 * Some poll() documentation says that EPOLLHUP is incompatible 563 * with the EPOLLOUT/POLLWR flags, so somebody should check this 564 * all. But careful, it tends to be safer to return too many 565 * bits than too few, and you can easily break real applications 566 * if you don't tell them that something has hung up! 567 * 568 * Check-me. 569 * 570 * Check number 1. EPOLLHUP is _UNMASKABLE_ event (see UNIX98 and 571 * our fs/select.c). It means that after we received EOF, 572 * poll always returns immediately, making impossible poll() on write() 573 * in state CLOSE_WAIT. One solution is evident --- to set EPOLLHUP 574 * if and only if shutdown has been made in both directions. 575 * Actually, it is interesting to look how Solaris and DUX 576 * solve this dilemma. I would prefer, if EPOLLHUP were maskable, 577 * then we could set it on SND_SHUTDOWN. BTW examples given 578 * in Stevens' books assume exactly this behaviour, it explains 579 * why EPOLLHUP is incompatible with EPOLLOUT. --ANK 580 * 581 * NOTE. Check for TCP_CLOSE is added. The goal is to prevent 582 * blocking on fresh not-connected or disconnected socket. --ANK 583 */ 584 shutdown = READ_ONCE(sk->sk_shutdown); 585 if (shutdown == SHUTDOWN_MASK || state == TCP_CLOSE) 586 mask |= EPOLLHUP; 587 if (shutdown & RCV_SHUTDOWN) 588 mask |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP; 589 590 /* Connected or passive Fast Open socket? */ 591 if (state != TCP_SYN_SENT && 592 (state != TCP_SYN_RECV || rcu_access_pointer(tp->fastopen_rsk))) { 593 int target = sock_rcvlowat(sk, 0, INT_MAX); 594 u16 urg_data = READ_ONCE(tp->urg_data); 595 596 if (unlikely(urg_data) && 597 READ_ONCE(tp->urg_seq) == READ_ONCE(tp->copied_seq) && 598 !sock_flag(sk, SOCK_URGINLINE)) 599 target++; 600 601 if (tcp_stream_is_readable(sk, target)) 602 mask |= EPOLLIN | EPOLLRDNORM; 603 604 if (!(shutdown & SEND_SHUTDOWN)) { 605 if (__sk_stream_is_writeable(sk, 1)) { 606 mask |= EPOLLOUT | EPOLLWRNORM; 607 } else { /* send SIGIO later */ 608 sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk); 609 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); 610 611 /* Race breaker. If space is freed after 612 * wspace test but before the flags are set, 613 * IO signal will be lost. Memory barrier 614 * pairs with the input side. 615 */ 616 smp_mb__after_atomic(); 617 if (__sk_stream_is_writeable(sk, 1)) 618 mask |= EPOLLOUT | EPOLLWRNORM; 619 } 620 } else 621 mask |= EPOLLOUT | EPOLLWRNORM; 622 623 if (urg_data & TCP_URG_VALID) 624 mask |= EPOLLPRI; 625 } else if (state == TCP_SYN_SENT && 626 inet_test_bit(DEFER_CONNECT, sk)) { 627 /* Active TCP fastopen socket with defer_connect 628 * Return EPOLLOUT so application can call write() 629 * in order for kernel to generate SYN+data 630 */ 631 mask |= EPOLLOUT | EPOLLWRNORM; 632 } 633 /* This barrier is coupled with smp_wmb() in tcp_done_with_error() */ 634 smp_rmb(); 635 if (READ_ONCE(sk->sk_err) || 636 !skb_queue_empty_lockless(&sk->sk_error_queue)) 637 mask |= EPOLLERR; 638 639 return mask; 640 } 641 EXPORT_SYMBOL(tcp_poll); 642 643 int tcp_ioctl(struct sock *sk, int cmd, int *karg) 644 { 645 struct tcp_sock *tp = tcp_sk(sk); 646 int answ; 647 bool slow; 648 649 switch (cmd) { 650 case SIOCINQ: 651 if (sk->sk_state == TCP_LISTEN) 652 return -EINVAL; 653 654 slow = lock_sock_fast(sk); 655 answ = tcp_inq(sk); 656 unlock_sock_fast(sk, slow); 657 break; 658 case SIOCATMARK: 659 answ = READ_ONCE(tp->urg_data) && 660 READ_ONCE(tp->urg_seq) == READ_ONCE(tp->copied_seq); 661 break; 662 case SIOCOUTQ: 663 if (sk->sk_state == TCP_LISTEN) 664 return -EINVAL; 665 666 if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) 667 answ = 0; 668 else 669 answ = READ_ONCE(tp->write_seq) - tp->snd_una; 670 break; 671 case SIOCOUTQNSD: 672 if (sk->sk_state == TCP_LISTEN) 673 return -EINVAL; 674 675 if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) 676 answ = 0; 677 else 678 answ = READ_ONCE(tp->write_seq) - 679 READ_ONCE(tp->snd_nxt); 680 break; 681 default: 682 return -ENOIOCTLCMD; 683 } 684 685 *karg = answ; 686 return 0; 687 } 688 EXPORT_IPV6_MOD(tcp_ioctl); 689 690 void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb) 691 { 692 TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH; 693 tp->pushed_seq = tp->write_seq; 694 } 695 696 static inline bool forced_push(const struct tcp_sock *tp) 697 { 698 return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1)); 699 } 700 701 void tcp_skb_entail(struct sock *sk, struct sk_buff *skb) 702 { 703 struct tcp_sock *tp = tcp_sk(sk); 704 struct tcp_skb_cb *tcb = TCP_SKB_CB(skb); 705 706 tcb->seq = tcb->end_seq = tp->write_seq; 707 tcb->tcp_flags = TCPHDR_ACK; 708 __skb_header_release(skb); 709 psp_enqueue_set_decrypted(sk, skb); 710 tcp_add_write_queue_tail(sk, skb); 711 sk_wmem_queued_add(sk, skb->truesize); 712 sk_mem_charge(sk, skb->truesize); 713 if (tp->nonagle & TCP_NAGLE_PUSH) 714 tp->nonagle &= ~TCP_NAGLE_PUSH; 715 716 tcp_slow_start_after_idle_check(sk); 717 } 718 719 static inline void tcp_mark_urg(struct tcp_sock *tp, int flags) 720 { 721 if (flags & MSG_OOB) 722 tp->snd_up = tp->write_seq; 723 } 724 725 /* If a not yet filled skb is pushed, do not send it if 726 * we have data packets in Qdisc or NIC queues : 727 * Because TX completion will happen shortly, it gives a chance 728 * to coalesce future sendmsg() payload into this skb, without 729 * need for a timer, and with no latency trade off. 730 * As packets containing data payload have a bigger truesize 731 * than pure acks (dataless) packets, the last checks prevent 732 * autocorking if we only have an ACK in Qdisc/NIC queues, 733 * or if TX completion was delayed after we processed ACK packet. 734 */ 735 static bool tcp_should_autocork(struct sock *sk, struct sk_buff *skb, 736 int size_goal) 737 { 738 return skb->len < size_goal && 739 READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_autocorking) && 740 !tcp_rtx_queue_empty(sk) && 741 refcount_read(&sk->sk_wmem_alloc) > skb->truesize && 742 tcp_skb_can_collapse_to(skb); 743 } 744 745 void tcp_push(struct sock *sk, int flags, int mss_now, 746 int nonagle, int size_goal) 747 { 748 struct tcp_sock *tp = tcp_sk(sk); 749 struct sk_buff *skb; 750 751 skb = tcp_write_queue_tail(sk); 752 if (!skb) 753 return; 754 if (!(flags & MSG_MORE) || forced_push(tp)) 755 tcp_mark_push(tp, skb); 756 757 tcp_mark_urg(tp, flags); 758 759 if (tcp_should_autocork(sk, skb, size_goal)) { 760 761 /* avoid atomic op if TSQ_THROTTLED bit is already set */ 762 if (!test_bit(TSQ_THROTTLED, &sk->sk_tsq_flags)) { 763 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAUTOCORKING); 764 set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags); 765 smp_mb__after_atomic(); 766 } 767 /* It is possible TX completion already happened 768 * before we set TSQ_THROTTLED. 769 */ 770 if (refcount_read(&sk->sk_wmem_alloc) > skb->truesize) 771 return; 772 } 773 774 if (flags & MSG_MORE) 775 nonagle = TCP_NAGLE_CORK; 776 777 __tcp_push_pending_frames(sk, mss_now, nonagle); 778 } 779 780 static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb, 781 unsigned int offset, size_t len) 782 { 783 struct tcp_splice_state *tss = rd_desc->arg.data; 784 int ret; 785 786 ret = skb_splice_bits(skb, skb->sk, offset, tss->pipe, 787 min(rd_desc->count, len), tss->flags); 788 if (ret > 0) 789 rd_desc->count -= ret; 790 return ret; 791 } 792 793 static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss) 794 { 795 /* Store TCP splice context information in read_descriptor_t. */ 796 read_descriptor_t rd_desc = { 797 .arg.data = tss, 798 .count = tss->len, 799 }; 800 801 return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv); 802 } 803 804 /** 805 * tcp_splice_read - splice data from TCP socket to a pipe 806 * @sock: socket to splice from 807 * @ppos: position (not valid) 808 * @pipe: pipe to splice to 809 * @len: number of bytes to splice 810 * @flags: splice modifier flags 811 * 812 * Description: 813 * Will read pages from given socket and fill them into a pipe. 814 * 815 **/ 816 ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos, 817 struct pipe_inode_info *pipe, size_t len, 818 unsigned int flags) 819 { 820 struct sock *sk = sock->sk; 821 struct tcp_splice_state tss = { 822 .pipe = pipe, 823 .len = len, 824 .flags = flags, 825 }; 826 long timeo; 827 ssize_t spliced; 828 int ret; 829 830 sock_rps_record_flow(sk); 831 /* 832 * We can't seek on a socket input 833 */ 834 if (unlikely(*ppos)) 835 return -ESPIPE; 836 837 ret = spliced = 0; 838 839 lock_sock(sk); 840 841 timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK); 842 while (tss.len) { 843 ret = __tcp_splice_read(sk, &tss); 844 if (ret < 0) 845 break; 846 else if (!ret) { 847 if (spliced) 848 break; 849 if (sock_flag(sk, SOCK_DONE)) 850 break; 851 if (sk->sk_err) { 852 ret = sock_error(sk); 853 break; 854 } 855 if (sk->sk_shutdown & RCV_SHUTDOWN) 856 break; 857 if (sk->sk_state == TCP_CLOSE) { 858 /* 859 * This occurs when user tries to read 860 * from never connected socket. 861 */ 862 ret = -ENOTCONN; 863 break; 864 } 865 if (!timeo) { 866 ret = -EAGAIN; 867 break; 868 } 869 /* if __tcp_splice_read() got nothing while we have 870 * an skb in receive queue, we do not want to loop. 871 * This might happen with URG data. 872 */ 873 if (!skb_queue_empty(&sk->sk_receive_queue)) 874 break; 875 ret = sk_wait_data(sk, &timeo, NULL); 876 if (ret < 0) 877 break; 878 if (signal_pending(current)) { 879 ret = sock_intr_errno(timeo); 880 break; 881 } 882 continue; 883 } 884 tss.len -= ret; 885 spliced += ret; 886 887 if (!tss.len || !timeo) 888 break; 889 release_sock(sk); 890 lock_sock(sk); 891 892 if (sk->sk_err || sk->sk_state == TCP_CLOSE || 893 (sk->sk_shutdown & RCV_SHUTDOWN) || 894 signal_pending(current)) 895 break; 896 } 897 898 release_sock(sk); 899 900 if (spliced) 901 return spliced; 902 903 return ret; 904 } 905 EXPORT_IPV6_MOD(tcp_splice_read); 906 907 struct sk_buff *tcp_stream_alloc_skb(struct sock *sk, gfp_t gfp, 908 bool force_schedule) 909 { 910 struct sk_buff *skb; 911 912 skb = alloc_skb_fclone(MAX_TCP_HEADER, gfp); 913 if (likely(skb)) { 914 bool mem_scheduled; 915 916 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb)); 917 if (force_schedule) { 918 mem_scheduled = true; 919 sk_forced_mem_schedule(sk, skb->truesize); 920 } else { 921 mem_scheduled = sk_wmem_schedule(sk, skb->truesize); 922 } 923 if (likely(mem_scheduled)) { 924 skb_reserve(skb, MAX_TCP_HEADER); 925 skb->ip_summed = CHECKSUM_PARTIAL; 926 INIT_LIST_HEAD(&skb->tcp_tsorted_anchor); 927 return skb; 928 } 929 __kfree_skb(skb); 930 } else { 931 sk->sk_prot->enter_memory_pressure(sk); 932 sk_stream_moderate_sndbuf(sk); 933 } 934 return NULL; 935 } 936 937 static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now, 938 int large_allowed) 939 { 940 struct tcp_sock *tp = tcp_sk(sk); 941 u32 new_size_goal, size_goal; 942 943 if (!large_allowed) 944 return mss_now; 945 946 /* Note : tcp_tso_autosize() will eventually split this later */ 947 new_size_goal = tcp_bound_to_half_wnd(tp, sk->sk_gso_max_size); 948 949 /* We try hard to avoid divides here */ 950 size_goal = tp->gso_segs * mss_now; 951 if (unlikely(new_size_goal < size_goal || 952 new_size_goal >= size_goal + mss_now)) { 953 tp->gso_segs = min_t(u16, new_size_goal / mss_now, 954 sk->sk_gso_max_segs); 955 size_goal = tp->gso_segs * mss_now; 956 } 957 958 return max(size_goal, mss_now); 959 } 960 961 int tcp_send_mss(struct sock *sk, int *size_goal, int flags) 962 { 963 int mss_now; 964 965 mss_now = tcp_current_mss(sk); 966 *size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB)); 967 968 return mss_now; 969 } 970 971 /* In some cases, sendmsg() could have added an skb to the write queue, 972 * but failed adding payload on it. We need to remove it to consume less 973 * memory, but more importantly be able to generate EPOLLOUT for Edge Trigger 974 * epoll() users. Another reason is that tcp_write_xmit() does not like 975 * finding an empty skb in the write queue. 976 */ 977 void tcp_remove_empty_skb(struct sock *sk) 978 { 979 struct sk_buff *skb = tcp_write_queue_tail(sk); 980 981 if (skb && TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq) { 982 tcp_unlink_write_queue(skb, sk); 983 if (tcp_write_queue_empty(sk)) 984 tcp_chrono_stop(sk, TCP_CHRONO_BUSY); 985 tcp_wmem_free_skb(sk, skb); 986 } 987 } 988 989 /* skb changing from pure zc to mixed, must charge zc */ 990 static int tcp_downgrade_zcopy_pure(struct sock *sk, struct sk_buff *skb) 991 { 992 if (unlikely(skb_zcopy_pure(skb))) { 993 u32 extra = skb->truesize - 994 SKB_TRUESIZE(skb_end_offset(skb)); 995 996 if (!sk_wmem_schedule(sk, extra)) 997 return -ENOMEM; 998 999 sk_mem_charge(sk, extra); 1000 skb_shinfo(skb)->flags &= ~SKBFL_PURE_ZEROCOPY; 1001 } 1002 return 0; 1003 } 1004 1005 1006 int tcp_wmem_schedule(struct sock *sk, int copy) 1007 { 1008 int left; 1009 1010 if (likely(sk_wmem_schedule(sk, copy))) 1011 return copy; 1012 1013 /* We could be in trouble if we have nothing queued. 1014 * Use whatever is left in sk->sk_forward_alloc and tcp_wmem[0] 1015 * to guarantee some progress. 1016 */ 1017 left = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_wmem[0]) - sk->sk_wmem_queued; 1018 if (left > 0) 1019 sk_forced_mem_schedule(sk, min(left, copy)); 1020 return min(copy, sk->sk_forward_alloc); 1021 } 1022 1023 void tcp_free_fastopen_req(struct tcp_sock *tp) 1024 { 1025 if (tp->fastopen_req) { 1026 kfree(tp->fastopen_req); 1027 tp->fastopen_req = NULL; 1028 } 1029 } 1030 1031 int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg, int *copied, 1032 size_t size, struct ubuf_info *uarg) 1033 { 1034 struct tcp_sock *tp = tcp_sk(sk); 1035 struct inet_sock *inet = inet_sk(sk); 1036 struct sockaddr *uaddr = msg->msg_name; 1037 int err, flags; 1038 1039 if (!(READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_fastopen) & 1040 TFO_CLIENT_ENABLE) || 1041 (uaddr && msg->msg_namelen >= sizeof(uaddr->sa_family) && 1042 uaddr->sa_family == AF_UNSPEC)) 1043 return -EOPNOTSUPP; 1044 if (tp->fastopen_req) 1045 return -EALREADY; /* Another Fast Open is in progress */ 1046 1047 tp->fastopen_req = kzalloc(sizeof(struct tcp_fastopen_request), 1048 sk->sk_allocation); 1049 if (unlikely(!tp->fastopen_req)) 1050 return -ENOBUFS; 1051 tp->fastopen_req->data = msg; 1052 tp->fastopen_req->size = size; 1053 tp->fastopen_req->uarg = uarg; 1054 1055 if (inet_test_bit(DEFER_CONNECT, sk)) { 1056 err = tcp_connect(sk); 1057 /* Same failure procedure as in tcp_v4/6_connect */ 1058 if (err) { 1059 tcp_set_state(sk, TCP_CLOSE); 1060 inet->inet_dport = 0; 1061 sk->sk_route_caps = 0; 1062 } 1063 } 1064 flags = (msg->msg_flags & MSG_DONTWAIT) ? O_NONBLOCK : 0; 1065 err = __inet_stream_connect(sk->sk_socket, uaddr, 1066 msg->msg_namelen, flags, 1); 1067 /* fastopen_req could already be freed in __inet_stream_connect 1068 * if the connection times out or gets rst 1069 */ 1070 if (tp->fastopen_req) { 1071 *copied = tp->fastopen_req->copied; 1072 tcp_free_fastopen_req(tp); 1073 inet_clear_bit(DEFER_CONNECT, sk); 1074 } 1075 return err; 1076 } 1077 1078 int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size) 1079 { 1080 struct net_devmem_dmabuf_binding *binding = NULL; 1081 struct tcp_sock *tp = tcp_sk(sk); 1082 struct ubuf_info *uarg = NULL; 1083 struct sk_buff *skb; 1084 struct sockcm_cookie sockc; 1085 int flags, err, copied = 0; 1086 int mss_now = 0, size_goal, copied_syn = 0; 1087 int process_backlog = 0; 1088 int sockc_err = 0; 1089 int zc = 0; 1090 long timeo; 1091 1092 flags = msg->msg_flags; 1093 1094 sockc = (struct sockcm_cookie){ .tsflags = READ_ONCE(sk->sk_tsflags) }; 1095 if (msg->msg_controllen) { 1096 sockc_err = sock_cmsg_send(sk, msg, &sockc); 1097 /* Don't return error until MSG_FASTOPEN has been processed; 1098 * that may succeed even if the cmsg is invalid. 1099 */ 1100 } 1101 1102 if ((flags & MSG_ZEROCOPY) && size) { 1103 if (msg->msg_ubuf) { 1104 uarg = msg->msg_ubuf; 1105 if (sk->sk_route_caps & NETIF_F_SG) 1106 zc = MSG_ZEROCOPY; 1107 } else if (sock_flag(sk, SOCK_ZEROCOPY)) { 1108 skb = tcp_write_queue_tail(sk); 1109 uarg = msg_zerocopy_realloc(sk, size, skb_zcopy(skb), 1110 !sockc_err && sockc.dmabuf_id); 1111 if (!uarg) { 1112 err = -ENOBUFS; 1113 goto out_err; 1114 } 1115 if (sk->sk_route_caps & NETIF_F_SG) 1116 zc = MSG_ZEROCOPY; 1117 else 1118 uarg_to_msgzc(uarg)->zerocopy = 0; 1119 1120 if (!sockc_err && sockc.dmabuf_id) { 1121 binding = net_devmem_get_binding(sk, sockc.dmabuf_id); 1122 if (IS_ERR(binding)) { 1123 err = PTR_ERR(binding); 1124 binding = NULL; 1125 goto out_err; 1126 } 1127 } 1128 } 1129 } else if (unlikely(msg->msg_flags & MSG_SPLICE_PAGES) && size) { 1130 if (sk->sk_route_caps & NETIF_F_SG) 1131 zc = MSG_SPLICE_PAGES; 1132 } 1133 1134 if (!sockc_err && sockc.dmabuf_id && 1135 (!(flags & MSG_ZEROCOPY) || !sock_flag(sk, SOCK_ZEROCOPY))) { 1136 err = -EINVAL; 1137 goto out_err; 1138 } 1139 1140 if (unlikely(flags & MSG_FASTOPEN || 1141 inet_test_bit(DEFER_CONNECT, sk)) && 1142 !tp->repair) { 1143 err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size, uarg); 1144 if (err == -EINPROGRESS && copied_syn > 0) 1145 goto out; 1146 else if (err) 1147 goto out_err; 1148 } 1149 1150 timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT); 1151 1152 tcp_rate_check_app_limited(sk); /* is sending application-limited? */ 1153 1154 /* Wait for a connection to finish. One exception is TCP Fast Open 1155 * (passive side) where data is allowed to be sent before a connection 1156 * is fully established. 1157 */ 1158 if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) && 1159 !tcp_passive_fastopen(sk)) { 1160 err = sk_stream_wait_connect(sk, &timeo); 1161 if (err != 0) 1162 goto do_error; 1163 } 1164 1165 if (unlikely(tp->repair)) { 1166 if (tp->repair_queue == TCP_RECV_QUEUE) { 1167 copied = tcp_send_rcvq(sk, msg, size); 1168 goto out_nopush; 1169 } 1170 1171 err = -EINVAL; 1172 if (tp->repair_queue == TCP_NO_QUEUE) 1173 goto out_err; 1174 1175 /* 'common' sending to sendq */ 1176 } 1177 1178 if (sockc_err) { 1179 err = sockc_err; 1180 goto out_err; 1181 } 1182 1183 /* This should be in poll */ 1184 sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk); 1185 1186 /* Ok commence sending. */ 1187 copied = 0; 1188 1189 restart: 1190 mss_now = tcp_send_mss(sk, &size_goal, flags); 1191 1192 err = -EPIPE; 1193 if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN)) 1194 goto do_error; 1195 1196 while (msg_data_left(msg)) { 1197 int copy = 0; 1198 1199 skb = tcp_write_queue_tail(sk); 1200 if (skb) 1201 copy = size_goal - skb->len; 1202 1203 trace_tcp_sendmsg_locked(sk, msg, skb, size_goal); 1204 1205 if (copy <= 0 || !tcp_skb_can_collapse_to(skb)) { 1206 bool first_skb; 1207 1208 new_segment: 1209 if (!sk_stream_memory_free(sk)) 1210 goto wait_for_space; 1211 1212 if (unlikely(process_backlog >= 16)) { 1213 process_backlog = 0; 1214 if (sk_flush_backlog(sk)) 1215 goto restart; 1216 } 1217 first_skb = tcp_rtx_and_write_queues_empty(sk); 1218 skb = tcp_stream_alloc_skb(sk, sk->sk_allocation, 1219 first_skb); 1220 if (!skb) 1221 goto wait_for_space; 1222 1223 process_backlog++; 1224 1225 #ifdef CONFIG_SKB_DECRYPTED 1226 skb->decrypted = !!(flags & MSG_SENDPAGE_DECRYPTED); 1227 #endif 1228 tcp_skb_entail(sk, skb); 1229 copy = size_goal; 1230 1231 /* All packets are restored as if they have 1232 * already been sent. skb_mstamp_ns isn't set to 1233 * avoid wrong rtt estimation. 1234 */ 1235 if (tp->repair) 1236 TCP_SKB_CB(skb)->sacked |= TCPCB_REPAIRED; 1237 } 1238 1239 /* Try to append data to the end of skb. */ 1240 if (copy > msg_data_left(msg)) 1241 copy = msg_data_left(msg); 1242 1243 if (zc == 0) { 1244 bool merge = true; 1245 int i = skb_shinfo(skb)->nr_frags; 1246 struct page_frag *pfrag = sk_page_frag(sk); 1247 1248 if (!sk_page_frag_refill(sk, pfrag)) 1249 goto wait_for_space; 1250 1251 if (!skb_can_coalesce(skb, i, pfrag->page, 1252 pfrag->offset)) { 1253 if (i >= READ_ONCE(net_hotdata.sysctl_max_skb_frags)) { 1254 tcp_mark_push(tp, skb); 1255 goto new_segment; 1256 } 1257 merge = false; 1258 } 1259 1260 copy = min_t(int, copy, pfrag->size - pfrag->offset); 1261 1262 if (unlikely(skb_zcopy_pure(skb) || skb_zcopy_managed(skb))) { 1263 if (tcp_downgrade_zcopy_pure(sk, skb)) 1264 goto wait_for_space; 1265 skb_zcopy_downgrade_managed(skb); 1266 } 1267 1268 copy = tcp_wmem_schedule(sk, copy); 1269 if (!copy) 1270 goto wait_for_space; 1271 1272 err = skb_copy_to_page_nocache(sk, &msg->msg_iter, skb, 1273 pfrag->page, 1274 pfrag->offset, 1275 copy); 1276 if (err) 1277 goto do_error; 1278 1279 /* Update the skb. */ 1280 if (merge) { 1281 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); 1282 } else { 1283 skb_fill_page_desc(skb, i, pfrag->page, 1284 pfrag->offset, copy); 1285 page_ref_inc(pfrag->page); 1286 } 1287 pfrag->offset += copy; 1288 } else if (zc == MSG_ZEROCOPY) { 1289 /* First append to a fragless skb builds initial 1290 * pure zerocopy skb 1291 */ 1292 if (!skb->len) 1293 skb_shinfo(skb)->flags |= SKBFL_PURE_ZEROCOPY; 1294 1295 if (!skb_zcopy_pure(skb)) { 1296 copy = tcp_wmem_schedule(sk, copy); 1297 if (!copy) 1298 goto wait_for_space; 1299 } 1300 1301 err = skb_zerocopy_iter_stream(sk, skb, msg, copy, uarg, 1302 binding); 1303 if (err == -EMSGSIZE || err == -EEXIST) { 1304 tcp_mark_push(tp, skb); 1305 goto new_segment; 1306 } 1307 if (err < 0) 1308 goto do_error; 1309 copy = err; 1310 } else if (zc == MSG_SPLICE_PAGES) { 1311 /* Splice in data if we can; copy if we can't. */ 1312 if (tcp_downgrade_zcopy_pure(sk, skb)) 1313 goto wait_for_space; 1314 copy = tcp_wmem_schedule(sk, copy); 1315 if (!copy) 1316 goto wait_for_space; 1317 1318 err = skb_splice_from_iter(skb, &msg->msg_iter, copy); 1319 if (err < 0) { 1320 if (err == -EMSGSIZE) { 1321 tcp_mark_push(tp, skb); 1322 goto new_segment; 1323 } 1324 goto do_error; 1325 } 1326 copy = err; 1327 1328 if (!(flags & MSG_NO_SHARED_FRAGS)) 1329 skb_shinfo(skb)->flags |= SKBFL_SHARED_FRAG; 1330 1331 sk_wmem_queued_add(sk, copy); 1332 sk_mem_charge(sk, copy); 1333 } 1334 1335 if (!copied) 1336 TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH; 1337 1338 WRITE_ONCE(tp->write_seq, tp->write_seq + copy); 1339 TCP_SKB_CB(skb)->end_seq += copy; 1340 tcp_skb_pcount_set(skb, 0); 1341 1342 copied += copy; 1343 if (!msg_data_left(msg)) { 1344 if (unlikely(flags & MSG_EOR)) 1345 TCP_SKB_CB(skb)->eor = 1; 1346 goto out; 1347 } 1348 1349 if (skb->len < size_goal || (flags & MSG_OOB) || unlikely(tp->repair)) 1350 continue; 1351 1352 if (forced_push(tp)) { 1353 tcp_mark_push(tp, skb); 1354 __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH); 1355 } else if (skb == tcp_send_head(sk)) 1356 tcp_push_one(sk, mss_now); 1357 continue; 1358 1359 wait_for_space: 1360 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); 1361 tcp_remove_empty_skb(sk); 1362 if (copied) 1363 tcp_push(sk, flags & ~MSG_MORE, mss_now, 1364 TCP_NAGLE_PUSH, size_goal); 1365 1366 err = sk_stream_wait_memory(sk, &timeo); 1367 if (err != 0) 1368 goto do_error; 1369 1370 mss_now = tcp_send_mss(sk, &size_goal, flags); 1371 } 1372 1373 out: 1374 if (copied) { 1375 tcp_tx_timestamp(sk, &sockc); 1376 tcp_push(sk, flags, mss_now, tp->nonagle, size_goal); 1377 } 1378 out_nopush: 1379 /* msg->msg_ubuf is pinned by the caller so we don't take extra refs */ 1380 if (uarg && !msg->msg_ubuf) 1381 net_zcopy_put(uarg); 1382 if (binding) 1383 net_devmem_dmabuf_binding_put(binding); 1384 return copied + copied_syn; 1385 1386 do_error: 1387 tcp_remove_empty_skb(sk); 1388 1389 if (copied + copied_syn) 1390 goto out; 1391 out_err: 1392 /* msg->msg_ubuf is pinned by the caller so we don't take extra refs */ 1393 if (uarg && !msg->msg_ubuf) 1394 net_zcopy_put_abort(uarg, true); 1395 err = sk_stream_error(sk, flags, err); 1396 /* make sure we wake any epoll edge trigger waiter */ 1397 if (unlikely(tcp_rtx_and_write_queues_empty(sk) && err == -EAGAIN)) { 1398 sk->sk_write_space(sk); 1399 tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED); 1400 } 1401 if (binding) 1402 net_devmem_dmabuf_binding_put(binding); 1403 1404 return err; 1405 } 1406 EXPORT_SYMBOL_GPL(tcp_sendmsg_locked); 1407 1408 int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size) 1409 { 1410 int ret; 1411 1412 lock_sock(sk); 1413 ret = tcp_sendmsg_locked(sk, msg, size); 1414 release_sock(sk); 1415 1416 return ret; 1417 } 1418 EXPORT_SYMBOL(tcp_sendmsg); 1419 1420 void tcp_splice_eof(struct socket *sock) 1421 { 1422 struct sock *sk = sock->sk; 1423 struct tcp_sock *tp = tcp_sk(sk); 1424 int mss_now, size_goal; 1425 1426 if (!tcp_write_queue_tail(sk)) 1427 return; 1428 1429 lock_sock(sk); 1430 mss_now = tcp_send_mss(sk, &size_goal, 0); 1431 tcp_push(sk, 0, mss_now, tp->nonagle, size_goal); 1432 release_sock(sk); 1433 } 1434 EXPORT_IPV6_MOD_GPL(tcp_splice_eof); 1435 1436 /* 1437 * Handle reading urgent data. BSD has very simple semantics for 1438 * this, no blocking and very strange errors 8) 1439 */ 1440 1441 static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags) 1442 { 1443 struct tcp_sock *tp = tcp_sk(sk); 1444 1445 /* No URG data to read. */ 1446 if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data || 1447 tp->urg_data == TCP_URG_READ) 1448 return -EINVAL; /* Yes this is right ! */ 1449 1450 if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE)) 1451 return -ENOTCONN; 1452 1453 if (tp->urg_data & TCP_URG_VALID) { 1454 int err = 0; 1455 char c = tp->urg_data; 1456 1457 if (!(flags & MSG_PEEK)) 1458 WRITE_ONCE(tp->urg_data, TCP_URG_READ); 1459 1460 /* Read urgent data. */ 1461 msg->msg_flags |= MSG_OOB; 1462 1463 if (len > 0) { 1464 if (!(flags & MSG_TRUNC)) 1465 err = memcpy_to_msg(msg, &c, 1); 1466 len = 1; 1467 } else 1468 msg->msg_flags |= MSG_TRUNC; 1469 1470 return err ? -EFAULT : len; 1471 } 1472 1473 if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN)) 1474 return 0; 1475 1476 /* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and 1477 * the available implementations agree in this case: 1478 * this call should never block, independent of the 1479 * blocking state of the socket. 1480 * Mike <pall@rz.uni-karlsruhe.de> 1481 */ 1482 return -EAGAIN; 1483 } 1484 1485 static int tcp_peek_sndq(struct sock *sk, struct msghdr *msg, int len) 1486 { 1487 struct sk_buff *skb; 1488 int copied = 0, err = 0; 1489 1490 skb_rbtree_walk(skb, &sk->tcp_rtx_queue) { 1491 err = skb_copy_datagram_msg(skb, 0, msg, skb->len); 1492 if (err) 1493 return err; 1494 copied += skb->len; 1495 } 1496 1497 skb_queue_walk(&sk->sk_write_queue, skb) { 1498 err = skb_copy_datagram_msg(skb, 0, msg, skb->len); 1499 if (err) 1500 break; 1501 1502 copied += skb->len; 1503 } 1504 1505 return err ?: copied; 1506 } 1507 1508 /* Clean up the receive buffer for full frames taken by the user, 1509 * then send an ACK if necessary. COPIED is the number of bytes 1510 * tcp_recvmsg has given to the user so far, it speeds up the 1511 * calculation of whether or not we must ACK for the sake of 1512 * a window update. 1513 */ 1514 void __tcp_cleanup_rbuf(struct sock *sk, int copied) 1515 { 1516 struct tcp_sock *tp = tcp_sk(sk); 1517 bool time_to_ack = false; 1518 1519 if (inet_csk_ack_scheduled(sk)) { 1520 const struct inet_connection_sock *icsk = inet_csk(sk); 1521 1522 if (/* Once-per-two-segments ACK was not sent by tcp_input.c */ 1523 tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss || 1524 /* 1525 * If this read emptied read buffer, we send ACK, if 1526 * connection is not bidirectional, user drained 1527 * receive buffer and there was a small segment 1528 * in queue. 1529 */ 1530 (copied > 0 && 1531 ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) || 1532 ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) && 1533 !inet_csk_in_pingpong_mode(sk))) && 1534 !atomic_read(&sk->sk_rmem_alloc))) 1535 time_to_ack = true; 1536 } 1537 1538 /* We send an ACK if we can now advertise a non-zero window 1539 * which has been raised "significantly". 1540 * 1541 * Even if window raised up to infinity, do not send window open ACK 1542 * in states, where we will not receive more. It is useless. 1543 */ 1544 if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) { 1545 __u32 rcv_window_now = tcp_receive_window(tp); 1546 1547 /* Optimize, __tcp_select_window() is not cheap. */ 1548 if (2*rcv_window_now <= tp->window_clamp) { 1549 __u32 new_window = __tcp_select_window(sk); 1550 1551 /* Send ACK now, if this read freed lots of space 1552 * in our buffer. Certainly, new_window is new window. 1553 * We can advertise it now, if it is not less than current one. 1554 * "Lots" means "at least twice" here. 1555 */ 1556 if (new_window && new_window >= 2 * rcv_window_now) 1557 time_to_ack = true; 1558 } 1559 } 1560 if (time_to_ack) 1561 tcp_send_ack(sk); 1562 } 1563 1564 void tcp_cleanup_rbuf(struct sock *sk, int copied) 1565 { 1566 struct sk_buff *skb = skb_peek(&sk->sk_receive_queue); 1567 struct tcp_sock *tp = tcp_sk(sk); 1568 1569 WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq), 1570 "cleanup rbuf bug: copied %X seq %X rcvnxt %X\n", 1571 tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt); 1572 __tcp_cleanup_rbuf(sk, copied); 1573 } 1574 1575 static void tcp_eat_recv_skb(struct sock *sk, struct sk_buff *skb) 1576 { 1577 __skb_unlink(skb, &sk->sk_receive_queue); 1578 if (likely(skb->destructor == sock_rfree)) { 1579 sock_rfree(skb); 1580 skb->destructor = NULL; 1581 skb->sk = NULL; 1582 return skb_attempt_defer_free(skb); 1583 } 1584 __kfree_skb(skb); 1585 } 1586 1587 struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off) 1588 { 1589 struct sk_buff *skb; 1590 u32 offset; 1591 1592 while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) { 1593 offset = seq - TCP_SKB_CB(skb)->seq; 1594 if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) { 1595 pr_err_once("%s: found a SYN, please report !\n", __func__); 1596 offset--; 1597 } 1598 if (offset < skb->len || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)) { 1599 *off = offset; 1600 return skb; 1601 } 1602 /* This looks weird, but this can happen if TCP collapsing 1603 * splitted a fat GRO packet, while we released socket lock 1604 * in skb_splice_bits() 1605 */ 1606 tcp_eat_recv_skb(sk, skb); 1607 } 1608 return NULL; 1609 } 1610 EXPORT_SYMBOL(tcp_recv_skb); 1611 1612 /* 1613 * This routine provides an alternative to tcp_recvmsg() for routines 1614 * that would like to handle copying from skbuffs directly in 'sendfile' 1615 * fashion. 1616 * Note: 1617 * - It is assumed that the socket was locked by the caller. 1618 * - The routine does not block. 1619 * - At present, there is no support for reading OOB data 1620 * or for 'peeking' the socket using this routine 1621 * (although both would be easy to implement). 1622 */ 1623 static int __tcp_read_sock(struct sock *sk, read_descriptor_t *desc, 1624 sk_read_actor_t recv_actor, bool noack, 1625 u32 *copied_seq) 1626 { 1627 struct sk_buff *skb; 1628 struct tcp_sock *tp = tcp_sk(sk); 1629 u32 seq = *copied_seq; 1630 u32 offset; 1631 int copied = 0; 1632 1633 if (sk->sk_state == TCP_LISTEN) 1634 return -ENOTCONN; 1635 while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) { 1636 if (offset < skb->len) { 1637 int used; 1638 size_t len; 1639 1640 len = skb->len - offset; 1641 /* Stop reading if we hit a patch of urgent data */ 1642 if (unlikely(tp->urg_data)) { 1643 u32 urg_offset = tp->urg_seq - seq; 1644 if (urg_offset < len) 1645 len = urg_offset; 1646 if (!len) 1647 break; 1648 } 1649 used = recv_actor(desc, skb, offset, len); 1650 if (used <= 0) { 1651 if (!copied) 1652 copied = used; 1653 break; 1654 } 1655 if (WARN_ON_ONCE(used > len)) 1656 used = len; 1657 seq += used; 1658 copied += used; 1659 offset += used; 1660 1661 /* If recv_actor drops the lock (e.g. TCP splice 1662 * receive) the skb pointer might be invalid when 1663 * getting here: tcp_collapse might have deleted it 1664 * while aggregating skbs from the socket queue. 1665 */ 1666 skb = tcp_recv_skb(sk, seq - 1, &offset); 1667 if (!skb) 1668 break; 1669 /* TCP coalescing might have appended data to the skb. 1670 * Try to splice more frags 1671 */ 1672 if (offset + 1 != skb->len) 1673 continue; 1674 } 1675 if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) { 1676 tcp_eat_recv_skb(sk, skb); 1677 ++seq; 1678 break; 1679 } 1680 tcp_eat_recv_skb(sk, skb); 1681 if (!desc->count) 1682 break; 1683 WRITE_ONCE(*copied_seq, seq); 1684 } 1685 WRITE_ONCE(*copied_seq, seq); 1686 1687 if (noack) 1688 goto out; 1689 1690 tcp_rcv_space_adjust(sk); 1691 1692 /* Clean up data we have read: This will do ACK frames. */ 1693 if (copied > 0) { 1694 tcp_recv_skb(sk, seq, &offset); 1695 tcp_cleanup_rbuf(sk, copied); 1696 } 1697 out: 1698 return copied; 1699 } 1700 1701 int tcp_read_sock(struct sock *sk, read_descriptor_t *desc, 1702 sk_read_actor_t recv_actor) 1703 { 1704 return __tcp_read_sock(sk, desc, recv_actor, false, 1705 &tcp_sk(sk)->copied_seq); 1706 } 1707 EXPORT_SYMBOL(tcp_read_sock); 1708 1709 int tcp_read_sock_noack(struct sock *sk, read_descriptor_t *desc, 1710 sk_read_actor_t recv_actor, bool noack, 1711 u32 *copied_seq) 1712 { 1713 return __tcp_read_sock(sk, desc, recv_actor, noack, copied_seq); 1714 } 1715 1716 int tcp_read_skb(struct sock *sk, skb_read_actor_t recv_actor) 1717 { 1718 struct sk_buff *skb; 1719 int copied = 0; 1720 1721 if (sk->sk_state == TCP_LISTEN) 1722 return -ENOTCONN; 1723 1724 while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) { 1725 u8 tcp_flags; 1726 int used; 1727 1728 __skb_unlink(skb, &sk->sk_receive_queue); 1729 WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk)); 1730 tcp_flags = TCP_SKB_CB(skb)->tcp_flags; 1731 used = recv_actor(sk, skb); 1732 if (used < 0) { 1733 if (!copied) 1734 copied = used; 1735 break; 1736 } 1737 copied += used; 1738 1739 if (tcp_flags & TCPHDR_FIN) 1740 break; 1741 } 1742 return copied; 1743 } 1744 EXPORT_IPV6_MOD(tcp_read_skb); 1745 1746 void tcp_read_done(struct sock *sk, size_t len) 1747 { 1748 struct tcp_sock *tp = tcp_sk(sk); 1749 u32 seq = tp->copied_seq; 1750 struct sk_buff *skb; 1751 size_t left; 1752 u32 offset; 1753 1754 if (sk->sk_state == TCP_LISTEN) 1755 return; 1756 1757 left = len; 1758 while (left && (skb = tcp_recv_skb(sk, seq, &offset)) != NULL) { 1759 int used; 1760 1761 used = min_t(size_t, skb->len - offset, left); 1762 seq += used; 1763 left -= used; 1764 1765 if (skb->len > offset + used) 1766 break; 1767 1768 if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) { 1769 tcp_eat_recv_skb(sk, skb); 1770 ++seq; 1771 break; 1772 } 1773 tcp_eat_recv_skb(sk, skb); 1774 } 1775 WRITE_ONCE(tp->copied_seq, seq); 1776 1777 tcp_rcv_space_adjust(sk); 1778 1779 /* Clean up data we have read: This will do ACK frames. */ 1780 if (left != len) 1781 tcp_cleanup_rbuf(sk, len - left); 1782 } 1783 EXPORT_SYMBOL(tcp_read_done); 1784 1785 int tcp_peek_len(struct socket *sock) 1786 { 1787 return tcp_inq(sock->sk); 1788 } 1789 EXPORT_IPV6_MOD(tcp_peek_len); 1790 1791 /* Make sure sk_rcvbuf is big enough to satisfy SO_RCVLOWAT hint */ 1792 int tcp_set_rcvlowat(struct sock *sk, int val) 1793 { 1794 struct tcp_sock *tp = tcp_sk(sk); 1795 int space, cap; 1796 1797 if (sk->sk_userlocks & SOCK_RCVBUF_LOCK) 1798 cap = sk->sk_rcvbuf >> 1; 1799 else 1800 cap = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2]) >> 1; 1801 val = min(val, cap); 1802 WRITE_ONCE(sk->sk_rcvlowat, val ? : 1); 1803 1804 /* Check if we need to signal EPOLLIN right now */ 1805 tcp_data_ready(sk); 1806 1807 if (sk->sk_userlocks & SOCK_RCVBUF_LOCK) 1808 return 0; 1809 1810 space = tcp_space_from_win(sk, val); 1811 if (space > sk->sk_rcvbuf) { 1812 WRITE_ONCE(sk->sk_rcvbuf, space); 1813 1814 if (tp->window_clamp && tp->window_clamp < val) 1815 WRITE_ONCE(tp->window_clamp, val); 1816 } 1817 return 0; 1818 } 1819 EXPORT_IPV6_MOD(tcp_set_rcvlowat); 1820 1821 void tcp_update_recv_tstamps(struct sk_buff *skb, 1822 struct scm_timestamping_internal *tss) 1823 { 1824 if (skb->tstamp) 1825 tss->ts[0] = ktime_to_timespec64(skb->tstamp); 1826 else 1827 tss->ts[0] = (struct timespec64) {0}; 1828 1829 if (skb_hwtstamps(skb)->hwtstamp) 1830 tss->ts[2] = ktime_to_timespec64(skb_hwtstamps(skb)->hwtstamp); 1831 else 1832 tss->ts[2] = (struct timespec64) {0}; 1833 } 1834 1835 #ifdef CONFIG_MMU 1836 static const struct vm_operations_struct tcp_vm_ops = { 1837 }; 1838 1839 int tcp_mmap(struct file *file, struct socket *sock, 1840 struct vm_area_struct *vma) 1841 { 1842 if (vma->vm_flags & (VM_WRITE | VM_EXEC)) 1843 return -EPERM; 1844 vm_flags_clear(vma, VM_MAYWRITE | VM_MAYEXEC); 1845 1846 /* Instruct vm_insert_page() to not mmap_read_lock(mm) */ 1847 vm_flags_set(vma, VM_MIXEDMAP); 1848 1849 vma->vm_ops = &tcp_vm_ops; 1850 return 0; 1851 } 1852 EXPORT_IPV6_MOD(tcp_mmap); 1853 1854 static skb_frag_t *skb_advance_to_frag(struct sk_buff *skb, u32 offset_skb, 1855 u32 *offset_frag) 1856 { 1857 skb_frag_t *frag; 1858 1859 if (unlikely(offset_skb >= skb->len)) 1860 return NULL; 1861 1862 offset_skb -= skb_headlen(skb); 1863 if ((int)offset_skb < 0 || skb_has_frag_list(skb)) 1864 return NULL; 1865 1866 frag = skb_shinfo(skb)->frags; 1867 while (offset_skb) { 1868 if (skb_frag_size(frag) > offset_skb) { 1869 *offset_frag = offset_skb; 1870 return frag; 1871 } 1872 offset_skb -= skb_frag_size(frag); 1873 ++frag; 1874 } 1875 *offset_frag = 0; 1876 return frag; 1877 } 1878 1879 static bool can_map_frag(const skb_frag_t *frag) 1880 { 1881 struct page *page; 1882 1883 if (skb_frag_size(frag) != PAGE_SIZE || skb_frag_off(frag)) 1884 return false; 1885 1886 page = skb_frag_page(frag); 1887 1888 if (PageCompound(page) || page->mapping) 1889 return false; 1890 1891 return true; 1892 } 1893 1894 static int find_next_mappable_frag(const skb_frag_t *frag, 1895 int remaining_in_skb) 1896 { 1897 int offset = 0; 1898 1899 if (likely(can_map_frag(frag))) 1900 return 0; 1901 1902 while (offset < remaining_in_skb && !can_map_frag(frag)) { 1903 offset += skb_frag_size(frag); 1904 ++frag; 1905 } 1906 return offset; 1907 } 1908 1909 static void tcp_zerocopy_set_hint_for_skb(struct sock *sk, 1910 struct tcp_zerocopy_receive *zc, 1911 struct sk_buff *skb, u32 offset) 1912 { 1913 u32 frag_offset, partial_frag_remainder = 0; 1914 int mappable_offset; 1915 skb_frag_t *frag; 1916 1917 /* worst case: skip to next skb. try to improve on this case below */ 1918 zc->recv_skip_hint = skb->len - offset; 1919 1920 /* Find the frag containing this offset (and how far into that frag) */ 1921 frag = skb_advance_to_frag(skb, offset, &frag_offset); 1922 if (!frag) 1923 return; 1924 1925 if (frag_offset) { 1926 struct skb_shared_info *info = skb_shinfo(skb); 1927 1928 /* We read part of the last frag, must recvmsg() rest of skb. */ 1929 if (frag == &info->frags[info->nr_frags - 1]) 1930 return; 1931 1932 /* Else, we must at least read the remainder in this frag. */ 1933 partial_frag_remainder = skb_frag_size(frag) - frag_offset; 1934 zc->recv_skip_hint -= partial_frag_remainder; 1935 ++frag; 1936 } 1937 1938 /* partial_frag_remainder: If part way through a frag, must read rest. 1939 * mappable_offset: Bytes till next mappable frag, *not* counting bytes 1940 * in partial_frag_remainder. 1941 */ 1942 mappable_offset = find_next_mappable_frag(frag, zc->recv_skip_hint); 1943 zc->recv_skip_hint = mappable_offset + partial_frag_remainder; 1944 } 1945 1946 static int tcp_recvmsg_locked(struct sock *sk, struct msghdr *msg, size_t len, 1947 int flags, struct scm_timestamping_internal *tss, 1948 int *cmsg_flags); 1949 static int receive_fallback_to_copy(struct sock *sk, 1950 struct tcp_zerocopy_receive *zc, int inq, 1951 struct scm_timestamping_internal *tss) 1952 { 1953 unsigned long copy_address = (unsigned long)zc->copybuf_address; 1954 struct msghdr msg = {}; 1955 int err; 1956 1957 zc->length = 0; 1958 zc->recv_skip_hint = 0; 1959 1960 if (copy_address != zc->copybuf_address) 1961 return -EINVAL; 1962 1963 err = import_ubuf(ITER_DEST, (void __user *)copy_address, inq, 1964 &msg.msg_iter); 1965 if (err) 1966 return err; 1967 1968 err = tcp_recvmsg_locked(sk, &msg, inq, MSG_DONTWAIT, 1969 tss, &zc->msg_flags); 1970 if (err < 0) 1971 return err; 1972 1973 zc->copybuf_len = err; 1974 if (likely(zc->copybuf_len)) { 1975 struct sk_buff *skb; 1976 u32 offset; 1977 1978 skb = tcp_recv_skb(sk, tcp_sk(sk)->copied_seq, &offset); 1979 if (skb) 1980 tcp_zerocopy_set_hint_for_skb(sk, zc, skb, offset); 1981 } 1982 return 0; 1983 } 1984 1985 static int tcp_copy_straggler_data(struct tcp_zerocopy_receive *zc, 1986 struct sk_buff *skb, u32 copylen, 1987 u32 *offset, u32 *seq) 1988 { 1989 unsigned long copy_address = (unsigned long)zc->copybuf_address; 1990 struct msghdr msg = {}; 1991 int err; 1992 1993 if (copy_address != zc->copybuf_address) 1994 return -EINVAL; 1995 1996 err = import_ubuf(ITER_DEST, (void __user *)copy_address, copylen, 1997 &msg.msg_iter); 1998 if (err) 1999 return err; 2000 err = skb_copy_datagram_msg(skb, *offset, &msg, copylen); 2001 if (err) 2002 return err; 2003 zc->recv_skip_hint -= copylen; 2004 *offset += copylen; 2005 *seq += copylen; 2006 return (__s32)copylen; 2007 } 2008 2009 static int tcp_zc_handle_leftover(struct tcp_zerocopy_receive *zc, 2010 struct sock *sk, 2011 struct sk_buff *skb, 2012 u32 *seq, 2013 s32 copybuf_len, 2014 struct scm_timestamping_internal *tss) 2015 { 2016 u32 offset, copylen = min_t(u32, copybuf_len, zc->recv_skip_hint); 2017 2018 if (!copylen) 2019 return 0; 2020 /* skb is null if inq < PAGE_SIZE. */ 2021 if (skb) { 2022 offset = *seq - TCP_SKB_CB(skb)->seq; 2023 } else { 2024 skb = tcp_recv_skb(sk, *seq, &offset); 2025 if (TCP_SKB_CB(skb)->has_rxtstamp) { 2026 tcp_update_recv_tstamps(skb, tss); 2027 zc->msg_flags |= TCP_CMSG_TS; 2028 } 2029 } 2030 2031 zc->copybuf_len = tcp_copy_straggler_data(zc, skb, copylen, &offset, 2032 seq); 2033 return zc->copybuf_len < 0 ? 0 : copylen; 2034 } 2035 2036 static int tcp_zerocopy_vm_insert_batch_error(struct vm_area_struct *vma, 2037 struct page **pending_pages, 2038 unsigned long pages_remaining, 2039 unsigned long *address, 2040 u32 *length, 2041 u32 *seq, 2042 struct tcp_zerocopy_receive *zc, 2043 u32 total_bytes_to_map, 2044 int err) 2045 { 2046 /* At least one page did not map. Try zapping if we skipped earlier. */ 2047 if (err == -EBUSY && 2048 zc->flags & TCP_RECEIVE_ZEROCOPY_FLAG_TLB_CLEAN_HINT) { 2049 u32 maybe_zap_len; 2050 2051 maybe_zap_len = total_bytes_to_map - /* All bytes to map */ 2052 *length + /* Mapped or pending */ 2053 (pages_remaining * PAGE_SIZE); /* Failed map. */ 2054 zap_page_range_single(vma, *address, maybe_zap_len, NULL); 2055 err = 0; 2056 } 2057 2058 if (!err) { 2059 unsigned long leftover_pages = pages_remaining; 2060 int bytes_mapped; 2061 2062 /* We called zap_page_range_single, try to reinsert. */ 2063 err = vm_insert_pages(vma, *address, 2064 pending_pages, 2065 &pages_remaining); 2066 bytes_mapped = PAGE_SIZE * (leftover_pages - pages_remaining); 2067 *seq += bytes_mapped; 2068 *address += bytes_mapped; 2069 } 2070 if (err) { 2071 /* Either we were unable to zap, OR we zapped, retried an 2072 * insert, and still had an issue. Either ways, pages_remaining 2073 * is the number of pages we were unable to map, and we unroll 2074 * some state we speculatively touched before. 2075 */ 2076 const int bytes_not_mapped = PAGE_SIZE * pages_remaining; 2077 2078 *length -= bytes_not_mapped; 2079 zc->recv_skip_hint += bytes_not_mapped; 2080 } 2081 return err; 2082 } 2083 2084 static int tcp_zerocopy_vm_insert_batch(struct vm_area_struct *vma, 2085 struct page **pages, 2086 unsigned int pages_to_map, 2087 unsigned long *address, 2088 u32 *length, 2089 u32 *seq, 2090 struct tcp_zerocopy_receive *zc, 2091 u32 total_bytes_to_map) 2092 { 2093 unsigned long pages_remaining = pages_to_map; 2094 unsigned int pages_mapped; 2095 unsigned int bytes_mapped; 2096 int err; 2097 2098 err = vm_insert_pages(vma, *address, pages, &pages_remaining); 2099 pages_mapped = pages_to_map - (unsigned int)pages_remaining; 2100 bytes_mapped = PAGE_SIZE * pages_mapped; 2101 /* Even if vm_insert_pages fails, it may have partially succeeded in 2102 * mapping (some but not all of the pages). 2103 */ 2104 *seq += bytes_mapped; 2105 *address += bytes_mapped; 2106 2107 if (likely(!err)) 2108 return 0; 2109 2110 /* Error: maybe zap and retry + rollback state for failed inserts. */ 2111 return tcp_zerocopy_vm_insert_batch_error(vma, pages + pages_mapped, 2112 pages_remaining, address, length, seq, zc, total_bytes_to_map, 2113 err); 2114 } 2115 2116 #define TCP_VALID_ZC_MSG_FLAGS (TCP_CMSG_TS) 2117 static void tcp_zc_finalize_rx_tstamp(struct sock *sk, 2118 struct tcp_zerocopy_receive *zc, 2119 struct scm_timestamping_internal *tss) 2120 { 2121 unsigned long msg_control_addr; 2122 struct msghdr cmsg_dummy; 2123 2124 msg_control_addr = (unsigned long)zc->msg_control; 2125 cmsg_dummy.msg_control_user = (void __user *)msg_control_addr; 2126 cmsg_dummy.msg_controllen = 2127 (__kernel_size_t)zc->msg_controllen; 2128 cmsg_dummy.msg_flags = in_compat_syscall() 2129 ? MSG_CMSG_COMPAT : 0; 2130 cmsg_dummy.msg_control_is_user = true; 2131 zc->msg_flags = 0; 2132 if (zc->msg_control == msg_control_addr && 2133 zc->msg_controllen == cmsg_dummy.msg_controllen) { 2134 tcp_recv_timestamp(&cmsg_dummy, sk, tss); 2135 zc->msg_control = (__u64) 2136 ((uintptr_t)cmsg_dummy.msg_control_user); 2137 zc->msg_controllen = 2138 (__u64)cmsg_dummy.msg_controllen; 2139 zc->msg_flags = (__u32)cmsg_dummy.msg_flags; 2140 } 2141 } 2142 2143 static struct vm_area_struct *find_tcp_vma(struct mm_struct *mm, 2144 unsigned long address, 2145 bool *mmap_locked) 2146 { 2147 struct vm_area_struct *vma = lock_vma_under_rcu(mm, address); 2148 2149 if (vma) { 2150 if (vma->vm_ops != &tcp_vm_ops) { 2151 vma_end_read(vma); 2152 return NULL; 2153 } 2154 *mmap_locked = false; 2155 return vma; 2156 } 2157 2158 mmap_read_lock(mm); 2159 vma = vma_lookup(mm, address); 2160 if (!vma || vma->vm_ops != &tcp_vm_ops) { 2161 mmap_read_unlock(mm); 2162 return NULL; 2163 } 2164 *mmap_locked = true; 2165 return vma; 2166 } 2167 2168 #define TCP_ZEROCOPY_PAGE_BATCH_SIZE 32 2169 static int tcp_zerocopy_receive(struct sock *sk, 2170 struct tcp_zerocopy_receive *zc, 2171 struct scm_timestamping_internal *tss) 2172 { 2173 u32 length = 0, offset, vma_len, avail_len, copylen = 0; 2174 unsigned long address = (unsigned long)zc->address; 2175 struct page *pages[TCP_ZEROCOPY_PAGE_BATCH_SIZE]; 2176 s32 copybuf_len = zc->copybuf_len; 2177 struct tcp_sock *tp = tcp_sk(sk); 2178 const skb_frag_t *frags = NULL; 2179 unsigned int pages_to_map = 0; 2180 struct vm_area_struct *vma; 2181 struct sk_buff *skb = NULL; 2182 u32 seq = tp->copied_seq; 2183 u32 total_bytes_to_map; 2184 int inq = tcp_inq(sk); 2185 bool mmap_locked; 2186 int ret; 2187 2188 zc->copybuf_len = 0; 2189 zc->msg_flags = 0; 2190 2191 if (address & (PAGE_SIZE - 1) || address != zc->address) 2192 return -EINVAL; 2193 2194 if (sk->sk_state == TCP_LISTEN) 2195 return -ENOTCONN; 2196 2197 sock_rps_record_flow(sk); 2198 2199 if (inq && inq <= copybuf_len) 2200 return receive_fallback_to_copy(sk, zc, inq, tss); 2201 2202 if (inq < PAGE_SIZE) { 2203 zc->length = 0; 2204 zc->recv_skip_hint = inq; 2205 if (!inq && sock_flag(sk, SOCK_DONE)) 2206 return -EIO; 2207 return 0; 2208 } 2209 2210 vma = find_tcp_vma(current->mm, address, &mmap_locked); 2211 if (!vma) 2212 return -EINVAL; 2213 2214 vma_len = min_t(unsigned long, zc->length, vma->vm_end - address); 2215 avail_len = min_t(u32, vma_len, inq); 2216 total_bytes_to_map = avail_len & ~(PAGE_SIZE - 1); 2217 if (total_bytes_to_map) { 2218 if (!(zc->flags & TCP_RECEIVE_ZEROCOPY_FLAG_TLB_CLEAN_HINT)) 2219 zap_page_range_single(vma, address, total_bytes_to_map, 2220 NULL); 2221 zc->length = total_bytes_to_map; 2222 zc->recv_skip_hint = 0; 2223 } else { 2224 zc->length = avail_len; 2225 zc->recv_skip_hint = avail_len; 2226 } 2227 ret = 0; 2228 while (length + PAGE_SIZE <= zc->length) { 2229 int mappable_offset; 2230 struct page *page; 2231 2232 if (zc->recv_skip_hint < PAGE_SIZE) { 2233 u32 offset_frag; 2234 2235 if (skb) { 2236 if (zc->recv_skip_hint > 0) 2237 break; 2238 skb = skb->next; 2239 offset = seq - TCP_SKB_CB(skb)->seq; 2240 } else { 2241 skb = tcp_recv_skb(sk, seq, &offset); 2242 } 2243 2244 if (!skb_frags_readable(skb)) 2245 break; 2246 2247 if (TCP_SKB_CB(skb)->has_rxtstamp) { 2248 tcp_update_recv_tstamps(skb, tss); 2249 zc->msg_flags |= TCP_CMSG_TS; 2250 } 2251 zc->recv_skip_hint = skb->len - offset; 2252 frags = skb_advance_to_frag(skb, offset, &offset_frag); 2253 if (!frags || offset_frag) 2254 break; 2255 } 2256 2257 mappable_offset = find_next_mappable_frag(frags, 2258 zc->recv_skip_hint); 2259 if (mappable_offset) { 2260 zc->recv_skip_hint = mappable_offset; 2261 break; 2262 } 2263 page = skb_frag_page(frags); 2264 if (WARN_ON_ONCE(!page)) 2265 break; 2266 2267 prefetchw(page); 2268 pages[pages_to_map++] = page; 2269 length += PAGE_SIZE; 2270 zc->recv_skip_hint -= PAGE_SIZE; 2271 frags++; 2272 if (pages_to_map == TCP_ZEROCOPY_PAGE_BATCH_SIZE || 2273 zc->recv_skip_hint < PAGE_SIZE) { 2274 /* Either full batch, or we're about to go to next skb 2275 * (and we cannot unroll failed ops across skbs). 2276 */ 2277 ret = tcp_zerocopy_vm_insert_batch(vma, pages, 2278 pages_to_map, 2279 &address, &length, 2280 &seq, zc, 2281 total_bytes_to_map); 2282 if (ret) 2283 goto out; 2284 pages_to_map = 0; 2285 } 2286 } 2287 if (pages_to_map) { 2288 ret = tcp_zerocopy_vm_insert_batch(vma, pages, pages_to_map, 2289 &address, &length, &seq, 2290 zc, total_bytes_to_map); 2291 } 2292 out: 2293 if (mmap_locked) 2294 mmap_read_unlock(current->mm); 2295 else 2296 vma_end_read(vma); 2297 /* Try to copy straggler data. */ 2298 if (!ret) 2299 copylen = tcp_zc_handle_leftover(zc, sk, skb, &seq, copybuf_len, tss); 2300 2301 if (length + copylen) { 2302 WRITE_ONCE(tp->copied_seq, seq); 2303 tcp_rcv_space_adjust(sk); 2304 2305 /* Clean up data we have read: This will do ACK frames. */ 2306 tcp_recv_skb(sk, seq, &offset); 2307 tcp_cleanup_rbuf(sk, length + copylen); 2308 ret = 0; 2309 if (length == zc->length) 2310 zc->recv_skip_hint = 0; 2311 } else { 2312 if (!zc->recv_skip_hint && sock_flag(sk, SOCK_DONE)) 2313 ret = -EIO; 2314 } 2315 zc->length = length; 2316 return ret; 2317 } 2318 #endif 2319 2320 /* Similar to __sock_recv_timestamp, but does not require an skb */ 2321 void tcp_recv_timestamp(struct msghdr *msg, const struct sock *sk, 2322 struct scm_timestamping_internal *tss) 2323 { 2324 int new_tstamp = sock_flag(sk, SOCK_TSTAMP_NEW); 2325 u32 tsflags = READ_ONCE(sk->sk_tsflags); 2326 bool has_timestamping = false; 2327 2328 if (tss->ts[0].tv_sec || tss->ts[0].tv_nsec) { 2329 if (sock_flag(sk, SOCK_RCVTSTAMP)) { 2330 if (sock_flag(sk, SOCK_RCVTSTAMPNS)) { 2331 if (new_tstamp) { 2332 struct __kernel_timespec kts = { 2333 .tv_sec = tss->ts[0].tv_sec, 2334 .tv_nsec = tss->ts[0].tv_nsec, 2335 }; 2336 put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMPNS_NEW, 2337 sizeof(kts), &kts); 2338 } else { 2339 struct __kernel_old_timespec ts_old = { 2340 .tv_sec = tss->ts[0].tv_sec, 2341 .tv_nsec = tss->ts[0].tv_nsec, 2342 }; 2343 put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMPNS_OLD, 2344 sizeof(ts_old), &ts_old); 2345 } 2346 } else { 2347 if (new_tstamp) { 2348 struct __kernel_sock_timeval stv = { 2349 .tv_sec = tss->ts[0].tv_sec, 2350 .tv_usec = tss->ts[0].tv_nsec / 1000, 2351 }; 2352 put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_NEW, 2353 sizeof(stv), &stv); 2354 } else { 2355 struct __kernel_old_timeval tv = { 2356 .tv_sec = tss->ts[0].tv_sec, 2357 .tv_usec = tss->ts[0].tv_nsec / 1000, 2358 }; 2359 put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_OLD, 2360 sizeof(tv), &tv); 2361 } 2362 } 2363 } 2364 2365 if (tsflags & SOF_TIMESTAMPING_SOFTWARE && 2366 (tsflags & SOF_TIMESTAMPING_RX_SOFTWARE || 2367 !(tsflags & SOF_TIMESTAMPING_OPT_RX_FILTER))) 2368 has_timestamping = true; 2369 else 2370 tss->ts[0] = (struct timespec64) {0}; 2371 } 2372 2373 if (tss->ts[2].tv_sec || tss->ts[2].tv_nsec) { 2374 if (tsflags & SOF_TIMESTAMPING_RAW_HARDWARE && 2375 (tsflags & SOF_TIMESTAMPING_RX_HARDWARE || 2376 !(tsflags & SOF_TIMESTAMPING_OPT_RX_FILTER))) 2377 has_timestamping = true; 2378 else 2379 tss->ts[2] = (struct timespec64) {0}; 2380 } 2381 2382 if (has_timestamping) { 2383 tss->ts[1] = (struct timespec64) {0}; 2384 if (sock_flag(sk, SOCK_TSTAMP_NEW)) 2385 put_cmsg_scm_timestamping64(msg, tss); 2386 else 2387 put_cmsg_scm_timestamping(msg, tss); 2388 } 2389 } 2390 2391 static int tcp_inq_hint(struct sock *sk) 2392 { 2393 const struct tcp_sock *tp = tcp_sk(sk); 2394 u32 copied_seq = READ_ONCE(tp->copied_seq); 2395 u32 rcv_nxt = READ_ONCE(tp->rcv_nxt); 2396 int inq; 2397 2398 inq = rcv_nxt - copied_seq; 2399 if (unlikely(inq < 0 || copied_seq != READ_ONCE(tp->copied_seq))) { 2400 lock_sock(sk); 2401 inq = tp->rcv_nxt - tp->copied_seq; 2402 release_sock(sk); 2403 } 2404 /* After receiving a FIN, tell the user-space to continue reading 2405 * by returning a non-zero inq. 2406 */ 2407 if (inq == 0 && sock_flag(sk, SOCK_DONE)) 2408 inq = 1; 2409 return inq; 2410 } 2411 2412 /* batch __xa_alloc() calls and reduce xa_lock()/xa_unlock() overhead. */ 2413 struct tcp_xa_pool { 2414 u8 max; /* max <= MAX_SKB_FRAGS */ 2415 u8 idx; /* idx <= max */ 2416 __u32 tokens[MAX_SKB_FRAGS]; 2417 netmem_ref netmems[MAX_SKB_FRAGS]; 2418 }; 2419 2420 static void tcp_xa_pool_commit_locked(struct sock *sk, struct tcp_xa_pool *p) 2421 { 2422 int i; 2423 2424 /* Commit part that has been copied to user space. */ 2425 for (i = 0; i < p->idx; i++) 2426 __xa_cmpxchg(&sk->sk_user_frags, p->tokens[i], XA_ZERO_ENTRY, 2427 (__force void *)p->netmems[i], GFP_KERNEL); 2428 /* Rollback what has been pre-allocated and is no longer needed. */ 2429 for (; i < p->max; i++) 2430 __xa_erase(&sk->sk_user_frags, p->tokens[i]); 2431 2432 p->max = 0; 2433 p->idx = 0; 2434 } 2435 2436 static void tcp_xa_pool_commit(struct sock *sk, struct tcp_xa_pool *p) 2437 { 2438 if (!p->max) 2439 return; 2440 2441 xa_lock_bh(&sk->sk_user_frags); 2442 2443 tcp_xa_pool_commit_locked(sk, p); 2444 2445 xa_unlock_bh(&sk->sk_user_frags); 2446 } 2447 2448 static int tcp_xa_pool_refill(struct sock *sk, struct tcp_xa_pool *p, 2449 unsigned int max_frags) 2450 { 2451 int err, k; 2452 2453 if (p->idx < p->max) 2454 return 0; 2455 2456 xa_lock_bh(&sk->sk_user_frags); 2457 2458 tcp_xa_pool_commit_locked(sk, p); 2459 2460 for (k = 0; k < max_frags; k++) { 2461 err = __xa_alloc(&sk->sk_user_frags, &p->tokens[k], 2462 XA_ZERO_ENTRY, xa_limit_31b, GFP_KERNEL); 2463 if (err) 2464 break; 2465 } 2466 2467 xa_unlock_bh(&sk->sk_user_frags); 2468 2469 p->max = k; 2470 p->idx = 0; 2471 return k ? 0 : err; 2472 } 2473 2474 /* On error, returns the -errno. On success, returns number of bytes sent to the 2475 * user. May not consume all of @remaining_len. 2476 */ 2477 static int tcp_recvmsg_dmabuf(struct sock *sk, const struct sk_buff *skb, 2478 unsigned int offset, struct msghdr *msg, 2479 int remaining_len) 2480 { 2481 struct dmabuf_cmsg dmabuf_cmsg = { 0 }; 2482 struct tcp_xa_pool tcp_xa_pool; 2483 unsigned int start; 2484 int i, copy, n; 2485 int sent = 0; 2486 int err = 0; 2487 2488 tcp_xa_pool.max = 0; 2489 tcp_xa_pool.idx = 0; 2490 do { 2491 start = skb_headlen(skb); 2492 2493 if (skb_frags_readable(skb)) { 2494 err = -ENODEV; 2495 goto out; 2496 } 2497 2498 /* Copy header. */ 2499 copy = start - offset; 2500 if (copy > 0) { 2501 copy = min(copy, remaining_len); 2502 2503 n = copy_to_iter(skb->data + offset, copy, 2504 &msg->msg_iter); 2505 if (n != copy) { 2506 err = -EFAULT; 2507 goto out; 2508 } 2509 2510 offset += copy; 2511 remaining_len -= copy; 2512 2513 /* First a dmabuf_cmsg for # bytes copied to user 2514 * buffer. 2515 */ 2516 memset(&dmabuf_cmsg, 0, sizeof(dmabuf_cmsg)); 2517 dmabuf_cmsg.frag_size = copy; 2518 err = put_cmsg_notrunc(msg, SOL_SOCKET, 2519 SO_DEVMEM_LINEAR, 2520 sizeof(dmabuf_cmsg), 2521 &dmabuf_cmsg); 2522 if (err) 2523 goto out; 2524 2525 sent += copy; 2526 2527 if (remaining_len == 0) 2528 goto out; 2529 } 2530 2531 /* after that, send information of dmabuf pages through a 2532 * sequence of cmsg 2533 */ 2534 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { 2535 skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; 2536 struct net_iov *niov; 2537 u64 frag_offset; 2538 int end; 2539 2540 /* !skb_frags_readable() should indicate that ALL the 2541 * frags in this skb are dmabuf net_iovs. We're checking 2542 * for that flag above, but also check individual frags 2543 * here. If the tcp stack is not setting 2544 * skb_frags_readable() correctly, we still don't want 2545 * to crash here. 2546 */ 2547 if (!skb_frag_net_iov(frag)) { 2548 net_err_ratelimited("Found non-dmabuf skb with net_iov"); 2549 err = -ENODEV; 2550 goto out; 2551 } 2552 2553 niov = skb_frag_net_iov(frag); 2554 if (!net_is_devmem_iov(niov)) { 2555 err = -ENODEV; 2556 goto out; 2557 } 2558 2559 end = start + skb_frag_size(frag); 2560 copy = end - offset; 2561 2562 if (copy > 0) { 2563 copy = min(copy, remaining_len); 2564 2565 frag_offset = net_iov_virtual_addr(niov) + 2566 skb_frag_off(frag) + offset - 2567 start; 2568 dmabuf_cmsg.frag_offset = frag_offset; 2569 dmabuf_cmsg.frag_size = copy; 2570 err = tcp_xa_pool_refill(sk, &tcp_xa_pool, 2571 skb_shinfo(skb)->nr_frags - i); 2572 if (err) 2573 goto out; 2574 2575 /* Will perform the exchange later */ 2576 dmabuf_cmsg.frag_token = tcp_xa_pool.tokens[tcp_xa_pool.idx]; 2577 dmabuf_cmsg.dmabuf_id = net_devmem_iov_binding_id(niov); 2578 2579 offset += copy; 2580 remaining_len -= copy; 2581 2582 err = put_cmsg_notrunc(msg, SOL_SOCKET, 2583 SO_DEVMEM_DMABUF, 2584 sizeof(dmabuf_cmsg), 2585 &dmabuf_cmsg); 2586 if (err) 2587 goto out; 2588 2589 atomic_long_inc(&niov->pp_ref_count); 2590 tcp_xa_pool.netmems[tcp_xa_pool.idx++] = skb_frag_netmem(frag); 2591 2592 sent += copy; 2593 2594 if (remaining_len == 0) 2595 goto out; 2596 } 2597 start = end; 2598 } 2599 2600 tcp_xa_pool_commit(sk, &tcp_xa_pool); 2601 if (!remaining_len) 2602 goto out; 2603 2604 /* if remaining_len is not satisfied yet, we need to go to the 2605 * next frag in the frag_list to satisfy remaining_len. 2606 */ 2607 skb = skb_shinfo(skb)->frag_list ?: skb->next; 2608 2609 offset = offset - start; 2610 } while (skb); 2611 2612 if (remaining_len) { 2613 err = -EFAULT; 2614 goto out; 2615 } 2616 2617 out: 2618 tcp_xa_pool_commit(sk, &tcp_xa_pool); 2619 if (!sent) 2620 sent = err; 2621 2622 return sent; 2623 } 2624 2625 /* 2626 * This routine copies from a sock struct into the user buffer. 2627 * 2628 * Technical note: in 2.3 we work on _locked_ socket, so that 2629 * tricks with *seq access order and skb->users are not required. 2630 * Probably, code can be easily improved even more. 2631 */ 2632 2633 static int tcp_recvmsg_locked(struct sock *sk, struct msghdr *msg, size_t len, 2634 int flags, struct scm_timestamping_internal *tss, 2635 int *cmsg_flags) 2636 { 2637 struct tcp_sock *tp = tcp_sk(sk); 2638 int last_copied_dmabuf = -1; /* uninitialized */ 2639 int copied = 0; 2640 u32 peek_seq; 2641 u32 *seq; 2642 unsigned long used; 2643 int err; 2644 int target; /* Read at least this many bytes */ 2645 long timeo; 2646 struct sk_buff *skb, *last; 2647 u32 peek_offset = 0; 2648 u32 urg_hole = 0; 2649 2650 err = -ENOTCONN; 2651 if (sk->sk_state == TCP_LISTEN) 2652 goto out; 2653 2654 if (tp->recvmsg_inq) { 2655 *cmsg_flags = TCP_CMSG_INQ; 2656 msg->msg_get_inq = 1; 2657 } 2658 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); 2659 2660 /* Urgent data needs to be handled specially. */ 2661 if (flags & MSG_OOB) 2662 goto recv_urg; 2663 2664 if (unlikely(tp->repair)) { 2665 err = -EPERM; 2666 if (!(flags & MSG_PEEK)) 2667 goto out; 2668 2669 if (tp->repair_queue == TCP_SEND_QUEUE) 2670 goto recv_sndq; 2671 2672 err = -EINVAL; 2673 if (tp->repair_queue == TCP_NO_QUEUE) 2674 goto out; 2675 2676 /* 'common' recv queue MSG_PEEK-ing */ 2677 } 2678 2679 seq = &tp->copied_seq; 2680 if (flags & MSG_PEEK) { 2681 peek_offset = max(sk_peek_offset(sk, flags), 0); 2682 peek_seq = tp->copied_seq + peek_offset; 2683 seq = &peek_seq; 2684 } 2685 2686 target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); 2687 2688 do { 2689 u32 offset; 2690 2691 /* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */ 2692 if (unlikely(tp->urg_data) && tp->urg_seq == *seq) { 2693 if (copied) 2694 break; 2695 if (signal_pending(current)) { 2696 copied = timeo ? sock_intr_errno(timeo) : -EAGAIN; 2697 break; 2698 } 2699 } 2700 2701 /* Next get a buffer. */ 2702 2703 last = skb_peek_tail(&sk->sk_receive_queue); 2704 skb_queue_walk(&sk->sk_receive_queue, skb) { 2705 last = skb; 2706 /* Now that we have two receive queues this 2707 * shouldn't happen. 2708 */ 2709 if (WARN(before(*seq, TCP_SKB_CB(skb)->seq), 2710 "TCP recvmsg seq # bug: copied %X, seq %X, rcvnxt %X, fl %X\n", 2711 *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, 2712 flags)) 2713 break; 2714 2715 offset = *seq - TCP_SKB_CB(skb)->seq; 2716 if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) { 2717 pr_err_once("%s: found a SYN, please report !\n", __func__); 2718 offset--; 2719 } 2720 if (offset < skb->len) 2721 goto found_ok_skb; 2722 if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) 2723 goto found_fin_ok; 2724 WARN(!(flags & MSG_PEEK), 2725 "TCP recvmsg seq # bug 2: copied %X, seq %X, rcvnxt %X, fl %X\n", 2726 *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags); 2727 } 2728 2729 /* Well, if we have backlog, try to process it now yet. */ 2730 2731 if (copied >= target && !READ_ONCE(sk->sk_backlog.tail)) 2732 break; 2733 2734 if (copied) { 2735 if (!timeo || 2736 sk->sk_err || 2737 sk->sk_state == TCP_CLOSE || 2738 (sk->sk_shutdown & RCV_SHUTDOWN) || 2739 signal_pending(current)) 2740 break; 2741 } else { 2742 if (sock_flag(sk, SOCK_DONE)) 2743 break; 2744 2745 if (sk->sk_err) { 2746 copied = sock_error(sk); 2747 break; 2748 } 2749 2750 if (sk->sk_shutdown & RCV_SHUTDOWN) 2751 break; 2752 2753 if (sk->sk_state == TCP_CLOSE) { 2754 /* This occurs when user tries to read 2755 * from never connected socket. 2756 */ 2757 copied = -ENOTCONN; 2758 break; 2759 } 2760 2761 if (!timeo) { 2762 copied = -EAGAIN; 2763 break; 2764 } 2765 2766 if (signal_pending(current)) { 2767 copied = sock_intr_errno(timeo); 2768 break; 2769 } 2770 } 2771 2772 if (copied >= target) { 2773 /* Do not sleep, just process backlog. */ 2774 __sk_flush_backlog(sk); 2775 } else { 2776 tcp_cleanup_rbuf(sk, copied); 2777 err = sk_wait_data(sk, &timeo, last); 2778 if (err < 0) { 2779 err = copied ? : err; 2780 goto out; 2781 } 2782 } 2783 2784 if ((flags & MSG_PEEK) && 2785 (peek_seq - peek_offset - copied - urg_hole != tp->copied_seq)) { 2786 net_dbg_ratelimited("TCP(%s:%d): Application bug, race in MSG_PEEK\n", 2787 current->comm, 2788 task_pid_nr(current)); 2789 peek_seq = tp->copied_seq + peek_offset; 2790 } 2791 continue; 2792 2793 found_ok_skb: 2794 /* Ok so how much can we use? */ 2795 used = skb->len - offset; 2796 if (len < used) 2797 used = len; 2798 2799 /* Do we have urgent data here? */ 2800 if (unlikely(tp->urg_data)) { 2801 u32 urg_offset = tp->urg_seq - *seq; 2802 if (urg_offset < used) { 2803 if (!urg_offset) { 2804 if (!sock_flag(sk, SOCK_URGINLINE)) { 2805 WRITE_ONCE(*seq, *seq + 1); 2806 urg_hole++; 2807 offset++; 2808 used--; 2809 if (!used) 2810 goto skip_copy; 2811 } 2812 } else 2813 used = urg_offset; 2814 } 2815 } 2816 2817 if (!(flags & MSG_TRUNC)) { 2818 if (last_copied_dmabuf != -1 && 2819 last_copied_dmabuf != !skb_frags_readable(skb)) 2820 break; 2821 2822 if (skb_frags_readable(skb)) { 2823 err = skb_copy_datagram_msg(skb, offset, msg, 2824 used); 2825 if (err) { 2826 /* Exception. Bailout! */ 2827 if (!copied) 2828 copied = -EFAULT; 2829 break; 2830 } 2831 } else { 2832 if (!(flags & MSG_SOCK_DEVMEM)) { 2833 /* dmabuf skbs can only be received 2834 * with the MSG_SOCK_DEVMEM flag. 2835 */ 2836 if (!copied) 2837 copied = -EFAULT; 2838 2839 break; 2840 } 2841 2842 err = tcp_recvmsg_dmabuf(sk, skb, offset, msg, 2843 used); 2844 if (err < 0) { 2845 if (!copied) 2846 copied = err; 2847 2848 break; 2849 } 2850 used = err; 2851 } 2852 } 2853 2854 last_copied_dmabuf = !skb_frags_readable(skb); 2855 2856 WRITE_ONCE(*seq, *seq + used); 2857 copied += used; 2858 len -= used; 2859 if (flags & MSG_PEEK) 2860 sk_peek_offset_fwd(sk, used); 2861 else 2862 sk_peek_offset_bwd(sk, used); 2863 tcp_rcv_space_adjust(sk); 2864 2865 skip_copy: 2866 if (unlikely(tp->urg_data) && after(tp->copied_seq, tp->urg_seq)) { 2867 WRITE_ONCE(tp->urg_data, 0); 2868 tcp_fast_path_check(sk); 2869 } 2870 2871 if (TCP_SKB_CB(skb)->has_rxtstamp) { 2872 tcp_update_recv_tstamps(skb, tss); 2873 *cmsg_flags |= TCP_CMSG_TS; 2874 } 2875 2876 if (used + offset < skb->len) 2877 continue; 2878 2879 if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) 2880 goto found_fin_ok; 2881 if (!(flags & MSG_PEEK)) 2882 tcp_eat_recv_skb(sk, skb); 2883 continue; 2884 2885 found_fin_ok: 2886 /* Process the FIN. */ 2887 WRITE_ONCE(*seq, *seq + 1); 2888 if (!(flags & MSG_PEEK)) 2889 tcp_eat_recv_skb(sk, skb); 2890 break; 2891 } while (len > 0); 2892 2893 /* According to UNIX98, msg_name/msg_namelen are ignored 2894 * on connected socket. I was just happy when found this 8) --ANK 2895 */ 2896 2897 /* Clean up data we have read: This will do ACK frames. */ 2898 tcp_cleanup_rbuf(sk, copied); 2899 return copied; 2900 2901 out: 2902 return err; 2903 2904 recv_urg: 2905 err = tcp_recv_urg(sk, msg, len, flags); 2906 goto out; 2907 2908 recv_sndq: 2909 err = tcp_peek_sndq(sk, msg, len); 2910 goto out; 2911 } 2912 2913 int tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags, 2914 int *addr_len) 2915 { 2916 int cmsg_flags = 0, ret; 2917 struct scm_timestamping_internal tss; 2918 2919 if (unlikely(flags & MSG_ERRQUEUE)) 2920 return inet_recv_error(sk, msg, len, addr_len); 2921 2922 if (sk_can_busy_loop(sk) && 2923 skb_queue_empty_lockless(&sk->sk_receive_queue) && 2924 sk->sk_state == TCP_ESTABLISHED) 2925 sk_busy_loop(sk, flags & MSG_DONTWAIT); 2926 2927 lock_sock(sk); 2928 ret = tcp_recvmsg_locked(sk, msg, len, flags, &tss, &cmsg_flags); 2929 release_sock(sk); 2930 2931 if ((cmsg_flags || msg->msg_get_inq) && ret >= 0) { 2932 if (cmsg_flags & TCP_CMSG_TS) 2933 tcp_recv_timestamp(msg, sk, &tss); 2934 if (msg->msg_get_inq) { 2935 msg->msg_inq = tcp_inq_hint(sk); 2936 if (cmsg_flags & TCP_CMSG_INQ) 2937 put_cmsg(msg, SOL_TCP, TCP_CM_INQ, 2938 sizeof(msg->msg_inq), &msg->msg_inq); 2939 } 2940 } 2941 return ret; 2942 } 2943 EXPORT_IPV6_MOD(tcp_recvmsg); 2944 2945 void tcp_set_state(struct sock *sk, int state) 2946 { 2947 int oldstate = sk->sk_state; 2948 2949 /* We defined a new enum for TCP states that are exported in BPF 2950 * so as not force the internal TCP states to be frozen. The 2951 * following checks will detect if an internal state value ever 2952 * differs from the BPF value. If this ever happens, then we will 2953 * need to remap the internal value to the BPF value before calling 2954 * tcp_call_bpf_2arg. 2955 */ 2956 BUILD_BUG_ON((int)BPF_TCP_ESTABLISHED != (int)TCP_ESTABLISHED); 2957 BUILD_BUG_ON((int)BPF_TCP_SYN_SENT != (int)TCP_SYN_SENT); 2958 BUILD_BUG_ON((int)BPF_TCP_SYN_RECV != (int)TCP_SYN_RECV); 2959 BUILD_BUG_ON((int)BPF_TCP_FIN_WAIT1 != (int)TCP_FIN_WAIT1); 2960 BUILD_BUG_ON((int)BPF_TCP_FIN_WAIT2 != (int)TCP_FIN_WAIT2); 2961 BUILD_BUG_ON((int)BPF_TCP_TIME_WAIT != (int)TCP_TIME_WAIT); 2962 BUILD_BUG_ON((int)BPF_TCP_CLOSE != (int)TCP_CLOSE); 2963 BUILD_BUG_ON((int)BPF_TCP_CLOSE_WAIT != (int)TCP_CLOSE_WAIT); 2964 BUILD_BUG_ON((int)BPF_TCP_LAST_ACK != (int)TCP_LAST_ACK); 2965 BUILD_BUG_ON((int)BPF_TCP_LISTEN != (int)TCP_LISTEN); 2966 BUILD_BUG_ON((int)BPF_TCP_CLOSING != (int)TCP_CLOSING); 2967 BUILD_BUG_ON((int)BPF_TCP_NEW_SYN_RECV != (int)TCP_NEW_SYN_RECV); 2968 BUILD_BUG_ON((int)BPF_TCP_BOUND_INACTIVE != (int)TCP_BOUND_INACTIVE); 2969 BUILD_BUG_ON((int)BPF_TCP_MAX_STATES != (int)TCP_MAX_STATES); 2970 2971 /* bpf uapi header bpf.h defines an anonymous enum with values 2972 * BPF_TCP_* used by bpf programs. Currently gcc built vmlinux 2973 * is able to emit this enum in DWARF due to the above BUILD_BUG_ON. 2974 * But clang built vmlinux does not have this enum in DWARF 2975 * since clang removes the above code before generating IR/debuginfo. 2976 * Let us explicitly emit the type debuginfo to ensure the 2977 * above-mentioned anonymous enum in the vmlinux DWARF and hence BTF 2978 * regardless of which compiler is used. 2979 */ 2980 BTF_TYPE_EMIT_ENUM(BPF_TCP_ESTABLISHED); 2981 2982 if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_STATE_CB_FLAG)) 2983 tcp_call_bpf_2arg(sk, BPF_SOCK_OPS_STATE_CB, oldstate, state); 2984 2985 switch (state) { 2986 case TCP_ESTABLISHED: 2987 if (oldstate != TCP_ESTABLISHED) 2988 TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB); 2989 break; 2990 case TCP_CLOSE_WAIT: 2991 if (oldstate == TCP_SYN_RECV) 2992 TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB); 2993 break; 2994 2995 case TCP_CLOSE: 2996 if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED) 2997 TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS); 2998 2999 sk->sk_prot->unhash(sk); 3000 if (inet_csk(sk)->icsk_bind_hash && 3001 !(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) 3002 inet_put_port(sk); 3003 fallthrough; 3004 default: 3005 if (oldstate == TCP_ESTABLISHED || oldstate == TCP_CLOSE_WAIT) 3006 TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB); 3007 } 3008 3009 /* Change state AFTER socket is unhashed to avoid closed 3010 * socket sitting in hash tables. 3011 */ 3012 inet_sk_state_store(sk, state); 3013 } 3014 EXPORT_SYMBOL_GPL(tcp_set_state); 3015 3016 /* 3017 * State processing on a close. This implements the state shift for 3018 * sending our FIN frame. Note that we only send a FIN for some 3019 * states. A shutdown() may have already sent the FIN, or we may be 3020 * closed. 3021 */ 3022 3023 static const unsigned char new_state[16] = { 3024 /* current state: new state: action: */ 3025 [0 /* (Invalid) */] = TCP_CLOSE, 3026 [TCP_ESTABLISHED] = TCP_FIN_WAIT1 | TCP_ACTION_FIN, 3027 [TCP_SYN_SENT] = TCP_CLOSE, 3028 [TCP_SYN_RECV] = TCP_FIN_WAIT1 | TCP_ACTION_FIN, 3029 [TCP_FIN_WAIT1] = TCP_FIN_WAIT1, 3030 [TCP_FIN_WAIT2] = TCP_FIN_WAIT2, 3031 [TCP_TIME_WAIT] = TCP_CLOSE, 3032 [TCP_CLOSE] = TCP_CLOSE, 3033 [TCP_CLOSE_WAIT] = TCP_LAST_ACK | TCP_ACTION_FIN, 3034 [TCP_LAST_ACK] = TCP_LAST_ACK, 3035 [TCP_LISTEN] = TCP_CLOSE, 3036 [TCP_CLOSING] = TCP_CLOSING, 3037 [TCP_NEW_SYN_RECV] = TCP_CLOSE, /* should not happen ! */ 3038 }; 3039 3040 static int tcp_close_state(struct sock *sk) 3041 { 3042 int next = (int)new_state[sk->sk_state]; 3043 int ns = next & TCP_STATE_MASK; 3044 3045 tcp_set_state(sk, ns); 3046 3047 return next & TCP_ACTION_FIN; 3048 } 3049 3050 /* 3051 * Shutdown the sending side of a connection. Much like close except 3052 * that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD). 3053 */ 3054 3055 void tcp_shutdown(struct sock *sk, int how) 3056 { 3057 /* We need to grab some memory, and put together a FIN, 3058 * and then put it into the queue to be sent. 3059 * Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92. 3060 */ 3061 if (!(how & SEND_SHUTDOWN)) 3062 return; 3063 3064 /* If we've already sent a FIN, or it's a closed state, skip this. */ 3065 if ((1 << sk->sk_state) & 3066 (TCPF_ESTABLISHED | TCPF_SYN_SENT | 3067 TCPF_CLOSE_WAIT)) { 3068 /* Clear out any half completed packets. FIN if needed. */ 3069 if (tcp_close_state(sk)) 3070 tcp_send_fin(sk); 3071 } 3072 } 3073 EXPORT_IPV6_MOD(tcp_shutdown); 3074 3075 int tcp_orphan_count_sum(void) 3076 { 3077 int i, total = 0; 3078 3079 for_each_possible_cpu(i) 3080 total += per_cpu(tcp_orphan_count, i); 3081 3082 return max(total, 0); 3083 } 3084 3085 static int tcp_orphan_cache; 3086 static struct timer_list tcp_orphan_timer; 3087 #define TCP_ORPHAN_TIMER_PERIOD msecs_to_jiffies(100) 3088 3089 static void tcp_orphan_update(struct timer_list *unused) 3090 { 3091 WRITE_ONCE(tcp_orphan_cache, tcp_orphan_count_sum()); 3092 mod_timer(&tcp_orphan_timer, jiffies + TCP_ORPHAN_TIMER_PERIOD); 3093 } 3094 3095 static bool tcp_too_many_orphans(int shift) 3096 { 3097 return READ_ONCE(tcp_orphan_cache) << shift > 3098 READ_ONCE(sysctl_tcp_max_orphans); 3099 } 3100 3101 static bool tcp_out_of_memory(const struct sock *sk) 3102 { 3103 if (sk->sk_wmem_queued > SOCK_MIN_SNDBUF && 3104 sk_memory_allocated(sk) > sk_prot_mem_limits(sk, 2)) 3105 return true; 3106 return false; 3107 } 3108 3109 bool tcp_check_oom(const struct sock *sk, int shift) 3110 { 3111 bool too_many_orphans, out_of_socket_memory; 3112 3113 too_many_orphans = tcp_too_many_orphans(shift); 3114 out_of_socket_memory = tcp_out_of_memory(sk); 3115 3116 if (too_many_orphans) 3117 net_info_ratelimited("too many orphaned sockets\n"); 3118 if (out_of_socket_memory) 3119 net_info_ratelimited("out of memory -- consider tuning tcp_mem\n"); 3120 return too_many_orphans || out_of_socket_memory; 3121 } 3122 3123 void __tcp_close(struct sock *sk, long timeout) 3124 { 3125 bool data_was_unread = false; 3126 struct sk_buff *skb; 3127 int state; 3128 3129 WRITE_ONCE(sk->sk_shutdown, SHUTDOWN_MASK); 3130 3131 if (sk->sk_state == TCP_LISTEN) { 3132 tcp_set_state(sk, TCP_CLOSE); 3133 3134 /* Special case. */ 3135 inet_csk_listen_stop(sk); 3136 3137 goto adjudge_to_death; 3138 } 3139 3140 /* We need to flush the recv. buffs. We do this only on the 3141 * descriptor close, not protocol-sourced closes, because the 3142 * reader process may not have drained the data yet! 3143 */ 3144 while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) { 3145 u32 end_seq = TCP_SKB_CB(skb)->end_seq; 3146 3147 if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) 3148 end_seq--; 3149 if (after(end_seq, tcp_sk(sk)->copied_seq)) 3150 data_was_unread = true; 3151 tcp_eat_recv_skb(sk, skb); 3152 } 3153 3154 /* If socket has been already reset (e.g. in tcp_reset()) - kill it. */ 3155 if (sk->sk_state == TCP_CLOSE) 3156 goto adjudge_to_death; 3157 3158 /* As outlined in RFC 2525, section 2.17, we send a RST here because 3159 * data was lost. To witness the awful effects of the old behavior of 3160 * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk 3161 * GET in an FTP client, suspend the process, wait for the client to 3162 * advertise a zero window, then kill -9 the FTP client, wheee... 3163 * Note: timeout is always zero in such a case. 3164 */ 3165 if (unlikely(tcp_sk(sk)->repair)) { 3166 sk->sk_prot->disconnect(sk, 0); 3167 } else if (data_was_unread) { 3168 /* Unread data was tossed, zap the connection. */ 3169 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE); 3170 tcp_set_state(sk, TCP_CLOSE); 3171 tcp_send_active_reset(sk, sk->sk_allocation, 3172 SK_RST_REASON_TCP_ABORT_ON_CLOSE); 3173 } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) { 3174 /* Check zero linger _after_ checking for unread data. */ 3175 sk->sk_prot->disconnect(sk, 0); 3176 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA); 3177 } else if (tcp_close_state(sk)) { 3178 /* We FIN if the application ate all the data before 3179 * zapping the connection. 3180 */ 3181 3182 /* RED-PEN. Formally speaking, we have broken TCP state 3183 * machine. State transitions: 3184 * 3185 * TCP_ESTABLISHED -> TCP_FIN_WAIT1 3186 * TCP_SYN_RECV -> TCP_FIN_WAIT1 (it is difficult) 3187 * TCP_CLOSE_WAIT -> TCP_LAST_ACK 3188 * 3189 * are legal only when FIN has been sent (i.e. in window), 3190 * rather than queued out of window. Purists blame. 3191 * 3192 * F.e. "RFC state" is ESTABLISHED, 3193 * if Linux state is FIN-WAIT-1, but FIN is still not sent. 3194 * 3195 * The visible declinations are that sometimes 3196 * we enter time-wait state, when it is not required really 3197 * (harmless), do not send active resets, when they are 3198 * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when 3199 * they look as CLOSING or LAST_ACK for Linux) 3200 * Probably, I missed some more holelets. 3201 * --ANK 3202 * XXX (TFO) - To start off we don't support SYN+ACK+FIN 3203 * in a single packet! (May consider it later but will 3204 * probably need API support or TCP_CORK SYN-ACK until 3205 * data is written and socket is closed.) 3206 */ 3207 tcp_send_fin(sk); 3208 } 3209 3210 sk_stream_wait_close(sk, timeout); 3211 3212 adjudge_to_death: 3213 state = sk->sk_state; 3214 sock_hold(sk); 3215 sock_orphan(sk); 3216 3217 local_bh_disable(); 3218 bh_lock_sock(sk); 3219 /* remove backlog if any, without releasing ownership. */ 3220 __release_sock(sk); 3221 3222 tcp_orphan_count_inc(); 3223 3224 /* Have we already been destroyed by a softirq or backlog? */ 3225 if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE) 3226 goto out; 3227 3228 /* This is a (useful) BSD violating of the RFC. There is a 3229 * problem with TCP as specified in that the other end could 3230 * keep a socket open forever with no application left this end. 3231 * We use a 1 minute timeout (about the same as BSD) then kill 3232 * our end. If they send after that then tough - BUT: long enough 3233 * that we won't make the old 4*rto = almost no time - whoops 3234 * reset mistake. 3235 * 3236 * Nope, it was not mistake. It is really desired behaviour 3237 * f.e. on http servers, when such sockets are useless, but 3238 * consume significant resources. Let's do it with special 3239 * linger2 option. --ANK 3240 */ 3241 3242 if (sk->sk_state == TCP_FIN_WAIT2) { 3243 struct tcp_sock *tp = tcp_sk(sk); 3244 if (READ_ONCE(tp->linger2) < 0) { 3245 tcp_set_state(sk, TCP_CLOSE); 3246 tcp_send_active_reset(sk, GFP_ATOMIC, 3247 SK_RST_REASON_TCP_ABORT_ON_LINGER); 3248 __NET_INC_STATS(sock_net(sk), 3249 LINUX_MIB_TCPABORTONLINGER); 3250 } else { 3251 const int tmo = tcp_fin_time(sk); 3252 3253 if (tmo > TCP_TIMEWAIT_LEN) { 3254 tcp_reset_keepalive_timer(sk, 3255 tmo - TCP_TIMEWAIT_LEN); 3256 } else { 3257 tcp_time_wait(sk, TCP_FIN_WAIT2, tmo); 3258 goto out; 3259 } 3260 } 3261 } 3262 if (sk->sk_state != TCP_CLOSE) { 3263 if (tcp_check_oom(sk, 0)) { 3264 tcp_set_state(sk, TCP_CLOSE); 3265 tcp_send_active_reset(sk, GFP_ATOMIC, 3266 SK_RST_REASON_TCP_ABORT_ON_MEMORY); 3267 __NET_INC_STATS(sock_net(sk), 3268 LINUX_MIB_TCPABORTONMEMORY); 3269 } else if (!check_net(sock_net(sk))) { 3270 /* Not possible to send reset; just close */ 3271 tcp_set_state(sk, TCP_CLOSE); 3272 } 3273 } 3274 3275 if (sk->sk_state == TCP_CLOSE) { 3276 struct request_sock *req; 3277 3278 req = rcu_dereference_protected(tcp_sk(sk)->fastopen_rsk, 3279 lockdep_sock_is_held(sk)); 3280 /* We could get here with a non-NULL req if the socket is 3281 * aborted (e.g., closed with unread data) before 3WHS 3282 * finishes. 3283 */ 3284 if (req) 3285 reqsk_fastopen_remove(sk, req, false); 3286 inet_csk_destroy_sock(sk); 3287 } 3288 /* Otherwise, socket is reprieved until protocol close. */ 3289 3290 out: 3291 bh_unlock_sock(sk); 3292 local_bh_enable(); 3293 } 3294 3295 void tcp_close(struct sock *sk, long timeout) 3296 { 3297 lock_sock(sk); 3298 __tcp_close(sk, timeout); 3299 release_sock(sk); 3300 if (!sk->sk_net_refcnt) 3301 inet_csk_clear_xmit_timers_sync(sk); 3302 sock_put(sk); 3303 } 3304 EXPORT_SYMBOL(tcp_close); 3305 3306 /* These states need RST on ABORT according to RFC793 */ 3307 3308 static inline bool tcp_need_reset(int state) 3309 { 3310 return (1 << state) & 3311 (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 | 3312 TCPF_FIN_WAIT2 | TCPF_SYN_RECV); 3313 } 3314 3315 static void tcp_rtx_queue_purge(struct sock *sk) 3316 { 3317 struct rb_node *p = rb_first(&sk->tcp_rtx_queue); 3318 3319 tcp_sk(sk)->highest_sack = NULL; 3320 while (p) { 3321 struct sk_buff *skb = rb_to_skb(p); 3322 3323 p = rb_next(p); 3324 /* Since we are deleting whole queue, no need to 3325 * list_del(&skb->tcp_tsorted_anchor) 3326 */ 3327 tcp_rtx_queue_unlink(skb, sk); 3328 tcp_wmem_free_skb(sk, skb); 3329 } 3330 } 3331 3332 void tcp_write_queue_purge(struct sock *sk) 3333 { 3334 struct sk_buff *skb; 3335 3336 tcp_chrono_stop(sk, TCP_CHRONO_BUSY); 3337 while ((skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) { 3338 tcp_skb_tsorted_anchor_cleanup(skb); 3339 tcp_wmem_free_skb(sk, skb); 3340 } 3341 tcp_rtx_queue_purge(sk); 3342 INIT_LIST_HEAD(&tcp_sk(sk)->tsorted_sent_queue); 3343 tcp_clear_all_retrans_hints(tcp_sk(sk)); 3344 tcp_sk(sk)->packets_out = 0; 3345 inet_csk(sk)->icsk_backoff = 0; 3346 } 3347 3348 int tcp_disconnect(struct sock *sk, int flags) 3349 { 3350 struct inet_sock *inet = inet_sk(sk); 3351 struct inet_connection_sock *icsk = inet_csk(sk); 3352 struct tcp_sock *tp = tcp_sk(sk); 3353 int old_state = sk->sk_state; 3354 struct request_sock *req; 3355 u32 seq; 3356 3357 if (old_state != TCP_CLOSE) 3358 tcp_set_state(sk, TCP_CLOSE); 3359 3360 /* ABORT function of RFC793 */ 3361 if (old_state == TCP_LISTEN) { 3362 inet_csk_listen_stop(sk); 3363 } else if (unlikely(tp->repair)) { 3364 WRITE_ONCE(sk->sk_err, ECONNABORTED); 3365 } else if (tcp_need_reset(old_state)) { 3366 tcp_send_active_reset(sk, gfp_any(), SK_RST_REASON_TCP_STATE); 3367 WRITE_ONCE(sk->sk_err, ECONNRESET); 3368 } else if (tp->snd_nxt != tp->write_seq && 3369 (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK)) { 3370 /* The last check adjusts for discrepancy of Linux wrt. RFC 3371 * states 3372 */ 3373 tcp_send_active_reset(sk, gfp_any(), 3374 SK_RST_REASON_TCP_DISCONNECT_WITH_DATA); 3375 WRITE_ONCE(sk->sk_err, ECONNRESET); 3376 } else if (old_state == TCP_SYN_SENT) 3377 WRITE_ONCE(sk->sk_err, ECONNRESET); 3378 3379 tcp_clear_xmit_timers(sk); 3380 __skb_queue_purge(&sk->sk_receive_queue); 3381 WRITE_ONCE(tp->copied_seq, tp->rcv_nxt); 3382 WRITE_ONCE(tp->urg_data, 0); 3383 sk_set_peek_off(sk, -1); 3384 tcp_write_queue_purge(sk); 3385 tcp_fastopen_active_disable_ofo_check(sk); 3386 skb_rbtree_purge(&tp->out_of_order_queue); 3387 3388 inet->inet_dport = 0; 3389 3390 inet_bhash2_reset_saddr(sk); 3391 3392 WRITE_ONCE(sk->sk_shutdown, 0); 3393 sock_reset_flag(sk, SOCK_DONE); 3394 tp->srtt_us = 0; 3395 tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT); 3396 tp->rcv_rtt_last_tsecr = 0; 3397 3398 seq = tp->write_seq + tp->max_window + 2; 3399 if (!seq) 3400 seq = 1; 3401 WRITE_ONCE(tp->write_seq, seq); 3402 3403 icsk->icsk_backoff = 0; 3404 WRITE_ONCE(icsk->icsk_probes_out, 0); 3405 icsk->icsk_probes_tstamp = 0; 3406 icsk->icsk_rto = TCP_TIMEOUT_INIT; 3407 WRITE_ONCE(icsk->icsk_rto_min, TCP_RTO_MIN); 3408 WRITE_ONCE(icsk->icsk_delack_max, TCP_DELACK_MAX); 3409 tp->snd_ssthresh = TCP_INFINITE_SSTHRESH; 3410 tcp_snd_cwnd_set(tp, TCP_INIT_CWND); 3411 tp->snd_cwnd_cnt = 0; 3412 tp->is_cwnd_limited = 0; 3413 tp->max_packets_out = 0; 3414 tp->window_clamp = 0; 3415 tp->delivered = 0; 3416 tp->delivered_ce = 0; 3417 tp->accecn_fail_mode = 0; 3418 tp->saw_accecn_opt = TCP_ACCECN_OPT_NOT_SEEN; 3419 tcp_accecn_init_counters(tp); 3420 tp->prev_ecnfield = 0; 3421 tp->accecn_opt_tstamp = 0; 3422 if (icsk->icsk_ca_initialized && icsk->icsk_ca_ops->release) 3423 icsk->icsk_ca_ops->release(sk); 3424 memset(icsk->icsk_ca_priv, 0, sizeof(icsk->icsk_ca_priv)); 3425 icsk->icsk_ca_initialized = 0; 3426 tcp_set_ca_state(sk, TCP_CA_Open); 3427 tp->is_sack_reneg = 0; 3428 tcp_clear_retrans(tp); 3429 tp->total_retrans = 0; 3430 inet_csk_delack_init(sk); 3431 /* Initialize rcv_mss to TCP_MIN_MSS to avoid division by 0 3432 * issue in __tcp_select_window() 3433 */ 3434 icsk->icsk_ack.rcv_mss = TCP_MIN_MSS; 3435 memset(&tp->rx_opt, 0, sizeof(tp->rx_opt)); 3436 __sk_dst_reset(sk); 3437 dst_release(unrcu_pointer(xchg(&sk->sk_rx_dst, NULL))); 3438 tcp_saved_syn_free(tp); 3439 tp->compressed_ack = 0; 3440 tp->segs_in = 0; 3441 tp->segs_out = 0; 3442 tp->bytes_sent = 0; 3443 tp->bytes_acked = 0; 3444 tp->bytes_received = 0; 3445 tp->bytes_retrans = 0; 3446 tp->data_segs_in = 0; 3447 tp->data_segs_out = 0; 3448 tp->duplicate_sack[0].start_seq = 0; 3449 tp->duplicate_sack[0].end_seq = 0; 3450 tp->dsack_dups = 0; 3451 tp->reord_seen = 0; 3452 tp->retrans_out = 0; 3453 tp->sacked_out = 0; 3454 tp->tlp_high_seq = 0; 3455 tp->last_oow_ack_time = 0; 3456 tp->plb_rehash = 0; 3457 /* There's a bubble in the pipe until at least the first ACK. */ 3458 tp->app_limited = ~0U; 3459 tp->rate_app_limited = 1; 3460 tp->rack.mstamp = 0; 3461 tp->rack.advanced = 0; 3462 tp->rack.reo_wnd_steps = 1; 3463 tp->rack.last_delivered = 0; 3464 tp->rack.reo_wnd_persist = 0; 3465 tp->rack.dsack_seen = 0; 3466 tp->syn_data_acked = 0; 3467 tp->syn_fastopen_child = 0; 3468 tp->rx_opt.saw_tstamp = 0; 3469 tp->rx_opt.dsack = 0; 3470 tp->rx_opt.num_sacks = 0; 3471 tp->rcv_ooopack = 0; 3472 3473 3474 /* Clean up fastopen related fields */ 3475 req = rcu_dereference_protected(tp->fastopen_rsk, 3476 lockdep_sock_is_held(sk)); 3477 if (req) 3478 reqsk_fastopen_remove(sk, req, false); 3479 tcp_free_fastopen_req(tp); 3480 inet_clear_bit(DEFER_CONNECT, sk); 3481 tp->fastopen_client_fail = 0; 3482 3483 WARN_ON(inet->inet_num && !icsk->icsk_bind_hash); 3484 3485 if (sk->sk_frag.page) { 3486 put_page(sk->sk_frag.page); 3487 sk->sk_frag.page = NULL; 3488 sk->sk_frag.offset = 0; 3489 } 3490 sk_error_report(sk); 3491 return 0; 3492 } 3493 EXPORT_SYMBOL(tcp_disconnect); 3494 3495 static inline bool tcp_can_repair_sock(const struct sock *sk) 3496 { 3497 return sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN) && 3498 (sk->sk_state != TCP_LISTEN); 3499 } 3500 3501 static int tcp_repair_set_window(struct tcp_sock *tp, sockptr_t optbuf, int len) 3502 { 3503 struct tcp_repair_window opt; 3504 3505 if (!tp->repair) 3506 return -EPERM; 3507 3508 if (len != sizeof(opt)) 3509 return -EINVAL; 3510 3511 if (copy_from_sockptr(&opt, optbuf, sizeof(opt))) 3512 return -EFAULT; 3513 3514 if (opt.max_window < opt.snd_wnd) 3515 return -EINVAL; 3516 3517 if (after(opt.snd_wl1, tp->rcv_nxt + opt.rcv_wnd)) 3518 return -EINVAL; 3519 3520 if (after(opt.rcv_wup, tp->rcv_nxt)) 3521 return -EINVAL; 3522 3523 tp->snd_wl1 = opt.snd_wl1; 3524 tp->snd_wnd = opt.snd_wnd; 3525 tp->max_window = opt.max_window; 3526 3527 tp->rcv_wnd = opt.rcv_wnd; 3528 tp->rcv_wup = opt.rcv_wup; 3529 3530 return 0; 3531 } 3532 3533 static int tcp_repair_options_est(struct sock *sk, sockptr_t optbuf, 3534 unsigned int len) 3535 { 3536 struct tcp_sock *tp = tcp_sk(sk); 3537 struct tcp_repair_opt opt; 3538 size_t offset = 0; 3539 3540 while (len >= sizeof(opt)) { 3541 if (copy_from_sockptr_offset(&opt, optbuf, offset, sizeof(opt))) 3542 return -EFAULT; 3543 3544 offset += sizeof(opt); 3545 len -= sizeof(opt); 3546 3547 switch (opt.opt_code) { 3548 case TCPOPT_MSS: 3549 tp->rx_opt.mss_clamp = opt.opt_val; 3550 tcp_mtup_init(sk); 3551 break; 3552 case TCPOPT_WINDOW: 3553 { 3554 u16 snd_wscale = opt.opt_val & 0xFFFF; 3555 u16 rcv_wscale = opt.opt_val >> 16; 3556 3557 if (snd_wscale > TCP_MAX_WSCALE || rcv_wscale > TCP_MAX_WSCALE) 3558 return -EFBIG; 3559 3560 tp->rx_opt.snd_wscale = snd_wscale; 3561 tp->rx_opt.rcv_wscale = rcv_wscale; 3562 tp->rx_opt.wscale_ok = 1; 3563 } 3564 break; 3565 case TCPOPT_SACK_PERM: 3566 if (opt.opt_val != 0) 3567 return -EINVAL; 3568 3569 tp->rx_opt.sack_ok |= TCP_SACK_SEEN; 3570 break; 3571 case TCPOPT_TIMESTAMP: 3572 if (opt.opt_val != 0) 3573 return -EINVAL; 3574 3575 tp->rx_opt.tstamp_ok = 1; 3576 break; 3577 } 3578 } 3579 3580 return 0; 3581 } 3582 3583 DEFINE_STATIC_KEY_FALSE(tcp_tx_delay_enabled); 3584 EXPORT_IPV6_MOD(tcp_tx_delay_enabled); 3585 3586 static void tcp_enable_tx_delay(void) 3587 { 3588 if (!static_branch_unlikely(&tcp_tx_delay_enabled)) { 3589 static int __tcp_tx_delay_enabled = 0; 3590 3591 if (cmpxchg(&__tcp_tx_delay_enabled, 0, 1) == 0) { 3592 static_branch_enable(&tcp_tx_delay_enabled); 3593 pr_info("TCP_TX_DELAY enabled\n"); 3594 } 3595 } 3596 } 3597 3598 /* When set indicates to always queue non-full frames. Later the user clears 3599 * this option and we transmit any pending partial frames in the queue. This is 3600 * meant to be used alongside sendfile() to get properly filled frames when the 3601 * user (for example) must write out headers with a write() call first and then 3602 * use sendfile to send out the data parts. 3603 * 3604 * TCP_CORK can be set together with TCP_NODELAY and it is stronger than 3605 * TCP_NODELAY. 3606 */ 3607 void __tcp_sock_set_cork(struct sock *sk, bool on) 3608 { 3609 struct tcp_sock *tp = tcp_sk(sk); 3610 3611 if (on) { 3612 tp->nonagle |= TCP_NAGLE_CORK; 3613 } else { 3614 tp->nonagle &= ~TCP_NAGLE_CORK; 3615 if (tp->nonagle & TCP_NAGLE_OFF) 3616 tp->nonagle |= TCP_NAGLE_PUSH; 3617 tcp_push_pending_frames(sk); 3618 } 3619 } 3620 3621 void tcp_sock_set_cork(struct sock *sk, bool on) 3622 { 3623 lock_sock(sk); 3624 __tcp_sock_set_cork(sk, on); 3625 release_sock(sk); 3626 } 3627 EXPORT_SYMBOL(tcp_sock_set_cork); 3628 3629 /* TCP_NODELAY is weaker than TCP_CORK, so that this option on corked socket is 3630 * remembered, but it is not activated until cork is cleared. 3631 * 3632 * However, when TCP_NODELAY is set we make an explicit push, which overrides 3633 * even TCP_CORK for currently queued segments. 3634 */ 3635 void __tcp_sock_set_nodelay(struct sock *sk, bool on) 3636 { 3637 if (on) { 3638 tcp_sk(sk)->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH; 3639 tcp_push_pending_frames(sk); 3640 } else { 3641 tcp_sk(sk)->nonagle &= ~TCP_NAGLE_OFF; 3642 } 3643 } 3644 3645 void tcp_sock_set_nodelay(struct sock *sk) 3646 { 3647 lock_sock(sk); 3648 __tcp_sock_set_nodelay(sk, true); 3649 release_sock(sk); 3650 } 3651 EXPORT_SYMBOL(tcp_sock_set_nodelay); 3652 3653 static void __tcp_sock_set_quickack(struct sock *sk, int val) 3654 { 3655 if (!val) { 3656 inet_csk_enter_pingpong_mode(sk); 3657 return; 3658 } 3659 3660 inet_csk_exit_pingpong_mode(sk); 3661 if ((1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) && 3662 inet_csk_ack_scheduled(sk)) { 3663 inet_csk(sk)->icsk_ack.pending |= ICSK_ACK_PUSHED; 3664 tcp_cleanup_rbuf(sk, 1); 3665 if (!(val & 1)) 3666 inet_csk_enter_pingpong_mode(sk); 3667 } 3668 } 3669 3670 void tcp_sock_set_quickack(struct sock *sk, int val) 3671 { 3672 lock_sock(sk); 3673 __tcp_sock_set_quickack(sk, val); 3674 release_sock(sk); 3675 } 3676 EXPORT_SYMBOL(tcp_sock_set_quickack); 3677 3678 int tcp_sock_set_syncnt(struct sock *sk, int val) 3679 { 3680 if (val < 1 || val > MAX_TCP_SYNCNT) 3681 return -EINVAL; 3682 3683 WRITE_ONCE(inet_csk(sk)->icsk_syn_retries, val); 3684 return 0; 3685 } 3686 EXPORT_SYMBOL(tcp_sock_set_syncnt); 3687 3688 int tcp_sock_set_user_timeout(struct sock *sk, int val) 3689 { 3690 /* Cap the max time in ms TCP will retry or probe the window 3691 * before giving up and aborting (ETIMEDOUT) a connection. 3692 */ 3693 if (val < 0) 3694 return -EINVAL; 3695 3696 WRITE_ONCE(inet_csk(sk)->icsk_user_timeout, val); 3697 return 0; 3698 } 3699 EXPORT_SYMBOL(tcp_sock_set_user_timeout); 3700 3701 int tcp_sock_set_keepidle_locked(struct sock *sk, int val) 3702 { 3703 struct tcp_sock *tp = tcp_sk(sk); 3704 3705 if (val < 1 || val > MAX_TCP_KEEPIDLE) 3706 return -EINVAL; 3707 3708 /* Paired with WRITE_ONCE() in keepalive_time_when() */ 3709 WRITE_ONCE(tp->keepalive_time, val * HZ); 3710 if (sock_flag(sk, SOCK_KEEPOPEN) && 3711 !((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) { 3712 u32 elapsed = keepalive_time_elapsed(tp); 3713 3714 if (tp->keepalive_time > elapsed) 3715 elapsed = tp->keepalive_time - elapsed; 3716 else 3717 elapsed = 0; 3718 tcp_reset_keepalive_timer(sk, elapsed); 3719 } 3720 3721 return 0; 3722 } 3723 3724 int tcp_sock_set_keepidle(struct sock *sk, int val) 3725 { 3726 int err; 3727 3728 lock_sock(sk); 3729 err = tcp_sock_set_keepidle_locked(sk, val); 3730 release_sock(sk); 3731 return err; 3732 } 3733 EXPORT_SYMBOL(tcp_sock_set_keepidle); 3734 3735 int tcp_sock_set_keepintvl(struct sock *sk, int val) 3736 { 3737 if (val < 1 || val > MAX_TCP_KEEPINTVL) 3738 return -EINVAL; 3739 3740 WRITE_ONCE(tcp_sk(sk)->keepalive_intvl, val * HZ); 3741 return 0; 3742 } 3743 EXPORT_SYMBOL(tcp_sock_set_keepintvl); 3744 3745 int tcp_sock_set_keepcnt(struct sock *sk, int val) 3746 { 3747 if (val < 1 || val > MAX_TCP_KEEPCNT) 3748 return -EINVAL; 3749 3750 /* Paired with READ_ONCE() in keepalive_probes() */ 3751 WRITE_ONCE(tcp_sk(sk)->keepalive_probes, val); 3752 return 0; 3753 } 3754 EXPORT_SYMBOL(tcp_sock_set_keepcnt); 3755 3756 int tcp_set_window_clamp(struct sock *sk, int val) 3757 { 3758 u32 old_window_clamp, new_window_clamp, new_rcv_ssthresh; 3759 struct tcp_sock *tp = tcp_sk(sk); 3760 3761 if (!val) { 3762 if (sk->sk_state != TCP_CLOSE) 3763 return -EINVAL; 3764 WRITE_ONCE(tp->window_clamp, 0); 3765 return 0; 3766 } 3767 3768 old_window_clamp = tp->window_clamp; 3769 new_window_clamp = max_t(int, SOCK_MIN_RCVBUF / 2, val); 3770 3771 if (new_window_clamp == old_window_clamp) 3772 return 0; 3773 3774 WRITE_ONCE(tp->window_clamp, new_window_clamp); 3775 3776 /* Need to apply the reserved mem provisioning only 3777 * when shrinking the window clamp. 3778 */ 3779 if (new_window_clamp < old_window_clamp) { 3780 __tcp_adjust_rcv_ssthresh(sk, new_window_clamp); 3781 } else { 3782 new_rcv_ssthresh = min(tp->rcv_wnd, new_window_clamp); 3783 tp->rcv_ssthresh = max(new_rcv_ssthresh, tp->rcv_ssthresh); 3784 } 3785 return 0; 3786 } 3787 3788 int tcp_sock_set_maxseg(struct sock *sk, int val) 3789 { 3790 /* Values greater than interface MTU won't take effect. However 3791 * at the point when this call is done we typically don't yet 3792 * know which interface is going to be used 3793 */ 3794 if (val && (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW)) 3795 return -EINVAL; 3796 3797 WRITE_ONCE(tcp_sk(sk)->rx_opt.user_mss, val); 3798 return 0; 3799 } 3800 3801 /* 3802 * Socket option code for TCP. 3803 */ 3804 int do_tcp_setsockopt(struct sock *sk, int level, int optname, 3805 sockptr_t optval, unsigned int optlen) 3806 { 3807 struct tcp_sock *tp = tcp_sk(sk); 3808 struct inet_connection_sock *icsk = inet_csk(sk); 3809 struct net *net = sock_net(sk); 3810 int val; 3811 int err = 0; 3812 3813 /* These are data/string values, all the others are ints */ 3814 switch (optname) { 3815 case TCP_CONGESTION: { 3816 char name[TCP_CA_NAME_MAX]; 3817 3818 if (optlen < 1) 3819 return -EINVAL; 3820 3821 val = strncpy_from_sockptr(name, optval, 3822 min_t(long, TCP_CA_NAME_MAX-1, optlen)); 3823 if (val < 0) 3824 return -EFAULT; 3825 name[val] = 0; 3826 3827 sockopt_lock_sock(sk); 3828 err = tcp_set_congestion_control(sk, name, !has_current_bpf_ctx(), 3829 sockopt_ns_capable(sock_net(sk)->user_ns, 3830 CAP_NET_ADMIN)); 3831 sockopt_release_sock(sk); 3832 return err; 3833 } 3834 case TCP_ULP: { 3835 char name[TCP_ULP_NAME_MAX]; 3836 3837 if (optlen < 1) 3838 return -EINVAL; 3839 3840 val = strncpy_from_sockptr(name, optval, 3841 min_t(long, TCP_ULP_NAME_MAX - 1, 3842 optlen)); 3843 if (val < 0) 3844 return -EFAULT; 3845 name[val] = 0; 3846 3847 sockopt_lock_sock(sk); 3848 err = tcp_set_ulp(sk, name); 3849 sockopt_release_sock(sk); 3850 return err; 3851 } 3852 case TCP_FASTOPEN_KEY: { 3853 __u8 key[TCP_FASTOPEN_KEY_BUF_LENGTH]; 3854 __u8 *backup_key = NULL; 3855 3856 /* Allow a backup key as well to facilitate key rotation 3857 * First key is the active one. 3858 */ 3859 if (optlen != TCP_FASTOPEN_KEY_LENGTH && 3860 optlen != TCP_FASTOPEN_KEY_BUF_LENGTH) 3861 return -EINVAL; 3862 3863 if (copy_from_sockptr(key, optval, optlen)) 3864 return -EFAULT; 3865 3866 if (optlen == TCP_FASTOPEN_KEY_BUF_LENGTH) 3867 backup_key = key + TCP_FASTOPEN_KEY_LENGTH; 3868 3869 return tcp_fastopen_reset_cipher(net, sk, key, backup_key); 3870 } 3871 default: 3872 /* fallthru */ 3873 break; 3874 } 3875 3876 if (optlen < sizeof(int)) 3877 return -EINVAL; 3878 3879 if (copy_from_sockptr(&val, optval, sizeof(val))) 3880 return -EFAULT; 3881 3882 /* Handle options that can be set without locking the socket. */ 3883 switch (optname) { 3884 case TCP_SYNCNT: 3885 return tcp_sock_set_syncnt(sk, val); 3886 case TCP_USER_TIMEOUT: 3887 return tcp_sock_set_user_timeout(sk, val); 3888 case TCP_KEEPINTVL: 3889 return tcp_sock_set_keepintvl(sk, val); 3890 case TCP_KEEPCNT: 3891 return tcp_sock_set_keepcnt(sk, val); 3892 case TCP_LINGER2: 3893 if (val < 0) 3894 WRITE_ONCE(tp->linger2, -1); 3895 else if (val > TCP_FIN_TIMEOUT_MAX / HZ) 3896 WRITE_ONCE(tp->linger2, TCP_FIN_TIMEOUT_MAX); 3897 else 3898 WRITE_ONCE(tp->linger2, val * HZ); 3899 return 0; 3900 case TCP_DEFER_ACCEPT: 3901 /* Translate value in seconds to number of retransmits */ 3902 WRITE_ONCE(icsk->icsk_accept_queue.rskq_defer_accept, 3903 secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ, 3904 TCP_RTO_MAX / HZ)); 3905 return 0; 3906 case TCP_RTO_MAX_MS: 3907 if (val < MSEC_PER_SEC || val > TCP_RTO_MAX_SEC * MSEC_PER_SEC) 3908 return -EINVAL; 3909 WRITE_ONCE(inet_csk(sk)->icsk_rto_max, msecs_to_jiffies(val)); 3910 return 0; 3911 case TCP_RTO_MIN_US: { 3912 int rto_min = usecs_to_jiffies(val); 3913 3914 if (rto_min > TCP_RTO_MIN || rto_min < TCP_TIMEOUT_MIN) 3915 return -EINVAL; 3916 WRITE_ONCE(inet_csk(sk)->icsk_rto_min, rto_min); 3917 return 0; 3918 } 3919 case TCP_DELACK_MAX_US: { 3920 int delack_max = usecs_to_jiffies(val); 3921 3922 if (delack_max > TCP_DELACK_MAX || delack_max < TCP_TIMEOUT_MIN) 3923 return -EINVAL; 3924 WRITE_ONCE(inet_csk(sk)->icsk_delack_max, delack_max); 3925 return 0; 3926 } 3927 case TCP_MAXSEG: 3928 return tcp_sock_set_maxseg(sk, val); 3929 } 3930 3931 sockopt_lock_sock(sk); 3932 3933 switch (optname) { 3934 case TCP_NODELAY: 3935 __tcp_sock_set_nodelay(sk, val); 3936 break; 3937 3938 case TCP_THIN_LINEAR_TIMEOUTS: 3939 if (val < 0 || val > 1) 3940 err = -EINVAL; 3941 else 3942 tp->thin_lto = val; 3943 break; 3944 3945 case TCP_THIN_DUPACK: 3946 if (val < 0 || val > 1) 3947 err = -EINVAL; 3948 break; 3949 3950 case TCP_REPAIR: 3951 if (!tcp_can_repair_sock(sk)) 3952 err = -EPERM; 3953 else if (val == TCP_REPAIR_ON) { 3954 tp->repair = 1; 3955 sk->sk_reuse = SK_FORCE_REUSE; 3956 tp->repair_queue = TCP_NO_QUEUE; 3957 } else if (val == TCP_REPAIR_OFF) { 3958 tp->repair = 0; 3959 sk->sk_reuse = SK_NO_REUSE; 3960 tcp_send_window_probe(sk); 3961 } else if (val == TCP_REPAIR_OFF_NO_WP) { 3962 tp->repair = 0; 3963 sk->sk_reuse = SK_NO_REUSE; 3964 } else 3965 err = -EINVAL; 3966 3967 break; 3968 3969 case TCP_REPAIR_QUEUE: 3970 if (!tp->repair) 3971 err = -EPERM; 3972 else if ((unsigned int)val < TCP_QUEUES_NR) 3973 tp->repair_queue = val; 3974 else 3975 err = -EINVAL; 3976 break; 3977 3978 case TCP_QUEUE_SEQ: 3979 if (sk->sk_state != TCP_CLOSE) { 3980 err = -EPERM; 3981 } else if (tp->repair_queue == TCP_SEND_QUEUE) { 3982 if (!tcp_rtx_queue_empty(sk)) 3983 err = -EPERM; 3984 else 3985 WRITE_ONCE(tp->write_seq, val); 3986 } else if (tp->repair_queue == TCP_RECV_QUEUE) { 3987 if (tp->rcv_nxt != tp->copied_seq) { 3988 err = -EPERM; 3989 } else { 3990 WRITE_ONCE(tp->rcv_nxt, val); 3991 WRITE_ONCE(tp->copied_seq, val); 3992 } 3993 } else { 3994 err = -EINVAL; 3995 } 3996 break; 3997 3998 case TCP_REPAIR_OPTIONS: 3999 if (!tp->repair) 4000 err = -EINVAL; 4001 else if (sk->sk_state == TCP_ESTABLISHED && !tp->bytes_sent) 4002 err = tcp_repair_options_est(sk, optval, optlen); 4003 else 4004 err = -EPERM; 4005 break; 4006 4007 case TCP_CORK: 4008 __tcp_sock_set_cork(sk, val); 4009 break; 4010 4011 case TCP_KEEPIDLE: 4012 err = tcp_sock_set_keepidle_locked(sk, val); 4013 break; 4014 case TCP_SAVE_SYN: 4015 /* 0: disable, 1: enable, 2: start from ether_header */ 4016 if (val < 0 || val > 2) 4017 err = -EINVAL; 4018 else 4019 tp->save_syn = val; 4020 break; 4021 4022 case TCP_WINDOW_CLAMP: 4023 err = tcp_set_window_clamp(sk, val); 4024 break; 4025 4026 case TCP_QUICKACK: 4027 __tcp_sock_set_quickack(sk, val); 4028 break; 4029 4030 case TCP_AO_REPAIR: 4031 if (!tcp_can_repair_sock(sk)) { 4032 err = -EPERM; 4033 break; 4034 } 4035 err = tcp_ao_set_repair(sk, optval, optlen); 4036 break; 4037 #ifdef CONFIG_TCP_AO 4038 case TCP_AO_ADD_KEY: 4039 case TCP_AO_DEL_KEY: 4040 case TCP_AO_INFO: { 4041 /* If this is the first TCP-AO setsockopt() on the socket, 4042 * sk_state has to be LISTEN or CLOSE. Allow TCP_REPAIR 4043 * in any state. 4044 */ 4045 if ((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) 4046 goto ao_parse; 4047 if (rcu_dereference_protected(tcp_sk(sk)->ao_info, 4048 lockdep_sock_is_held(sk))) 4049 goto ao_parse; 4050 if (tp->repair) 4051 goto ao_parse; 4052 err = -EISCONN; 4053 break; 4054 ao_parse: 4055 err = tp->af_specific->ao_parse(sk, optname, optval, optlen); 4056 break; 4057 } 4058 #endif 4059 #ifdef CONFIG_TCP_MD5SIG 4060 case TCP_MD5SIG: 4061 case TCP_MD5SIG_EXT: 4062 err = tp->af_specific->md5_parse(sk, optname, optval, optlen); 4063 break; 4064 #endif 4065 case TCP_FASTOPEN: 4066 if (val >= 0 && ((1 << sk->sk_state) & (TCPF_CLOSE | 4067 TCPF_LISTEN))) { 4068 tcp_fastopen_init_key_once(net); 4069 4070 fastopen_queue_tune(sk, val); 4071 } else { 4072 err = -EINVAL; 4073 } 4074 break; 4075 case TCP_FASTOPEN_CONNECT: 4076 if (val > 1 || val < 0) { 4077 err = -EINVAL; 4078 } else if (READ_ONCE(net->ipv4.sysctl_tcp_fastopen) & 4079 TFO_CLIENT_ENABLE) { 4080 if (sk->sk_state == TCP_CLOSE) 4081 tp->fastopen_connect = val; 4082 else 4083 err = -EINVAL; 4084 } else { 4085 err = -EOPNOTSUPP; 4086 } 4087 break; 4088 case TCP_FASTOPEN_NO_COOKIE: 4089 if (val > 1 || val < 0) 4090 err = -EINVAL; 4091 else if (!((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) 4092 err = -EINVAL; 4093 else 4094 tp->fastopen_no_cookie = val; 4095 break; 4096 case TCP_TIMESTAMP: 4097 if (!tp->repair) { 4098 err = -EPERM; 4099 break; 4100 } 4101 /* val is an opaque field, 4102 * and low order bit contains usec_ts enable bit. 4103 * Its a best effort, and we do not care if user makes an error. 4104 */ 4105 tp->tcp_usec_ts = val & 1; 4106 WRITE_ONCE(tp->tsoffset, val - tcp_clock_ts(tp->tcp_usec_ts)); 4107 break; 4108 case TCP_REPAIR_WINDOW: 4109 err = tcp_repair_set_window(tp, optval, optlen); 4110 break; 4111 case TCP_NOTSENT_LOWAT: 4112 WRITE_ONCE(tp->notsent_lowat, val); 4113 sk->sk_write_space(sk); 4114 break; 4115 case TCP_INQ: 4116 if (val > 1 || val < 0) 4117 err = -EINVAL; 4118 else 4119 tp->recvmsg_inq = val; 4120 break; 4121 case TCP_TX_DELAY: 4122 if (val) 4123 tcp_enable_tx_delay(); 4124 WRITE_ONCE(tp->tcp_tx_delay, val); 4125 break; 4126 default: 4127 err = -ENOPROTOOPT; 4128 break; 4129 } 4130 4131 sockopt_release_sock(sk); 4132 return err; 4133 } 4134 4135 int tcp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval, 4136 unsigned int optlen) 4137 { 4138 const struct inet_connection_sock *icsk = inet_csk(sk); 4139 4140 if (level != SOL_TCP) 4141 /* Paired with WRITE_ONCE() in do_ipv6_setsockopt() and tcp_v6_connect() */ 4142 return READ_ONCE(icsk->icsk_af_ops)->setsockopt(sk, level, optname, 4143 optval, optlen); 4144 return do_tcp_setsockopt(sk, level, optname, optval, optlen); 4145 } 4146 EXPORT_IPV6_MOD(tcp_setsockopt); 4147 4148 static void tcp_get_info_chrono_stats(const struct tcp_sock *tp, 4149 struct tcp_info *info) 4150 { 4151 u64 stats[__TCP_CHRONO_MAX], total = 0; 4152 enum tcp_chrono i; 4153 4154 for (i = TCP_CHRONO_BUSY; i < __TCP_CHRONO_MAX; ++i) { 4155 stats[i] = tp->chrono_stat[i - 1]; 4156 if (i == tp->chrono_type) 4157 stats[i] += tcp_jiffies32 - tp->chrono_start; 4158 stats[i] *= USEC_PER_SEC / HZ; 4159 total += stats[i]; 4160 } 4161 4162 info->tcpi_busy_time = total; 4163 info->tcpi_rwnd_limited = stats[TCP_CHRONO_RWND_LIMITED]; 4164 info->tcpi_sndbuf_limited = stats[TCP_CHRONO_SNDBUF_LIMITED]; 4165 } 4166 4167 /* Return information about state of tcp endpoint in API format. */ 4168 void tcp_get_info(struct sock *sk, struct tcp_info *info) 4169 { 4170 const struct tcp_sock *tp = tcp_sk(sk); /* iff sk_type == SOCK_STREAM */ 4171 const struct inet_connection_sock *icsk = inet_csk(sk); 4172 const u8 ect1_idx = INET_ECN_ECT_1 - 1; 4173 const u8 ect0_idx = INET_ECN_ECT_0 - 1; 4174 const u8 ce_idx = INET_ECN_CE - 1; 4175 unsigned long rate; 4176 u32 now; 4177 u64 rate64; 4178 bool slow; 4179 4180 memset(info, 0, sizeof(*info)); 4181 if (sk->sk_type != SOCK_STREAM) 4182 return; 4183 4184 info->tcpi_state = inet_sk_state_load(sk); 4185 4186 /* Report meaningful fields for all TCP states, including listeners */ 4187 rate = READ_ONCE(sk->sk_pacing_rate); 4188 rate64 = (rate != ~0UL) ? rate : ~0ULL; 4189 info->tcpi_pacing_rate = rate64; 4190 4191 rate = READ_ONCE(sk->sk_max_pacing_rate); 4192 rate64 = (rate != ~0UL) ? rate : ~0ULL; 4193 info->tcpi_max_pacing_rate = rate64; 4194 4195 info->tcpi_reordering = tp->reordering; 4196 info->tcpi_snd_cwnd = tcp_snd_cwnd(tp); 4197 4198 if (info->tcpi_state == TCP_LISTEN) { 4199 /* listeners aliased fields : 4200 * tcpi_unacked -> Number of children ready for accept() 4201 * tcpi_sacked -> max backlog 4202 */ 4203 info->tcpi_unacked = READ_ONCE(sk->sk_ack_backlog); 4204 info->tcpi_sacked = READ_ONCE(sk->sk_max_ack_backlog); 4205 return; 4206 } 4207 4208 slow = lock_sock_fast(sk); 4209 4210 info->tcpi_ca_state = icsk->icsk_ca_state; 4211 info->tcpi_retransmits = icsk->icsk_retransmits; 4212 info->tcpi_probes = icsk->icsk_probes_out; 4213 info->tcpi_backoff = icsk->icsk_backoff; 4214 4215 if (tp->rx_opt.tstamp_ok) 4216 info->tcpi_options |= TCPI_OPT_TIMESTAMPS; 4217 if (tcp_is_sack(tp)) 4218 info->tcpi_options |= TCPI_OPT_SACK; 4219 if (tp->rx_opt.wscale_ok) { 4220 info->tcpi_options |= TCPI_OPT_WSCALE; 4221 info->tcpi_snd_wscale = tp->rx_opt.snd_wscale; 4222 info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale; 4223 } 4224 4225 if (tcp_ecn_mode_any(tp)) 4226 info->tcpi_options |= TCPI_OPT_ECN; 4227 if (tp->ecn_flags & TCP_ECN_SEEN) 4228 info->tcpi_options |= TCPI_OPT_ECN_SEEN; 4229 if (tp->syn_data_acked) 4230 info->tcpi_options |= TCPI_OPT_SYN_DATA; 4231 if (tp->tcp_usec_ts) 4232 info->tcpi_options |= TCPI_OPT_USEC_TS; 4233 if (tp->syn_fastopen_child) 4234 info->tcpi_options |= TCPI_OPT_TFO_CHILD; 4235 4236 info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto); 4237 info->tcpi_ato = jiffies_to_usecs(min_t(u32, icsk->icsk_ack.ato, 4238 tcp_delack_max(sk))); 4239 info->tcpi_snd_mss = tp->mss_cache; 4240 info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss; 4241 4242 info->tcpi_unacked = tp->packets_out; 4243 info->tcpi_sacked = tp->sacked_out; 4244 4245 info->tcpi_lost = tp->lost_out; 4246 info->tcpi_retrans = tp->retrans_out; 4247 4248 now = tcp_jiffies32; 4249 info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime); 4250 info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime); 4251 info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp); 4252 4253 info->tcpi_pmtu = icsk->icsk_pmtu_cookie; 4254 info->tcpi_rcv_ssthresh = tp->rcv_ssthresh; 4255 info->tcpi_rtt = tp->srtt_us >> 3; 4256 info->tcpi_rttvar = tp->mdev_us >> 2; 4257 info->tcpi_snd_ssthresh = tp->snd_ssthresh; 4258 info->tcpi_advmss = tp->advmss; 4259 4260 info->tcpi_rcv_rtt = tp->rcv_rtt_est.rtt_us >> 3; 4261 info->tcpi_rcv_space = tp->rcvq_space.space; 4262 4263 info->tcpi_total_retrans = tp->total_retrans; 4264 4265 info->tcpi_bytes_acked = tp->bytes_acked; 4266 info->tcpi_bytes_received = tp->bytes_received; 4267 info->tcpi_notsent_bytes = max_t(int, 0, tp->write_seq - tp->snd_nxt); 4268 tcp_get_info_chrono_stats(tp, info); 4269 4270 info->tcpi_segs_out = tp->segs_out; 4271 4272 /* segs_in and data_segs_in can be updated from tcp_segs_in() from BH */ 4273 info->tcpi_segs_in = READ_ONCE(tp->segs_in); 4274 info->tcpi_data_segs_in = READ_ONCE(tp->data_segs_in); 4275 4276 info->tcpi_min_rtt = tcp_min_rtt(tp); 4277 info->tcpi_data_segs_out = tp->data_segs_out; 4278 4279 info->tcpi_delivery_rate_app_limited = tp->rate_app_limited ? 1 : 0; 4280 rate64 = tcp_compute_delivery_rate(tp); 4281 if (rate64) 4282 info->tcpi_delivery_rate = rate64; 4283 info->tcpi_delivered = tp->delivered; 4284 info->tcpi_delivered_ce = tp->delivered_ce; 4285 info->tcpi_bytes_sent = tp->bytes_sent; 4286 info->tcpi_bytes_retrans = tp->bytes_retrans; 4287 info->tcpi_dsack_dups = tp->dsack_dups; 4288 info->tcpi_reord_seen = tp->reord_seen; 4289 info->tcpi_rcv_ooopack = tp->rcv_ooopack; 4290 info->tcpi_snd_wnd = tp->snd_wnd; 4291 info->tcpi_rcv_wnd = tp->rcv_wnd; 4292 info->tcpi_rehash = tp->plb_rehash + tp->timeout_rehash; 4293 info->tcpi_fastopen_client_fail = tp->fastopen_client_fail; 4294 4295 info->tcpi_total_rto = tp->total_rto; 4296 info->tcpi_total_rto_recoveries = tp->total_rto_recoveries; 4297 info->tcpi_total_rto_time = tp->total_rto_time; 4298 if (tp->rto_stamp) 4299 info->tcpi_total_rto_time += tcp_clock_ms() - tp->rto_stamp; 4300 4301 info->tcpi_accecn_fail_mode = tp->accecn_fail_mode; 4302 info->tcpi_accecn_opt_seen = tp->saw_accecn_opt; 4303 info->tcpi_received_ce = tp->received_ce; 4304 info->tcpi_delivered_e1_bytes = tp->delivered_ecn_bytes[ect1_idx]; 4305 info->tcpi_delivered_e0_bytes = tp->delivered_ecn_bytes[ect0_idx]; 4306 info->tcpi_delivered_ce_bytes = tp->delivered_ecn_bytes[ce_idx]; 4307 info->tcpi_received_e1_bytes = tp->received_ecn_bytes[ect1_idx]; 4308 info->tcpi_received_e0_bytes = tp->received_ecn_bytes[ect0_idx]; 4309 info->tcpi_received_ce_bytes = tp->received_ecn_bytes[ce_idx]; 4310 4311 unlock_sock_fast(sk, slow); 4312 } 4313 EXPORT_SYMBOL_GPL(tcp_get_info); 4314 4315 static size_t tcp_opt_stats_get_size(void) 4316 { 4317 return 4318 nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BUSY */ 4319 nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_RWND_LIMITED */ 4320 nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_SNDBUF_LIMITED */ 4321 nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_DATA_SEGS_OUT */ 4322 nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_TOTAL_RETRANS */ 4323 nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_PACING_RATE */ 4324 nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_DELIVERY_RATE */ 4325 nla_total_size(sizeof(u32)) + /* TCP_NLA_SND_CWND */ 4326 nla_total_size(sizeof(u32)) + /* TCP_NLA_REORDERING */ 4327 nla_total_size(sizeof(u32)) + /* TCP_NLA_MIN_RTT */ 4328 nla_total_size(sizeof(u8)) + /* TCP_NLA_RECUR_RETRANS */ 4329 nla_total_size(sizeof(u8)) + /* TCP_NLA_DELIVERY_RATE_APP_LMT */ 4330 nla_total_size(sizeof(u32)) + /* TCP_NLA_SNDQ_SIZE */ 4331 nla_total_size(sizeof(u8)) + /* TCP_NLA_CA_STATE */ 4332 nla_total_size(sizeof(u32)) + /* TCP_NLA_SND_SSTHRESH */ 4333 nla_total_size(sizeof(u32)) + /* TCP_NLA_DELIVERED */ 4334 nla_total_size(sizeof(u32)) + /* TCP_NLA_DELIVERED_CE */ 4335 nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BYTES_SENT */ 4336 nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BYTES_RETRANS */ 4337 nla_total_size(sizeof(u32)) + /* TCP_NLA_DSACK_DUPS */ 4338 nla_total_size(sizeof(u32)) + /* TCP_NLA_REORD_SEEN */ 4339 nla_total_size(sizeof(u32)) + /* TCP_NLA_SRTT */ 4340 nla_total_size(sizeof(u16)) + /* TCP_NLA_TIMEOUT_REHASH */ 4341 nla_total_size(sizeof(u32)) + /* TCP_NLA_BYTES_NOTSENT */ 4342 nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_EDT */ 4343 nla_total_size(sizeof(u8)) + /* TCP_NLA_TTL */ 4344 nla_total_size(sizeof(u32)) + /* TCP_NLA_REHASH */ 4345 0; 4346 } 4347 4348 /* Returns TTL or hop limit of an incoming packet from skb. */ 4349 static u8 tcp_skb_ttl_or_hop_limit(const struct sk_buff *skb) 4350 { 4351 if (skb->protocol == htons(ETH_P_IP)) 4352 return ip_hdr(skb)->ttl; 4353 else if (skb->protocol == htons(ETH_P_IPV6)) 4354 return ipv6_hdr(skb)->hop_limit; 4355 else 4356 return 0; 4357 } 4358 4359 struct sk_buff *tcp_get_timestamping_opt_stats(const struct sock *sk, 4360 const struct sk_buff *orig_skb, 4361 const struct sk_buff *ack_skb) 4362 { 4363 const struct tcp_sock *tp = tcp_sk(sk); 4364 struct sk_buff *stats; 4365 struct tcp_info info; 4366 unsigned long rate; 4367 u64 rate64; 4368 4369 stats = alloc_skb(tcp_opt_stats_get_size(), GFP_ATOMIC); 4370 if (!stats) 4371 return NULL; 4372 4373 tcp_get_info_chrono_stats(tp, &info); 4374 nla_put_u64_64bit(stats, TCP_NLA_BUSY, 4375 info.tcpi_busy_time, TCP_NLA_PAD); 4376 nla_put_u64_64bit(stats, TCP_NLA_RWND_LIMITED, 4377 info.tcpi_rwnd_limited, TCP_NLA_PAD); 4378 nla_put_u64_64bit(stats, TCP_NLA_SNDBUF_LIMITED, 4379 info.tcpi_sndbuf_limited, TCP_NLA_PAD); 4380 nla_put_u64_64bit(stats, TCP_NLA_DATA_SEGS_OUT, 4381 tp->data_segs_out, TCP_NLA_PAD); 4382 nla_put_u64_64bit(stats, TCP_NLA_TOTAL_RETRANS, 4383 tp->total_retrans, TCP_NLA_PAD); 4384 4385 rate = READ_ONCE(sk->sk_pacing_rate); 4386 rate64 = (rate != ~0UL) ? rate : ~0ULL; 4387 nla_put_u64_64bit(stats, TCP_NLA_PACING_RATE, rate64, TCP_NLA_PAD); 4388 4389 rate64 = tcp_compute_delivery_rate(tp); 4390 nla_put_u64_64bit(stats, TCP_NLA_DELIVERY_RATE, rate64, TCP_NLA_PAD); 4391 4392 nla_put_u32(stats, TCP_NLA_SND_CWND, tcp_snd_cwnd(tp)); 4393 nla_put_u32(stats, TCP_NLA_REORDERING, tp->reordering); 4394 nla_put_u32(stats, TCP_NLA_MIN_RTT, tcp_min_rtt(tp)); 4395 4396 nla_put_u8(stats, TCP_NLA_RECUR_RETRANS, 4397 READ_ONCE(inet_csk(sk)->icsk_retransmits)); 4398 nla_put_u8(stats, TCP_NLA_DELIVERY_RATE_APP_LMT, !!tp->rate_app_limited); 4399 nla_put_u32(stats, TCP_NLA_SND_SSTHRESH, tp->snd_ssthresh); 4400 nla_put_u32(stats, TCP_NLA_DELIVERED, tp->delivered); 4401 nla_put_u32(stats, TCP_NLA_DELIVERED_CE, tp->delivered_ce); 4402 4403 nla_put_u32(stats, TCP_NLA_SNDQ_SIZE, tp->write_seq - tp->snd_una); 4404 nla_put_u8(stats, TCP_NLA_CA_STATE, inet_csk(sk)->icsk_ca_state); 4405 4406 nla_put_u64_64bit(stats, TCP_NLA_BYTES_SENT, tp->bytes_sent, 4407 TCP_NLA_PAD); 4408 nla_put_u64_64bit(stats, TCP_NLA_BYTES_RETRANS, tp->bytes_retrans, 4409 TCP_NLA_PAD); 4410 nla_put_u32(stats, TCP_NLA_DSACK_DUPS, tp->dsack_dups); 4411 nla_put_u32(stats, TCP_NLA_REORD_SEEN, tp->reord_seen); 4412 nla_put_u32(stats, TCP_NLA_SRTT, tp->srtt_us >> 3); 4413 nla_put_u16(stats, TCP_NLA_TIMEOUT_REHASH, tp->timeout_rehash); 4414 nla_put_u32(stats, TCP_NLA_BYTES_NOTSENT, 4415 max_t(int, 0, tp->write_seq - tp->snd_nxt)); 4416 nla_put_u64_64bit(stats, TCP_NLA_EDT, orig_skb->skb_mstamp_ns, 4417 TCP_NLA_PAD); 4418 if (ack_skb) 4419 nla_put_u8(stats, TCP_NLA_TTL, 4420 tcp_skb_ttl_or_hop_limit(ack_skb)); 4421 4422 nla_put_u32(stats, TCP_NLA_REHASH, tp->plb_rehash + tp->timeout_rehash); 4423 return stats; 4424 } 4425 4426 int do_tcp_getsockopt(struct sock *sk, int level, 4427 int optname, sockptr_t optval, sockptr_t optlen) 4428 { 4429 struct inet_connection_sock *icsk = inet_csk(sk); 4430 struct tcp_sock *tp = tcp_sk(sk); 4431 struct net *net = sock_net(sk); 4432 int user_mss; 4433 int val, len; 4434 4435 if (copy_from_sockptr(&len, optlen, sizeof(int))) 4436 return -EFAULT; 4437 4438 if (len < 0) 4439 return -EINVAL; 4440 4441 len = min_t(unsigned int, len, sizeof(int)); 4442 4443 switch (optname) { 4444 case TCP_MAXSEG: 4445 val = tp->mss_cache; 4446 user_mss = READ_ONCE(tp->rx_opt.user_mss); 4447 if (user_mss && 4448 ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) 4449 val = user_mss; 4450 if (tp->repair) 4451 val = tp->rx_opt.mss_clamp; 4452 break; 4453 case TCP_NODELAY: 4454 val = !!(tp->nonagle&TCP_NAGLE_OFF); 4455 break; 4456 case TCP_CORK: 4457 val = !!(tp->nonagle&TCP_NAGLE_CORK); 4458 break; 4459 case TCP_KEEPIDLE: 4460 val = keepalive_time_when(tp) / HZ; 4461 break; 4462 case TCP_KEEPINTVL: 4463 val = keepalive_intvl_when(tp) / HZ; 4464 break; 4465 case TCP_KEEPCNT: 4466 val = keepalive_probes(tp); 4467 break; 4468 case TCP_SYNCNT: 4469 val = READ_ONCE(icsk->icsk_syn_retries) ? : 4470 READ_ONCE(net->ipv4.sysctl_tcp_syn_retries); 4471 break; 4472 case TCP_LINGER2: 4473 val = READ_ONCE(tp->linger2); 4474 if (val >= 0) 4475 val = (val ? : READ_ONCE(net->ipv4.sysctl_tcp_fin_timeout)) / HZ; 4476 break; 4477 case TCP_DEFER_ACCEPT: 4478 val = READ_ONCE(icsk->icsk_accept_queue.rskq_defer_accept); 4479 val = retrans_to_secs(val, TCP_TIMEOUT_INIT / HZ, 4480 TCP_RTO_MAX / HZ); 4481 break; 4482 case TCP_WINDOW_CLAMP: 4483 val = READ_ONCE(tp->window_clamp); 4484 break; 4485 case TCP_INFO: { 4486 struct tcp_info info; 4487 4488 if (copy_from_sockptr(&len, optlen, sizeof(int))) 4489 return -EFAULT; 4490 4491 tcp_get_info(sk, &info); 4492 4493 len = min_t(unsigned int, len, sizeof(info)); 4494 if (copy_to_sockptr(optlen, &len, sizeof(int))) 4495 return -EFAULT; 4496 if (copy_to_sockptr(optval, &info, len)) 4497 return -EFAULT; 4498 return 0; 4499 } 4500 case TCP_CC_INFO: { 4501 const struct tcp_congestion_ops *ca_ops; 4502 union tcp_cc_info info; 4503 size_t sz = 0; 4504 int attr; 4505 4506 if (copy_from_sockptr(&len, optlen, sizeof(int))) 4507 return -EFAULT; 4508 4509 ca_ops = icsk->icsk_ca_ops; 4510 if (ca_ops && ca_ops->get_info) 4511 sz = ca_ops->get_info(sk, ~0U, &attr, &info); 4512 4513 len = min_t(unsigned int, len, sz); 4514 if (copy_to_sockptr(optlen, &len, sizeof(int))) 4515 return -EFAULT; 4516 if (copy_to_sockptr(optval, &info, len)) 4517 return -EFAULT; 4518 return 0; 4519 } 4520 case TCP_QUICKACK: 4521 val = !inet_csk_in_pingpong_mode(sk); 4522 break; 4523 4524 case TCP_CONGESTION: 4525 if (copy_from_sockptr(&len, optlen, sizeof(int))) 4526 return -EFAULT; 4527 len = min_t(unsigned int, len, TCP_CA_NAME_MAX); 4528 if (copy_to_sockptr(optlen, &len, sizeof(int))) 4529 return -EFAULT; 4530 if (copy_to_sockptr(optval, icsk->icsk_ca_ops->name, len)) 4531 return -EFAULT; 4532 return 0; 4533 4534 case TCP_ULP: 4535 if (copy_from_sockptr(&len, optlen, sizeof(int))) 4536 return -EFAULT; 4537 len = min_t(unsigned int, len, TCP_ULP_NAME_MAX); 4538 if (!icsk->icsk_ulp_ops) { 4539 len = 0; 4540 if (copy_to_sockptr(optlen, &len, sizeof(int))) 4541 return -EFAULT; 4542 return 0; 4543 } 4544 if (copy_to_sockptr(optlen, &len, sizeof(int))) 4545 return -EFAULT; 4546 if (copy_to_sockptr(optval, icsk->icsk_ulp_ops->name, len)) 4547 return -EFAULT; 4548 return 0; 4549 4550 case TCP_FASTOPEN_KEY: { 4551 u64 key[TCP_FASTOPEN_KEY_BUF_LENGTH / sizeof(u64)]; 4552 unsigned int key_len; 4553 4554 if (copy_from_sockptr(&len, optlen, sizeof(int))) 4555 return -EFAULT; 4556 4557 key_len = tcp_fastopen_get_cipher(net, icsk, key) * 4558 TCP_FASTOPEN_KEY_LENGTH; 4559 len = min_t(unsigned int, len, key_len); 4560 if (copy_to_sockptr(optlen, &len, sizeof(int))) 4561 return -EFAULT; 4562 if (copy_to_sockptr(optval, key, len)) 4563 return -EFAULT; 4564 return 0; 4565 } 4566 case TCP_THIN_LINEAR_TIMEOUTS: 4567 val = tp->thin_lto; 4568 break; 4569 4570 case TCP_THIN_DUPACK: 4571 val = 0; 4572 break; 4573 4574 case TCP_REPAIR: 4575 val = tp->repair; 4576 break; 4577 4578 case TCP_REPAIR_QUEUE: 4579 if (tp->repair) 4580 val = tp->repair_queue; 4581 else 4582 return -EINVAL; 4583 break; 4584 4585 case TCP_REPAIR_WINDOW: { 4586 struct tcp_repair_window opt; 4587 4588 if (copy_from_sockptr(&len, optlen, sizeof(int))) 4589 return -EFAULT; 4590 4591 if (len != sizeof(opt)) 4592 return -EINVAL; 4593 4594 if (!tp->repair) 4595 return -EPERM; 4596 4597 opt.snd_wl1 = tp->snd_wl1; 4598 opt.snd_wnd = tp->snd_wnd; 4599 opt.max_window = tp->max_window; 4600 opt.rcv_wnd = tp->rcv_wnd; 4601 opt.rcv_wup = tp->rcv_wup; 4602 4603 if (copy_to_sockptr(optval, &opt, len)) 4604 return -EFAULT; 4605 return 0; 4606 } 4607 case TCP_QUEUE_SEQ: 4608 if (tp->repair_queue == TCP_SEND_QUEUE) 4609 val = tp->write_seq; 4610 else if (tp->repair_queue == TCP_RECV_QUEUE) 4611 val = tp->rcv_nxt; 4612 else 4613 return -EINVAL; 4614 break; 4615 4616 case TCP_USER_TIMEOUT: 4617 val = READ_ONCE(icsk->icsk_user_timeout); 4618 break; 4619 4620 case TCP_FASTOPEN: 4621 val = READ_ONCE(icsk->icsk_accept_queue.fastopenq.max_qlen); 4622 break; 4623 4624 case TCP_FASTOPEN_CONNECT: 4625 val = tp->fastopen_connect; 4626 break; 4627 4628 case TCP_FASTOPEN_NO_COOKIE: 4629 val = tp->fastopen_no_cookie; 4630 break; 4631 4632 case TCP_TX_DELAY: 4633 val = READ_ONCE(tp->tcp_tx_delay); 4634 break; 4635 4636 case TCP_TIMESTAMP: 4637 val = tcp_clock_ts(tp->tcp_usec_ts) + READ_ONCE(tp->tsoffset); 4638 if (tp->tcp_usec_ts) 4639 val |= 1; 4640 else 4641 val &= ~1; 4642 break; 4643 case TCP_NOTSENT_LOWAT: 4644 val = READ_ONCE(tp->notsent_lowat); 4645 break; 4646 case TCP_INQ: 4647 val = tp->recvmsg_inq; 4648 break; 4649 case TCP_SAVE_SYN: 4650 val = tp->save_syn; 4651 break; 4652 case TCP_SAVED_SYN: { 4653 if (copy_from_sockptr(&len, optlen, sizeof(int))) 4654 return -EFAULT; 4655 4656 sockopt_lock_sock(sk); 4657 if (tp->saved_syn) { 4658 if (len < tcp_saved_syn_len(tp->saved_syn)) { 4659 len = tcp_saved_syn_len(tp->saved_syn); 4660 if (copy_to_sockptr(optlen, &len, sizeof(int))) { 4661 sockopt_release_sock(sk); 4662 return -EFAULT; 4663 } 4664 sockopt_release_sock(sk); 4665 return -EINVAL; 4666 } 4667 len = tcp_saved_syn_len(tp->saved_syn); 4668 if (copy_to_sockptr(optlen, &len, sizeof(int))) { 4669 sockopt_release_sock(sk); 4670 return -EFAULT; 4671 } 4672 if (copy_to_sockptr(optval, tp->saved_syn->data, len)) { 4673 sockopt_release_sock(sk); 4674 return -EFAULT; 4675 } 4676 tcp_saved_syn_free(tp); 4677 sockopt_release_sock(sk); 4678 } else { 4679 sockopt_release_sock(sk); 4680 len = 0; 4681 if (copy_to_sockptr(optlen, &len, sizeof(int))) 4682 return -EFAULT; 4683 } 4684 return 0; 4685 } 4686 #ifdef CONFIG_MMU 4687 case TCP_ZEROCOPY_RECEIVE: { 4688 struct scm_timestamping_internal tss; 4689 struct tcp_zerocopy_receive zc = {}; 4690 int err; 4691 4692 if (copy_from_sockptr(&len, optlen, sizeof(int))) 4693 return -EFAULT; 4694 if (len < 0 || 4695 len < offsetofend(struct tcp_zerocopy_receive, length)) 4696 return -EINVAL; 4697 if (unlikely(len > sizeof(zc))) { 4698 err = check_zeroed_sockptr(optval, sizeof(zc), 4699 len - sizeof(zc)); 4700 if (err < 1) 4701 return err == 0 ? -EINVAL : err; 4702 len = sizeof(zc); 4703 if (copy_to_sockptr(optlen, &len, sizeof(int))) 4704 return -EFAULT; 4705 } 4706 if (copy_from_sockptr(&zc, optval, len)) 4707 return -EFAULT; 4708 if (zc.reserved) 4709 return -EINVAL; 4710 if (zc.msg_flags & ~(TCP_VALID_ZC_MSG_FLAGS)) 4711 return -EINVAL; 4712 sockopt_lock_sock(sk); 4713 err = tcp_zerocopy_receive(sk, &zc, &tss); 4714 err = BPF_CGROUP_RUN_PROG_GETSOCKOPT_KERN(sk, level, optname, 4715 &zc, &len, err); 4716 sockopt_release_sock(sk); 4717 if (len >= offsetofend(struct tcp_zerocopy_receive, msg_flags)) 4718 goto zerocopy_rcv_cmsg; 4719 switch (len) { 4720 case offsetofend(struct tcp_zerocopy_receive, msg_flags): 4721 goto zerocopy_rcv_cmsg; 4722 case offsetofend(struct tcp_zerocopy_receive, msg_controllen): 4723 case offsetofend(struct tcp_zerocopy_receive, msg_control): 4724 case offsetofend(struct tcp_zerocopy_receive, flags): 4725 case offsetofend(struct tcp_zerocopy_receive, copybuf_len): 4726 case offsetofend(struct tcp_zerocopy_receive, copybuf_address): 4727 case offsetofend(struct tcp_zerocopy_receive, err): 4728 goto zerocopy_rcv_sk_err; 4729 case offsetofend(struct tcp_zerocopy_receive, inq): 4730 goto zerocopy_rcv_inq; 4731 case offsetofend(struct tcp_zerocopy_receive, length): 4732 default: 4733 goto zerocopy_rcv_out; 4734 } 4735 zerocopy_rcv_cmsg: 4736 if (zc.msg_flags & TCP_CMSG_TS) 4737 tcp_zc_finalize_rx_tstamp(sk, &zc, &tss); 4738 else 4739 zc.msg_flags = 0; 4740 zerocopy_rcv_sk_err: 4741 if (!err) 4742 zc.err = sock_error(sk); 4743 zerocopy_rcv_inq: 4744 zc.inq = tcp_inq_hint(sk); 4745 zerocopy_rcv_out: 4746 if (!err && copy_to_sockptr(optval, &zc, len)) 4747 err = -EFAULT; 4748 return err; 4749 } 4750 #endif 4751 case TCP_AO_REPAIR: 4752 if (!tcp_can_repair_sock(sk)) 4753 return -EPERM; 4754 return tcp_ao_get_repair(sk, optval, optlen); 4755 case TCP_AO_GET_KEYS: 4756 case TCP_AO_INFO: { 4757 int err; 4758 4759 sockopt_lock_sock(sk); 4760 if (optname == TCP_AO_GET_KEYS) 4761 err = tcp_ao_get_mkts(sk, optval, optlen); 4762 else 4763 err = tcp_ao_get_sock_info(sk, optval, optlen); 4764 sockopt_release_sock(sk); 4765 4766 return err; 4767 } 4768 case TCP_IS_MPTCP: 4769 val = 0; 4770 break; 4771 case TCP_RTO_MAX_MS: 4772 val = jiffies_to_msecs(tcp_rto_max(sk)); 4773 break; 4774 case TCP_RTO_MIN_US: 4775 val = jiffies_to_usecs(READ_ONCE(inet_csk(sk)->icsk_rto_min)); 4776 break; 4777 case TCP_DELACK_MAX_US: 4778 val = jiffies_to_usecs(READ_ONCE(inet_csk(sk)->icsk_delack_max)); 4779 break; 4780 default: 4781 return -ENOPROTOOPT; 4782 } 4783 4784 if (copy_to_sockptr(optlen, &len, sizeof(int))) 4785 return -EFAULT; 4786 if (copy_to_sockptr(optval, &val, len)) 4787 return -EFAULT; 4788 return 0; 4789 } 4790 4791 bool tcp_bpf_bypass_getsockopt(int level, int optname) 4792 { 4793 /* TCP do_tcp_getsockopt has optimized getsockopt implementation 4794 * to avoid extra socket lock for TCP_ZEROCOPY_RECEIVE. 4795 */ 4796 if (level == SOL_TCP && optname == TCP_ZEROCOPY_RECEIVE) 4797 return true; 4798 4799 return false; 4800 } 4801 EXPORT_IPV6_MOD(tcp_bpf_bypass_getsockopt); 4802 4803 int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, 4804 int __user *optlen) 4805 { 4806 struct inet_connection_sock *icsk = inet_csk(sk); 4807 4808 if (level != SOL_TCP) 4809 /* Paired with WRITE_ONCE() in do_ipv6_setsockopt() and tcp_v6_connect() */ 4810 return READ_ONCE(icsk->icsk_af_ops)->getsockopt(sk, level, optname, 4811 optval, optlen); 4812 return do_tcp_getsockopt(sk, level, optname, USER_SOCKPTR(optval), 4813 USER_SOCKPTR(optlen)); 4814 } 4815 EXPORT_IPV6_MOD(tcp_getsockopt); 4816 4817 #ifdef CONFIG_TCP_MD5SIG 4818 int tcp_md5_sigpool_id = -1; 4819 EXPORT_IPV6_MOD_GPL(tcp_md5_sigpool_id); 4820 4821 int tcp_md5_alloc_sigpool(void) 4822 { 4823 size_t scratch_size; 4824 int ret; 4825 4826 scratch_size = sizeof(union tcp_md5sum_block) + sizeof(struct tcphdr); 4827 ret = tcp_sigpool_alloc_ahash("md5", scratch_size); 4828 if (ret >= 0) { 4829 /* As long as any md5 sigpool was allocated, the return 4830 * id would stay the same. Re-write the id only for the case 4831 * when previously all MD5 keys were deleted and this call 4832 * allocates the first MD5 key, which may return a different 4833 * sigpool id than was used previously. 4834 */ 4835 WRITE_ONCE(tcp_md5_sigpool_id, ret); /* Avoids the compiler potentially being smart here */ 4836 return 0; 4837 } 4838 return ret; 4839 } 4840 4841 void tcp_md5_release_sigpool(void) 4842 { 4843 tcp_sigpool_release(READ_ONCE(tcp_md5_sigpool_id)); 4844 } 4845 4846 void tcp_md5_add_sigpool(void) 4847 { 4848 tcp_sigpool_get(READ_ONCE(tcp_md5_sigpool_id)); 4849 } 4850 4851 int tcp_md5_hash_key(struct tcp_sigpool *hp, 4852 const struct tcp_md5sig_key *key) 4853 { 4854 u8 keylen = READ_ONCE(key->keylen); /* paired with WRITE_ONCE() in tcp_md5_do_add */ 4855 struct scatterlist sg; 4856 4857 sg_init_one(&sg, key->key, keylen); 4858 ahash_request_set_crypt(hp->req, &sg, NULL, keylen); 4859 4860 /* We use data_race() because tcp_md5_do_add() might change 4861 * key->key under us 4862 */ 4863 return data_race(crypto_ahash_update(hp->req)); 4864 } 4865 EXPORT_IPV6_MOD(tcp_md5_hash_key); 4866 4867 /* Called with rcu_read_lock() */ 4868 static enum skb_drop_reason 4869 tcp_inbound_md5_hash(const struct sock *sk, const struct sk_buff *skb, 4870 const void *saddr, const void *daddr, 4871 int family, int l3index, const __u8 *hash_location) 4872 { 4873 /* This gets called for each TCP segment that has TCP-MD5 option. 4874 * We have 3 drop cases: 4875 * o No MD5 hash and one expected. 4876 * o MD5 hash and we're not expecting one. 4877 * o MD5 hash and its wrong. 4878 */ 4879 const struct tcp_sock *tp = tcp_sk(sk); 4880 struct tcp_md5sig_key *key; 4881 u8 newhash[16]; 4882 int genhash; 4883 4884 key = tcp_md5_do_lookup(sk, l3index, saddr, family); 4885 4886 if (!key && hash_location) { 4887 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5UNEXPECTED); 4888 trace_tcp_hash_md5_unexpected(sk, skb); 4889 return SKB_DROP_REASON_TCP_MD5UNEXPECTED; 4890 } 4891 4892 /* Check the signature. 4893 * To support dual stack listeners, we need to handle 4894 * IPv4-mapped case. 4895 */ 4896 if (family == AF_INET) 4897 genhash = tcp_v4_md5_hash_skb(newhash, key, NULL, skb); 4898 else 4899 genhash = tp->af_specific->calc_md5_hash(newhash, key, 4900 NULL, skb); 4901 if (genhash || memcmp(hash_location, newhash, 16) != 0) { 4902 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5FAILURE); 4903 trace_tcp_hash_md5_mismatch(sk, skb); 4904 return SKB_DROP_REASON_TCP_MD5FAILURE; 4905 } 4906 return SKB_NOT_DROPPED_YET; 4907 } 4908 #else 4909 static inline enum skb_drop_reason 4910 tcp_inbound_md5_hash(const struct sock *sk, const struct sk_buff *skb, 4911 const void *saddr, const void *daddr, 4912 int family, int l3index, const __u8 *hash_location) 4913 { 4914 return SKB_NOT_DROPPED_YET; 4915 } 4916 4917 #endif 4918 4919 /* Called with rcu_read_lock() */ 4920 enum skb_drop_reason 4921 tcp_inbound_hash(struct sock *sk, const struct request_sock *req, 4922 const struct sk_buff *skb, 4923 const void *saddr, const void *daddr, 4924 int family, int dif, int sdif) 4925 { 4926 const struct tcphdr *th = tcp_hdr(skb); 4927 const struct tcp_ao_hdr *aoh; 4928 const __u8 *md5_location; 4929 int l3index; 4930 4931 /* Invalid option or two times meet any of auth options */ 4932 if (tcp_parse_auth_options(th, &md5_location, &aoh)) { 4933 trace_tcp_hash_bad_header(sk, skb); 4934 return SKB_DROP_REASON_TCP_AUTH_HDR; 4935 } 4936 4937 if (req) { 4938 if (tcp_rsk_used_ao(req) != !!aoh) { 4939 u8 keyid, rnext, maclen; 4940 4941 if (aoh) { 4942 keyid = aoh->keyid; 4943 rnext = aoh->rnext_keyid; 4944 maclen = tcp_ao_hdr_maclen(aoh); 4945 } else { 4946 keyid = rnext = maclen = 0; 4947 } 4948 4949 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAOBAD); 4950 trace_tcp_ao_handshake_failure(sk, skb, keyid, rnext, maclen); 4951 return SKB_DROP_REASON_TCP_AOFAILURE; 4952 } 4953 } 4954 4955 /* sdif set, means packet ingressed via a device 4956 * in an L3 domain and dif is set to the l3mdev 4957 */ 4958 l3index = sdif ? dif : 0; 4959 4960 /* Fast path: unsigned segments */ 4961 if (likely(!md5_location && !aoh)) { 4962 /* Drop if there's TCP-MD5 or TCP-AO key with any rcvid/sndid 4963 * for the remote peer. On TCP-AO established connection 4964 * the last key is impossible to remove, so there's 4965 * always at least one current_key. 4966 */ 4967 if (tcp_ao_required(sk, saddr, family, l3index, true)) { 4968 trace_tcp_hash_ao_required(sk, skb); 4969 return SKB_DROP_REASON_TCP_AONOTFOUND; 4970 } 4971 if (unlikely(tcp_md5_do_lookup(sk, l3index, saddr, family))) { 4972 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5NOTFOUND); 4973 trace_tcp_hash_md5_required(sk, skb); 4974 return SKB_DROP_REASON_TCP_MD5NOTFOUND; 4975 } 4976 return SKB_NOT_DROPPED_YET; 4977 } 4978 4979 if (aoh) 4980 return tcp_inbound_ao_hash(sk, skb, family, req, l3index, aoh); 4981 4982 return tcp_inbound_md5_hash(sk, skb, saddr, daddr, family, 4983 l3index, md5_location); 4984 } 4985 EXPORT_IPV6_MOD_GPL(tcp_inbound_hash); 4986 4987 void tcp_done(struct sock *sk) 4988 { 4989 struct request_sock *req; 4990 4991 /* We might be called with a new socket, after 4992 * inet_csk_prepare_forced_close() has been called 4993 * so we can not use lockdep_sock_is_held(sk) 4994 */ 4995 req = rcu_dereference_protected(tcp_sk(sk)->fastopen_rsk, 1); 4996 4997 if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV) 4998 TCP_INC_STATS(sock_net(sk), TCP_MIB_ATTEMPTFAILS); 4999 5000 tcp_set_state(sk, TCP_CLOSE); 5001 tcp_clear_xmit_timers(sk); 5002 if (req) 5003 reqsk_fastopen_remove(sk, req, false); 5004 5005 WRITE_ONCE(sk->sk_shutdown, SHUTDOWN_MASK); 5006 5007 if (!sock_flag(sk, SOCK_DEAD)) 5008 sk->sk_state_change(sk); 5009 else 5010 inet_csk_destroy_sock(sk); 5011 } 5012 EXPORT_SYMBOL_GPL(tcp_done); 5013 5014 int tcp_abort(struct sock *sk, int err) 5015 { 5016 int state = inet_sk_state_load(sk); 5017 5018 if (state == TCP_NEW_SYN_RECV) { 5019 struct request_sock *req = inet_reqsk(sk); 5020 5021 local_bh_disable(); 5022 inet_csk_reqsk_queue_drop(req->rsk_listener, req); 5023 local_bh_enable(); 5024 return 0; 5025 } 5026 if (state == TCP_TIME_WAIT) { 5027 struct inet_timewait_sock *tw = inet_twsk(sk); 5028 5029 refcount_inc(&tw->tw_refcnt); 5030 local_bh_disable(); 5031 inet_twsk_deschedule_put(tw); 5032 local_bh_enable(); 5033 return 0; 5034 } 5035 5036 /* BPF context ensures sock locking. */ 5037 if (!has_current_bpf_ctx()) 5038 /* Don't race with userspace socket closes such as tcp_close. */ 5039 lock_sock(sk); 5040 5041 /* Avoid closing the same socket twice. */ 5042 if (sk->sk_state == TCP_CLOSE) { 5043 if (!has_current_bpf_ctx()) 5044 release_sock(sk); 5045 return -ENOENT; 5046 } 5047 5048 if (sk->sk_state == TCP_LISTEN) { 5049 tcp_set_state(sk, TCP_CLOSE); 5050 inet_csk_listen_stop(sk); 5051 } 5052 5053 /* Don't race with BH socket closes such as inet_csk_listen_stop. */ 5054 local_bh_disable(); 5055 bh_lock_sock(sk); 5056 5057 if (tcp_need_reset(sk->sk_state)) 5058 tcp_send_active_reset(sk, GFP_ATOMIC, 5059 SK_RST_REASON_TCP_STATE); 5060 tcp_done_with_error(sk, err); 5061 5062 bh_unlock_sock(sk); 5063 local_bh_enable(); 5064 if (!has_current_bpf_ctx()) 5065 release_sock(sk); 5066 return 0; 5067 } 5068 EXPORT_SYMBOL_GPL(tcp_abort); 5069 5070 extern struct tcp_congestion_ops tcp_reno; 5071 5072 static __initdata unsigned long thash_entries; 5073 static int __init set_thash_entries(char *str) 5074 { 5075 ssize_t ret; 5076 5077 if (!str) 5078 return 0; 5079 5080 ret = kstrtoul(str, 0, &thash_entries); 5081 if (ret) 5082 return 0; 5083 5084 return 1; 5085 } 5086 __setup("thash_entries=", set_thash_entries); 5087 5088 static void __init tcp_init_mem(void) 5089 { 5090 unsigned long limit = nr_free_buffer_pages() / 16; 5091 5092 limit = max(limit, 128UL); 5093 sysctl_tcp_mem[0] = limit / 4 * 3; /* 4.68 % */ 5094 sysctl_tcp_mem[1] = limit; /* 6.25 % */ 5095 sysctl_tcp_mem[2] = sysctl_tcp_mem[0] * 2; /* 9.37 % */ 5096 } 5097 5098 static void __init tcp_struct_check(void) 5099 { 5100 /* TX read-mostly hotpath cache lines */ 5101 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_tx, max_window); 5102 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_tx, rcv_ssthresh); 5103 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_tx, reordering); 5104 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_tx, notsent_lowat); 5105 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_tx, gso_segs); 5106 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_tx, retransmit_skb_hint); 5107 #if IS_ENABLED(CONFIG_TLS_DEVICE) 5108 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_tx, tcp_clean_acked); 5109 #endif 5110 5111 /* TXRX read-mostly hotpath cache lines */ 5112 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, tsoffset); 5113 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, snd_wnd); 5114 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, mss_cache); 5115 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, snd_cwnd); 5116 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, prr_out); 5117 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, lost_out); 5118 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, sacked_out); 5119 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_txrx, scaling_ratio); 5120 5121 /* RX read-mostly hotpath cache lines */ 5122 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, copied_seq); 5123 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, snd_wl1); 5124 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, tlp_high_seq); 5125 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, rttvar_us); 5126 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, retrans_out); 5127 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, advmss); 5128 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, urg_data); 5129 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, lost); 5130 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, rtt_min); 5131 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, out_of_order_queue); 5132 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, snd_ssthresh); 5133 5134 /* TX read-write hotpath cache lines */ 5135 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, segs_out); 5136 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, data_segs_out); 5137 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, bytes_sent); 5138 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, snd_sml); 5139 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, chrono_start); 5140 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, chrono_stat); 5141 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, write_seq); 5142 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, pushed_seq); 5143 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, lsndtime); 5144 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, mdev_us); 5145 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, tcp_wstamp_ns); 5146 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, accecn_opt_tstamp); 5147 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, rtt_seq); 5148 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, tsorted_sent_queue); 5149 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, highest_sack); 5150 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, ecn_flags); 5151 5152 /* TXRX read-write hotpath cache lines */ 5153 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, pred_flags); 5154 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, tcp_clock_cache); 5155 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, tcp_mstamp); 5156 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, rcv_nxt); 5157 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, snd_nxt); 5158 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, snd_una); 5159 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, window_clamp); 5160 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, srtt_us); 5161 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, packets_out); 5162 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, snd_up); 5163 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, delivered); 5164 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, delivered_ce); 5165 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, received_ce); 5166 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, received_ecn_bytes); 5167 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, app_limited); 5168 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, rcv_wnd); 5169 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, rcv_tstamp); 5170 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, rx_opt); 5171 5172 /* RX read-write hotpath cache lines */ 5173 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, bytes_received); 5174 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, segs_in); 5175 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, data_segs_in); 5176 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcv_wup); 5177 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, max_packets_out); 5178 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, cwnd_usage_seq); 5179 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rate_delivered); 5180 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rate_interval_us); 5181 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcv_rtt_last_tsecr); 5182 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, delivered_ecn_bytes); 5183 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, first_tx_mstamp); 5184 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, delivered_mstamp); 5185 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, bytes_acked); 5186 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcv_rtt_est); 5187 CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcvq_space); 5188 } 5189 5190 void __init tcp_init(void) 5191 { 5192 int max_rshare, max_wshare, cnt; 5193 unsigned long limit; 5194 unsigned int i; 5195 5196 BUILD_BUG_ON(TCP_MIN_SND_MSS <= MAX_TCP_OPTION_SPACE); 5197 BUILD_BUG_ON(sizeof(struct tcp_skb_cb) > 5198 sizeof_field(struct sk_buff, cb)); 5199 5200 tcp_struct_check(); 5201 5202 percpu_counter_init(&tcp_sockets_allocated, 0, GFP_KERNEL); 5203 5204 timer_setup(&tcp_orphan_timer, tcp_orphan_update, TIMER_DEFERRABLE); 5205 mod_timer(&tcp_orphan_timer, jiffies + TCP_ORPHAN_TIMER_PERIOD); 5206 5207 inet_hashinfo2_init(&tcp_hashinfo, "tcp_listen_portaddr_hash", 5208 thash_entries, 21, /* one slot per 2 MB*/ 5209 0, 64 * 1024); 5210 tcp_hashinfo.bind_bucket_cachep = 5211 kmem_cache_create("tcp_bind_bucket", 5212 sizeof(struct inet_bind_bucket), 0, 5213 SLAB_HWCACHE_ALIGN | SLAB_PANIC | 5214 SLAB_ACCOUNT, 5215 NULL); 5216 tcp_hashinfo.bind2_bucket_cachep = 5217 kmem_cache_create("tcp_bind2_bucket", 5218 sizeof(struct inet_bind2_bucket), 0, 5219 SLAB_HWCACHE_ALIGN | SLAB_PANIC | 5220 SLAB_ACCOUNT, 5221 NULL); 5222 5223 /* Size and allocate the main established and bind bucket 5224 * hash tables. 5225 * 5226 * The methodology is similar to that of the buffer cache. 5227 */ 5228 tcp_hashinfo.ehash = 5229 alloc_large_system_hash("TCP established", 5230 sizeof(struct inet_ehash_bucket), 5231 thash_entries, 5232 17, /* one slot per 128 KB of memory */ 5233 0, 5234 NULL, 5235 &tcp_hashinfo.ehash_mask, 5236 0, 5237 thash_entries ? 0 : 512 * 1024); 5238 for (i = 0; i <= tcp_hashinfo.ehash_mask; i++) 5239 INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i); 5240 5241 if (inet_ehash_locks_alloc(&tcp_hashinfo)) 5242 panic("TCP: failed to alloc ehash_locks"); 5243 tcp_hashinfo.bhash = 5244 alloc_large_system_hash("TCP bind", 5245 2 * sizeof(struct inet_bind_hashbucket), 5246 tcp_hashinfo.ehash_mask + 1, 5247 17, /* one slot per 128 KB of memory */ 5248 0, 5249 &tcp_hashinfo.bhash_size, 5250 NULL, 5251 0, 5252 64 * 1024); 5253 tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size; 5254 tcp_hashinfo.bhash2 = tcp_hashinfo.bhash + tcp_hashinfo.bhash_size; 5255 for (i = 0; i < tcp_hashinfo.bhash_size; i++) { 5256 spin_lock_init(&tcp_hashinfo.bhash[i].lock); 5257 INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain); 5258 spin_lock_init(&tcp_hashinfo.bhash2[i].lock); 5259 INIT_HLIST_HEAD(&tcp_hashinfo.bhash2[i].chain); 5260 } 5261 5262 tcp_hashinfo.pernet = false; 5263 5264 cnt = tcp_hashinfo.ehash_mask + 1; 5265 sysctl_tcp_max_orphans = cnt / 2; 5266 5267 tcp_init_mem(); 5268 /* Set per-socket limits to no more than 1/128 the pressure threshold */ 5269 limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7); 5270 max_wshare = min(4UL*1024*1024, limit); 5271 max_rshare = min(32UL*1024*1024, limit); 5272 5273 init_net.ipv4.sysctl_tcp_wmem[0] = PAGE_SIZE; 5274 init_net.ipv4.sysctl_tcp_wmem[1] = 16*1024; 5275 init_net.ipv4.sysctl_tcp_wmem[2] = max(64*1024, max_wshare); 5276 5277 init_net.ipv4.sysctl_tcp_rmem[0] = PAGE_SIZE; 5278 init_net.ipv4.sysctl_tcp_rmem[1] = 131072; 5279 init_net.ipv4.sysctl_tcp_rmem[2] = max(131072, max_rshare); 5280 5281 pr_info("Hash tables configured (established %u bind %u)\n", 5282 tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size); 5283 5284 tcp_v4_init(); 5285 tcp_metrics_init(); 5286 BUG_ON(tcp_register_congestion_control(&tcp_reno) != 0); 5287 tcp_tsq_work_init(); 5288 mptcp_init(); 5289 } 5290