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