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