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