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