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