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