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