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