xref: /linux/net/ipv4/tcp.c (revision e9d9da91548b21e189fcd0259a0f2d26d1afc509)
12874c5fdSThomas Gleixner // SPDX-License-Identifier: GPL-2.0-or-later
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  * INET		An implementation of the TCP/IP protocol suite for the LINUX
41da177e4SLinus Torvalds  *		operating system.  INET is implemented using the  BSD Socket
51da177e4SLinus Torvalds  *		interface as the means of communication with the user level.
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  *		Implementation of the Transmission Control Protocol(TCP).
81da177e4SLinus Torvalds  *
902c30a84SJesper Juhl  * Authors:	Ross Biro
101da177e4SLinus Torvalds  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
111da177e4SLinus Torvalds  *		Mark Evans, <evansmp@uhura.aston.ac.uk>
121da177e4SLinus Torvalds  *		Corey Minyard <wf-rch!minyard@relay.EU.net>
131da177e4SLinus Torvalds  *		Florian La Roche, <flla@stud.uni-sb.de>
141da177e4SLinus Torvalds  *		Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
151da177e4SLinus Torvalds  *		Linus Torvalds, <torvalds@cs.helsinki.fi>
161da177e4SLinus Torvalds  *		Alan Cox, <gw4pts@gw4pts.ampr.org>
171da177e4SLinus Torvalds  *		Matthew Dillon, <dillon@apollo.west.oic.com>
181da177e4SLinus Torvalds  *		Arnt Gulbrandsen, <agulbra@nvg.unit.no>
191da177e4SLinus Torvalds  *		Jorge Cwik, <jorge@laser.satlink.net>
201da177e4SLinus Torvalds  *
211da177e4SLinus Torvalds  * Fixes:
221da177e4SLinus Torvalds  *		Alan Cox	:	Numerous verify_area() calls
231da177e4SLinus Torvalds  *		Alan Cox	:	Set the ACK bit on a reset
241da177e4SLinus Torvalds  *		Alan Cox	:	Stopped it crashing if it closed while
251da177e4SLinus Torvalds  *					sk->inuse=1 and was trying to connect
261da177e4SLinus Torvalds  *					(tcp_err()).
271da177e4SLinus Torvalds  *		Alan Cox	:	All icmp error handling was broken
281da177e4SLinus Torvalds  *					pointers passed where wrong and the
291da177e4SLinus Torvalds  *					socket was looked up backwards. Nobody
301da177e4SLinus Torvalds  *					tested any icmp error code obviously.
311da177e4SLinus Torvalds  *		Alan Cox	:	tcp_err() now handled properly. It
321da177e4SLinus Torvalds  *					wakes people on errors. poll
331da177e4SLinus Torvalds  *					behaves and the icmp error race
341da177e4SLinus Torvalds  *					has gone by moving it into sock.c
351da177e4SLinus Torvalds  *		Alan Cox	:	tcp_send_reset() fixed to work for
361da177e4SLinus Torvalds  *					everything not just packets for
371da177e4SLinus Torvalds  *					unknown sockets.
381da177e4SLinus Torvalds  *		Alan Cox	:	tcp option processing.
391da177e4SLinus Torvalds  *		Alan Cox	:	Reset tweaked (still not 100%) [Had
401da177e4SLinus Torvalds  *					syn rule wrong]
411da177e4SLinus Torvalds  *		Herp Rosmanith  :	More reset fixes
421da177e4SLinus Torvalds  *		Alan Cox	:	No longer acks invalid rst frames.
431da177e4SLinus Torvalds  *					Acking any kind of RST is right out.
441da177e4SLinus Torvalds  *		Alan Cox	:	Sets an ignore me flag on an rst
451da177e4SLinus Torvalds  *					receive otherwise odd bits of prattle
461da177e4SLinus Torvalds  *					escape still
471da177e4SLinus Torvalds  *		Alan Cox	:	Fixed another acking RST frame bug.
481da177e4SLinus Torvalds  *					Should stop LAN workplace lockups.
491da177e4SLinus Torvalds  *		Alan Cox	: 	Some tidyups using the new skb list
501da177e4SLinus Torvalds  *					facilities
511da177e4SLinus Torvalds  *		Alan Cox	:	sk->keepopen now seems to work
521da177e4SLinus Torvalds  *		Alan Cox	:	Pulls options out correctly on accepts
531da177e4SLinus Torvalds  *		Alan Cox	:	Fixed assorted sk->rqueue->next errors
541da177e4SLinus Torvalds  *		Alan Cox	:	PSH doesn't end a TCP read. Switched a
551da177e4SLinus Torvalds  *					bit to skb ops.
561da177e4SLinus Torvalds  *		Alan Cox	:	Tidied tcp_data to avoid a potential
571da177e4SLinus Torvalds  *					nasty.
581da177e4SLinus Torvalds  *		Alan Cox	:	Added some better commenting, as the
591da177e4SLinus Torvalds  *					tcp is hard to follow
601da177e4SLinus Torvalds  *		Alan Cox	:	Removed incorrect check for 20 * psh
611da177e4SLinus Torvalds  *	Michael O'Reilly	:	ack < copied bug fix.
621da177e4SLinus Torvalds  *	Johannes Stille		:	Misc tcp fixes (not all in yet).
631da177e4SLinus Torvalds  *		Alan Cox	:	FIN with no memory -> CRASH
641da177e4SLinus Torvalds  *		Alan Cox	:	Added socket option proto entries.
651da177e4SLinus Torvalds  *					Also added awareness of them to accept.
661da177e4SLinus Torvalds  *		Alan Cox	:	Added TCP options (SOL_TCP)
671da177e4SLinus Torvalds  *		Alan Cox	:	Switched wakeup calls to callbacks,
681da177e4SLinus Torvalds  *					so the kernel can layer network
691da177e4SLinus Torvalds  *					sockets.
701da177e4SLinus Torvalds  *		Alan Cox	:	Use ip_tos/ip_ttl settings.
711da177e4SLinus Torvalds  *		Alan Cox	:	Handle FIN (more) properly (we hope).
721da177e4SLinus Torvalds  *		Alan Cox	:	RST frames sent on unsynchronised
731da177e4SLinus Torvalds  *					state ack error.
741da177e4SLinus Torvalds  *		Alan Cox	:	Put in missing check for SYN bit.
751da177e4SLinus Torvalds  *		Alan Cox	:	Added tcp_select_window() aka NET2E
761da177e4SLinus Torvalds  *					window non shrink trick.
771da177e4SLinus Torvalds  *		Alan Cox	:	Added a couple of small NET2E timer
781da177e4SLinus Torvalds  *					fixes
791da177e4SLinus Torvalds  *		Charles Hedrick :	TCP fixes
801da177e4SLinus Torvalds  *		Toomas Tamm	:	TCP window fixes
811da177e4SLinus Torvalds  *		Alan Cox	:	Small URG fix to rlogin ^C ack fight
821da177e4SLinus Torvalds  *		Charles Hedrick	:	Rewrote most of it to actually work
831da177e4SLinus Torvalds  *		Linus		:	Rewrote tcp_read() and URG handling
841da177e4SLinus Torvalds  *					completely
851da177e4SLinus Torvalds  *		Gerhard Koerting:	Fixed some missing timer handling
861da177e4SLinus Torvalds  *		Matthew Dillon  :	Reworked TCP machine states as per RFC
871da177e4SLinus Torvalds  *		Gerhard Koerting:	PC/TCP workarounds
881da177e4SLinus Torvalds  *		Adam Caldwell	:	Assorted timer/timing errors
891da177e4SLinus Torvalds  *		Matthew Dillon	:	Fixed another RST bug
901da177e4SLinus Torvalds  *		Alan Cox	:	Move to kernel side addressing changes.
911da177e4SLinus Torvalds  *		Alan Cox	:	Beginning work on TCP fastpathing
921da177e4SLinus Torvalds  *					(not yet usable)
931da177e4SLinus Torvalds  *		Arnt Gulbrandsen:	Turbocharged tcp_check() routine.
941da177e4SLinus Torvalds  *		Alan Cox	:	TCP fast path debugging
951da177e4SLinus Torvalds  *		Alan Cox	:	Window clamping
961da177e4SLinus Torvalds  *		Michael Riepe	:	Bug in tcp_check()
971da177e4SLinus Torvalds  *		Matt Dillon	:	More TCP improvements and RST bug fixes
981da177e4SLinus Torvalds  *		Matt Dillon	:	Yet more small nasties remove from the
991da177e4SLinus Torvalds  *					TCP code (Be very nice to this man if
1001da177e4SLinus Torvalds  *					tcp finally works 100%) 8)
1011da177e4SLinus Torvalds  *		Alan Cox	:	BSD accept semantics.
1021da177e4SLinus Torvalds  *		Alan Cox	:	Reset on closedown bug.
1031da177e4SLinus Torvalds  *	Peter De Schrijver	:	ENOTCONN check missing in tcp_sendto().
1041da177e4SLinus Torvalds  *		Michael Pall	:	Handle poll() after URG properly in
1051da177e4SLinus Torvalds  *					all cases.
1061da177e4SLinus Torvalds  *		Michael Pall	:	Undo the last fix in tcp_read_urg()
1071da177e4SLinus Torvalds  *					(multi URG PUSH broke rlogin).
1081da177e4SLinus Torvalds  *		Michael Pall	:	Fix the multi URG PUSH problem in
1091da177e4SLinus Torvalds  *					tcp_readable(), poll() after URG
1101da177e4SLinus Torvalds  *					works now.
1111da177e4SLinus Torvalds  *		Michael Pall	:	recv(...,MSG_OOB) never blocks in the
1121da177e4SLinus Torvalds  *					BSD api.
1131da177e4SLinus Torvalds  *		Alan Cox	:	Changed the semantics of sk->socket to
1141da177e4SLinus Torvalds  *					fix a race and a signal problem with
1151da177e4SLinus Torvalds  *					accept() and async I/O.
1161da177e4SLinus Torvalds  *		Alan Cox	:	Relaxed the rules on tcp_sendto().
1171da177e4SLinus Torvalds  *		Yury Shevchuk	:	Really fixed accept() blocking problem.
1181da177e4SLinus Torvalds  *		Craig I. Hagan  :	Allow for BSD compatible TIME_WAIT for
1191da177e4SLinus Torvalds  *					clients/servers which listen in on
1201da177e4SLinus Torvalds  *					fixed ports.
1211da177e4SLinus Torvalds  *		Alan Cox	:	Cleaned the above up and shrank it to
1221da177e4SLinus Torvalds  *					a sensible code size.
1231da177e4SLinus Torvalds  *		Alan Cox	:	Self connect lockup fix.
1241da177e4SLinus Torvalds  *		Alan Cox	:	No connect to multicast.
1251da177e4SLinus Torvalds  *		Ross Biro	:	Close unaccepted children on master
1261da177e4SLinus Torvalds  *					socket close.
1271da177e4SLinus Torvalds  *		Alan Cox	:	Reset tracing code.
1281da177e4SLinus Torvalds  *		Alan Cox	:	Spurious resets on shutdown.
1291da177e4SLinus Torvalds  *		Alan Cox	:	Giant 15 minute/60 second timer error
1301da177e4SLinus Torvalds  *		Alan Cox	:	Small whoops in polling before an
1311da177e4SLinus Torvalds  *					accept.
1321da177e4SLinus Torvalds  *		Alan Cox	:	Kept the state trace facility since
1331da177e4SLinus Torvalds  *					it's handy for debugging.
1341da177e4SLinus Torvalds  *		Alan Cox	:	More reset handler fixes.
1351da177e4SLinus Torvalds  *		Alan Cox	:	Started rewriting the code based on
1361da177e4SLinus Torvalds  *					the RFC's for other useful protocol
1371da177e4SLinus Torvalds  *					references see: Comer, KA9Q NOS, and
1381da177e4SLinus Torvalds  *					for a reference on the difference
1391da177e4SLinus Torvalds  *					between specifications and how BSD
1401da177e4SLinus Torvalds  *					works see the 4.4lite source.
1411da177e4SLinus Torvalds  *		A.N.Kuznetsov	:	Don't time wait on completion of tidy
1421da177e4SLinus Torvalds  *					close.
1431da177e4SLinus Torvalds  *		Linus Torvalds	:	Fin/Shutdown & copied_seq changes.
1441da177e4SLinus Torvalds  *		Linus Torvalds	:	Fixed BSD port reuse to work first syn
1451da177e4SLinus Torvalds  *		Alan Cox	:	Reimplemented timers as per the RFC
1461da177e4SLinus Torvalds  *					and using multiple timers for sanity.
1471da177e4SLinus Torvalds  *		Alan Cox	:	Small bug fixes, and a lot of new
1481da177e4SLinus Torvalds  *					comments.
1491da177e4SLinus Torvalds  *		Alan Cox	:	Fixed dual reader crash by locking
1501da177e4SLinus Torvalds  *					the buffers (much like datagram.c)
1511da177e4SLinus Torvalds  *		Alan Cox	:	Fixed stuck sockets in probe. A probe
1521da177e4SLinus Torvalds  *					now gets fed up of retrying without
1531da177e4SLinus Torvalds  *					(even a no space) answer.
1541da177e4SLinus Torvalds  *		Alan Cox	:	Extracted closing code better
1551da177e4SLinus Torvalds  *		Alan Cox	:	Fixed the closing state machine to
1561da177e4SLinus Torvalds  *					resemble the RFC.
1571da177e4SLinus Torvalds  *		Alan Cox	:	More 'per spec' fixes.
1581da177e4SLinus Torvalds  *		Jorge Cwik	:	Even faster checksumming.
1591da177e4SLinus Torvalds  *		Alan Cox	:	tcp_data() doesn't ack illegal PSH
1601da177e4SLinus Torvalds  *					only frames. At least one pc tcp stack
1611da177e4SLinus Torvalds  *					generates them.
1621da177e4SLinus Torvalds  *		Alan Cox	:	Cache last socket.
1631da177e4SLinus Torvalds  *		Alan Cox	:	Per route irtt.
1641da177e4SLinus Torvalds  *		Matt Day	:	poll()->select() match BSD precisely on error
1651da177e4SLinus Torvalds  *		Alan Cox	:	New buffers
1661da177e4SLinus Torvalds  *		Marc Tamsky	:	Various sk->prot->retransmits and
1671da177e4SLinus Torvalds  *					sk->retransmits misupdating fixed.
1681da177e4SLinus Torvalds  *					Fixed tcp_write_timeout: stuck close,
1691da177e4SLinus Torvalds  *					and TCP syn retries gets used now.
1701da177e4SLinus Torvalds  *		Mark Yarvis	:	In tcp_read_wakeup(), don't send an
1711da177e4SLinus Torvalds  *					ack if state is TCP_CLOSED.
1721da177e4SLinus Torvalds  *		Alan Cox	:	Look up device on a retransmit - routes may
1731da177e4SLinus Torvalds  *					change. Doesn't yet cope with MSS shrink right
1741da177e4SLinus Torvalds  *					but it's a start!
1751da177e4SLinus Torvalds  *		Marc Tamsky	:	Closing in closing fixes.
1761da177e4SLinus Torvalds  *		Mike Shaver	:	RFC1122 verifications.
1771da177e4SLinus Torvalds  *		Alan Cox	:	rcv_saddr errors.
1781da177e4SLinus Torvalds  *		Alan Cox	:	Block double connect().
1791da177e4SLinus Torvalds  *		Alan Cox	:	Small hooks for enSKIP.
1801da177e4SLinus Torvalds  *		Alexey Kuznetsov:	Path MTU discovery.
1811da177e4SLinus Torvalds  *		Alan Cox	:	Support soft errors.
1821da177e4SLinus Torvalds  *		Alan Cox	:	Fix MTU discovery pathological case
1831da177e4SLinus Torvalds  *					when the remote claims no mtu!
1841da177e4SLinus Torvalds  *		Marc Tamsky	:	TCP_CLOSE fix.
1851da177e4SLinus Torvalds  *		Colin (G3TNE)	:	Send a reset on syn ack replies in
1861da177e4SLinus Torvalds  *					window but wrong (fixes NT lpd problems)
1871da177e4SLinus Torvalds  *		Pedro Roque	:	Better TCP window handling, delayed ack.
1881da177e4SLinus Torvalds  *		Joerg Reuter	:	No modification of locked buffers in
1891da177e4SLinus Torvalds  *					tcp_do_retransmit()
1901da177e4SLinus Torvalds  *		Eric Schenk	:	Changed receiver side silly window
1911da177e4SLinus Torvalds  *					avoidance algorithm to BSD style
1921da177e4SLinus Torvalds  *					algorithm. This doubles throughput
1931da177e4SLinus Torvalds  *					against machines running Solaris,
1941da177e4SLinus Torvalds  *					and seems to result in general
1951da177e4SLinus Torvalds  *					improvement.
1961da177e4SLinus Torvalds  *	Stefan Magdalinski	:	adjusted tcp_readable() to fix FIONREAD
1971da177e4SLinus Torvalds  *	Willy Konynenberg	:	Transparent proxying support.
1981da177e4SLinus Torvalds  *	Mike McLagan		:	Routing by source
1991da177e4SLinus Torvalds  *		Keith Owens	:	Do proper merging with partial SKB's in
2001da177e4SLinus Torvalds  *					tcp_do_sendmsg to avoid burstiness.
2011da177e4SLinus Torvalds  *		Eric Schenk	:	Fix fast close down bug with
2021da177e4SLinus Torvalds  *					shutdown() followed by close().
2031da177e4SLinus Torvalds  *		Andi Kleen 	:	Make poll agree with SIGIO
2041da177e4SLinus Torvalds  *	Salvatore Sanfilippo	:	Support SO_LINGER with linger == 1 and
2051da177e4SLinus Torvalds  *					lingertime == 0 (RFC 793 ABORT Call)
2061da177e4SLinus Torvalds  *	Hirokazu Takahashi	:	Use copy_from_user() instead of
2071da177e4SLinus Torvalds  *					csum_and_copy_from_user() if possible.
2081da177e4SLinus Torvalds  *
2091da177e4SLinus Torvalds  * Description of States:
2101da177e4SLinus Torvalds  *
2111da177e4SLinus Torvalds  *	TCP_SYN_SENT		sent a connection request, waiting for ack
2121da177e4SLinus Torvalds  *
2131da177e4SLinus Torvalds  *	TCP_SYN_RECV		received a connection request, sent ack,
2141da177e4SLinus Torvalds  *				waiting for final ack in three-way handshake.
2151da177e4SLinus Torvalds  *
2161da177e4SLinus Torvalds  *	TCP_ESTABLISHED		connection established
2171da177e4SLinus Torvalds  *
2181da177e4SLinus Torvalds  *	TCP_FIN_WAIT1		our side has shutdown, waiting to complete
2191da177e4SLinus Torvalds  *				transmission of remaining buffered data
2201da177e4SLinus Torvalds  *
2211da177e4SLinus Torvalds  *	TCP_FIN_WAIT2		all buffered data sent, waiting for remote
2221da177e4SLinus Torvalds  *				to shutdown
2231da177e4SLinus Torvalds  *
2241da177e4SLinus Torvalds  *	TCP_CLOSING		both sides have shutdown but we still have
2251da177e4SLinus Torvalds  *				data we have to finish sending
2261da177e4SLinus Torvalds  *
2271da177e4SLinus Torvalds  *	TCP_TIME_WAIT		timeout to catch resent junk before entering
2281da177e4SLinus Torvalds  *				closed, can only be entered from FIN_WAIT2
2291da177e4SLinus Torvalds  *				or CLOSING.  Required because the other end
2301da177e4SLinus Torvalds  *				may not have gotten our last ACK causing it
2311da177e4SLinus Torvalds  *				to retransmit the data packet (which we ignore)
2321da177e4SLinus Torvalds  *
2331da177e4SLinus Torvalds  *	TCP_CLOSE_WAIT		remote side has shutdown and is waiting for
2341da177e4SLinus Torvalds  *				us to finish writing our data and to shutdown
2351da177e4SLinus Torvalds  *				(we have to close() to move on to LAST_ACK)
2361da177e4SLinus Torvalds  *
2371da177e4SLinus Torvalds  *	TCP_LAST_ACK		out side has shutdown after remote has
2381da177e4SLinus Torvalds  *				shutdown.  There may still be data in our
2391da177e4SLinus Torvalds  *				buffer that we have to finish sending
2401da177e4SLinus Torvalds  *
2411da177e4SLinus Torvalds  *	TCP_CLOSE		socket is finished
2421da177e4SLinus Torvalds  */
2431da177e4SLinus Torvalds 
244afd46503SJoe Perches #define pr_fmt(fmt) "TCP: " fmt
245afd46503SJoe Perches 
246cf80e0e4SHerbert Xu #include <crypto/hash.h>
247172589ccSIlpo Järvinen #include <linux/kernel.h>
2481da177e4SLinus Torvalds #include <linux/module.h>
2491da177e4SLinus Torvalds #include <linux/types.h>
2501da177e4SLinus Torvalds #include <linux/fcntl.h>
2511da177e4SLinus Torvalds #include <linux/poll.h>
2526e9250f5SEric Dumazet #include <linux/inet_diag.h>
2531da177e4SLinus Torvalds #include <linux/init.h>
2541da177e4SLinus Torvalds #include <linux/fs.h>
2559c55e01cSJens Axboe #include <linux/skbuff.h>
25681b23b4aSAndrew Morton #include <linux/scatterlist.h>
2579c55e01cSJens Axboe #include <linux/splice.h>
2589c55e01cSJens Axboe #include <linux/net.h>
2599c55e01cSJens Axboe #include <linux/socket.h>
2601da177e4SLinus Torvalds #include <linux/random.h>
26157c8a661SMike Rapoport #include <linux/memblock.h>
26257413ebcSMiquel van Smoorenburg #include <linux/highmem.h>
263b8059eadSDavid S. Miller #include <linux/cache.h>
264f4c50d99SHerbert Xu #include <linux/err.h>
265da5c78c8SWilliam Allen Simpson #include <linux/time.h>
2665a0e3ad6STejun Heo #include <linux/slab.h>
26798aaa913SMike Maloney #include <linux/errqueue.h>
26860e2a778SUrsula Braun #include <linux/static_key.h>
26997a19cafSYonghong Song #include <linux/btf.h>
2701da177e4SLinus Torvalds 
2711da177e4SLinus Torvalds #include <net/icmp.h>
272cf60af03SYuchung Cheng #include <net/inet_common.h>
2731da177e4SLinus Torvalds #include <net/tcp.h>
274f870fa0bSMat Martineau #include <net/mptcp.h>
2751da177e4SLinus Torvalds #include <net/xfrm.h>
2761da177e4SLinus Torvalds #include <net/ip.h>
2779c55e01cSJens Axboe #include <net/sock.h>
2781da177e4SLinus Torvalds 
2797c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
2801da177e4SLinus Torvalds #include <asm/ioctls.h>
281076bb0c8SEliezer Tamir #include <net/busy_poll.h>
2821da177e4SLinus Torvalds 
283925bba24SArjun Roy /* Track pending CMSGs. */
284925bba24SArjun Roy enum {
285925bba24SArjun Roy 	TCP_CMSG_INQ = 1,
286925bba24SArjun Roy 	TCP_CMSG_TS = 2
287925bba24SArjun Roy };
288925bba24SArjun Roy 
28919757cebSEric Dumazet DEFINE_PER_CPU(unsigned int, tcp_orphan_count);
29019757cebSEric Dumazet EXPORT_PER_CPU_SYMBOL_GPL(tcp_orphan_count);
2910a5578cfSArnaldo Carvalho de Melo 
292a4fe34bfSEric W. Biederman long sysctl_tcp_mem[3] __read_mostly;
293a4fe34bfSEric W. Biederman EXPORT_SYMBOL(sysctl_tcp_mem);
2941da177e4SLinus Torvalds 
29591b6d325SEric Dumazet atomic_long_t tcp_memory_allocated ____cacheline_aligned_in_smp;	/* Current allocated memory. */
2961da177e4SLinus Torvalds EXPORT_SYMBOL(tcp_memory_allocated);
2970defbb0aSEric Dumazet DEFINE_PER_CPU(int, tcp_memory_per_cpu_fw_alloc);
2980defbb0aSEric Dumazet EXPORT_PER_CPU_SYMBOL_GPL(tcp_memory_per_cpu_fw_alloc);
2991748376bSEric Dumazet 
30060e2a778SUrsula Braun #if IS_ENABLED(CONFIG_SMC)
30160e2a778SUrsula Braun DEFINE_STATIC_KEY_FALSE(tcp_have_smc);
30260e2a778SUrsula Braun EXPORT_SYMBOL(tcp_have_smc);
30360e2a778SUrsula Braun #endif
30460e2a778SUrsula Braun 
3051748376bSEric Dumazet /*
3061748376bSEric Dumazet  * Current number of TCP sockets.
3071748376bSEric Dumazet  */
30891b6d325SEric Dumazet struct percpu_counter tcp_sockets_allocated ____cacheline_aligned_in_smp;
3091da177e4SLinus Torvalds EXPORT_SYMBOL(tcp_sockets_allocated);
3101da177e4SLinus Torvalds 
3111da177e4SLinus Torvalds /*
3129c55e01cSJens Axboe  * TCP splice context
3139c55e01cSJens Axboe  */
3149c55e01cSJens Axboe struct tcp_splice_state {
3159c55e01cSJens Axboe 	struct pipe_inode_info *pipe;
3169c55e01cSJens Axboe 	size_t len;
3179c55e01cSJens Axboe 	unsigned int flags;
3189c55e01cSJens Axboe };
3199c55e01cSJens Axboe 
3209c55e01cSJens Axboe /*
3211da177e4SLinus Torvalds  * Pressure flag: try to collapse.
3221da177e4SLinus Torvalds  * Technical note: it is used by multiple contexts non atomically.
3233ab224beSHideo Aoki  * All the __sk_mem_schedule() is of this nature: accounting
3241da177e4SLinus Torvalds  * is strict, actions are advisory and have some latency.
3251da177e4SLinus Torvalds  */
32606044751SEric Dumazet unsigned long tcp_memory_pressure __read_mostly;
32706044751SEric Dumazet EXPORT_SYMBOL_GPL(tcp_memory_pressure);
3281da177e4SLinus Torvalds 
3295c52ba17SPavel Emelyanov void tcp_enter_memory_pressure(struct sock *sk)
3301da177e4SLinus Torvalds {
33106044751SEric Dumazet 	unsigned long val;
33206044751SEric Dumazet 
3331f142c17SEric Dumazet 	if (READ_ONCE(tcp_memory_pressure))
33406044751SEric Dumazet 		return;
33506044751SEric Dumazet 	val = jiffies;
33606044751SEric Dumazet 
33706044751SEric Dumazet 	if (!val)
33806044751SEric Dumazet 		val--;
33906044751SEric Dumazet 	if (!cmpxchg(&tcp_memory_pressure, 0, val))
3404e673444SPavel Emelyanov 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES);
3411da177e4SLinus Torvalds }
34206044751SEric Dumazet EXPORT_SYMBOL_GPL(tcp_enter_memory_pressure);
34306044751SEric Dumazet 
34406044751SEric Dumazet void tcp_leave_memory_pressure(struct sock *sk)
34506044751SEric Dumazet {
34606044751SEric Dumazet 	unsigned long val;
34706044751SEric Dumazet 
3481f142c17SEric Dumazet 	if (!READ_ONCE(tcp_memory_pressure))
34906044751SEric Dumazet 		return;
35006044751SEric Dumazet 	val = xchg(&tcp_memory_pressure, 0);
35106044751SEric Dumazet 	if (val)
35206044751SEric Dumazet 		NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURESCHRONO,
35306044751SEric Dumazet 			      jiffies_to_msecs(jiffies - val));
3541da177e4SLinus Torvalds }
35506044751SEric Dumazet EXPORT_SYMBOL_GPL(tcp_leave_memory_pressure);
3561da177e4SLinus Torvalds 
357b103cf34SJulian Anastasov /* Convert seconds to retransmits based on initial and max timeout */
358b103cf34SJulian Anastasov static u8 secs_to_retrans(int seconds, int timeout, int rto_max)
359b103cf34SJulian Anastasov {
360b103cf34SJulian Anastasov 	u8 res = 0;
361b103cf34SJulian Anastasov 
362b103cf34SJulian Anastasov 	if (seconds > 0) {
363b103cf34SJulian Anastasov 		int period = timeout;
364b103cf34SJulian Anastasov 
365b103cf34SJulian Anastasov 		res = 1;
366b103cf34SJulian Anastasov 		while (seconds > period && res < 255) {
367b103cf34SJulian Anastasov 			res++;
368b103cf34SJulian Anastasov 			timeout <<= 1;
369b103cf34SJulian Anastasov 			if (timeout > rto_max)
370b103cf34SJulian Anastasov 				timeout = rto_max;
371b103cf34SJulian Anastasov 			period += timeout;
372b103cf34SJulian Anastasov 		}
373b103cf34SJulian Anastasov 	}
374b103cf34SJulian Anastasov 	return res;
375b103cf34SJulian Anastasov }
376b103cf34SJulian Anastasov 
377b103cf34SJulian Anastasov /* Convert retransmits to seconds based on initial and max timeout */
378b103cf34SJulian Anastasov static int retrans_to_secs(u8 retrans, int timeout, int rto_max)
379b103cf34SJulian Anastasov {
380b103cf34SJulian Anastasov 	int period = 0;
381b103cf34SJulian Anastasov 
382b103cf34SJulian Anastasov 	if (retrans > 0) {
383b103cf34SJulian Anastasov 		period = timeout;
384b103cf34SJulian Anastasov 		while (--retrans) {
385b103cf34SJulian Anastasov 			timeout <<= 1;
386b103cf34SJulian Anastasov 			if (timeout > rto_max)
387b103cf34SJulian Anastasov 				timeout = rto_max;
388b103cf34SJulian Anastasov 			period += timeout;
389b103cf34SJulian Anastasov 		}
390b103cf34SJulian Anastasov 	}
391b103cf34SJulian Anastasov 	return period;
392b103cf34SJulian Anastasov }
393b103cf34SJulian Anastasov 
3940263598cSWei Wang static u64 tcp_compute_delivery_rate(const struct tcp_sock *tp)
3950263598cSWei Wang {
3960263598cSWei Wang 	u32 rate = READ_ONCE(tp->rate_delivered);
3970263598cSWei Wang 	u32 intv = READ_ONCE(tp->rate_interval_us);
3980263598cSWei Wang 	u64 rate64 = 0;
3990263598cSWei Wang 
4000263598cSWei Wang 	if (rate && intv) {
4010263598cSWei Wang 		rate64 = (u64)rate * tp->mss_cache * USEC_PER_SEC;
4020263598cSWei Wang 		do_div(rate64, intv);
4030263598cSWei Wang 	}
4040263598cSWei Wang 	return rate64;
4050263598cSWei Wang }
4060263598cSWei Wang 
407900f65d3SNeal Cardwell /* Address-family independent initialization for a tcp_sock.
408900f65d3SNeal Cardwell  *
409900f65d3SNeal Cardwell  * NOTE: A lot of things set to zero explicitly by call to
410900f65d3SNeal Cardwell  *       sk_alloc() so need not be done here.
411900f65d3SNeal Cardwell  */
412900f65d3SNeal Cardwell void tcp_init_sock(struct sock *sk)
413900f65d3SNeal Cardwell {
414900f65d3SNeal Cardwell 	struct inet_connection_sock *icsk = inet_csk(sk);
415900f65d3SNeal Cardwell 	struct tcp_sock *tp = tcp_sk(sk);
416900f65d3SNeal Cardwell 
4179f5afeaeSYaogong Wang 	tp->out_of_order_queue = RB_ROOT;
41875c119afSEric Dumazet 	sk->tcp_rtx_queue = RB_ROOT;
419900f65d3SNeal Cardwell 	tcp_init_xmit_timers(sk);
42046d3ceabSEric Dumazet 	INIT_LIST_HEAD(&tp->tsq_node);
421e2080072SEric Dumazet 	INIT_LIST_HEAD(&tp->tsorted_sent_queue);
422900f65d3SNeal Cardwell 
423900f65d3SNeal Cardwell 	icsk->icsk_rto = TCP_TIMEOUT_INIT;
424ca584ba0SMartin KaFai Lau 	icsk->icsk_rto_min = TCP_RTO_MIN;
4252b8ee4f0SMartin KaFai Lau 	icsk->icsk_delack_max = TCP_DELACK_MAX;
426740b0f18SEric Dumazet 	tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT);
427ac9517fcSEric Dumazet 	minmax_reset(&tp->rtt_min, tcp_jiffies32, ~0U);
428900f65d3SNeal Cardwell 
429900f65d3SNeal Cardwell 	/* So many TCP implementations out there (incorrectly) count the
430900f65d3SNeal Cardwell 	 * initial SYN frame in their delayed-ACK and congestion control
431900f65d3SNeal Cardwell 	 * algorithms that we must have the following bandaid to talk
432900f65d3SNeal Cardwell 	 * efficiently to them.  -DaveM
433900f65d3SNeal Cardwell 	 */
43440570375SEric Dumazet 	tcp_snd_cwnd_set(tp, TCP_INIT_CWND);
435900f65d3SNeal Cardwell 
436d7722e85SSoheil Hassas Yeganeh 	/* There's a bubble in the pipe until at least the first ACK. */
437d7722e85SSoheil Hassas Yeganeh 	tp->app_limited = ~0U;
438300b655dSDavid Morley 	tp->rate_app_limited = 1;
439d7722e85SSoheil Hassas Yeganeh 
440900f65d3SNeal Cardwell 	/* See draft-stevens-tcpca-spec-01 for discussion of the
441900f65d3SNeal Cardwell 	 * initialization of these values.
442900f65d3SNeal Cardwell 	 */
443900f65d3SNeal Cardwell 	tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
444900f65d3SNeal Cardwell 	tp->snd_cwnd_clamp = ~0;
445900f65d3SNeal Cardwell 	tp->mss_cache = TCP_MSS_DEFAULT;
446900f65d3SNeal Cardwell 
44746778cd1SKuniyuki Iwashima 	tp->reordering = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reordering);
44855d8694fSFlorian Westphal 	tcp_assign_congestion_control(sk);
449900f65d3SNeal Cardwell 
450ceaa1fefSAndrey Vagin 	tp->tsoffset = 0;
4511f255691SPriyaranjan Jha 	tp->rack.reo_wnd_steps = 1;
452ceaa1fefSAndrey Vagin 
453900f65d3SNeal Cardwell 	sk->sk_write_space = sk_stream_write_space;
454900f65d3SNeal Cardwell 	sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
455900f65d3SNeal Cardwell 
456900f65d3SNeal Cardwell 	icsk->icsk_sync_mss = tcp_sync_mss;
457900f65d3SNeal Cardwell 
45802739545SKuniyuki Iwashima 	WRITE_ONCE(sk->sk_sndbuf, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_wmem[1]));
45902739545SKuniyuki Iwashima 	WRITE_ONCE(sk->sk_rcvbuf, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[1]));
460900f65d3SNeal Cardwell 
461e993ffe3SPavel Begunkov 	set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
462900f65d3SNeal Cardwell 	sk_sockets_allocated_inc(sk);
463900f65d3SNeal Cardwell }
464900f65d3SNeal Cardwell EXPORT_SYMBOL(tcp_init_sock);
465900f65d3SNeal Cardwell 
4664e8cc228SEric Dumazet static void tcp_tx_timestamp(struct sock *sk, u16 tsflags)
4674ed2d765SWillem de Bruijn {
4684e8cc228SEric Dumazet 	struct sk_buff *skb = tcp_write_queue_tail(sk);
4694e8cc228SEric Dumazet 
470ad02c4f5SSoheil Hassas Yeganeh 	if (tsflags && skb) {
4714ed2d765SWillem de Bruijn 		struct skb_shared_info *shinfo = skb_shinfo(skb);
4726b084928SSoheil Hassas Yeganeh 		struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
4734ed2d765SWillem de Bruijn 
474c14ac945SSoheil Hassas Yeganeh 		sock_tx_timestamp(sk, tsflags, &shinfo->tx_flags);
4750a2cf20cSSoheil Hassas Yeganeh 		if (tsflags & SOF_TIMESTAMPING_TX_ACK)
4760a2cf20cSSoheil Hassas Yeganeh 			tcb->txstamp_ack = 1;
4770a2cf20cSSoheil Hassas Yeganeh 		if (tsflags & SOF_TIMESTAMPING_TX_RECORD_MASK)
4784ed2d765SWillem de Bruijn 			shinfo->tskey = TCP_SKB_CB(skb)->seq + skb->len - 1;
4794ed2d765SWillem de Bruijn 	}
480f066e2b0SWillem de Bruijn }
4814ed2d765SWillem de Bruijn 
48205dc72abSEric Dumazet static bool tcp_stream_is_readable(struct sock *sk, int target)
4838934ce2fSJohn Fastabend {
48405dc72abSEric Dumazet 	if (tcp_epollin_ready(sk, target))
48505dc72abSEric Dumazet 		return true;
4867b50ecfcSCong Wang 	return sk_is_readable(sk);
4878934ce2fSJohn Fastabend }
4888934ce2fSJohn Fastabend 
4891da177e4SLinus Torvalds /*
490a11e1d43SLinus Torvalds  *	Wait for a TCP event.
491a11e1d43SLinus Torvalds  *
492a11e1d43SLinus Torvalds  *	Note that we don't need to lock the socket, as the upper poll layers
493a11e1d43SLinus Torvalds  *	take care of normal races (between the test and the event) and we don't
494a11e1d43SLinus Torvalds  *	go look at any of the socket buffers directly.
4951da177e4SLinus Torvalds  */
496a11e1d43SLinus Torvalds __poll_t tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
4971da177e4SLinus Torvalds {
498a11e1d43SLinus Torvalds 	__poll_t mask;
4991da177e4SLinus Torvalds 	struct sock *sk = sock->sk;
500cf533ea5SEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
50100fd38d9SEric Dumazet 	int state;
5021da177e4SLinus Torvalds 
50389ab066dSKarsten Graul 	sock_poll_wait(file, sock, wait);
504a11e1d43SLinus Torvalds 
505986ffdfdSYafang Shao 	state = inet_sk_state_load(sk);
50600fd38d9SEric Dumazet 	if (state == TCP_LISTEN)
507dc40c7bcSArnaldo Carvalho de Melo 		return inet_csk_listen_poll(sk);
5081da177e4SLinus Torvalds 
509a11e1d43SLinus Torvalds 	/* Socket is not locked. We are protected from async events
510a11e1d43SLinus Torvalds 	 * by poll logic and correct handling of state changes
511a11e1d43SLinus Torvalds 	 * made by other threads is impossible in any case.
512a11e1d43SLinus Torvalds 	 */
513a11e1d43SLinus Torvalds 
514a11e1d43SLinus Torvalds 	mask = 0;
515a11e1d43SLinus Torvalds 
5161da177e4SLinus Torvalds 	/*
517a9a08845SLinus Torvalds 	 * EPOLLHUP is certainly not done right. But poll() doesn't
5181da177e4SLinus Torvalds 	 * have a notion of HUP in just one direction, and for a
5191da177e4SLinus Torvalds 	 * socket the read side is more interesting.
5201da177e4SLinus Torvalds 	 *
521a9a08845SLinus Torvalds 	 * Some poll() documentation says that EPOLLHUP is incompatible
522a9a08845SLinus Torvalds 	 * with the EPOLLOUT/POLLWR flags, so somebody should check this
5231da177e4SLinus Torvalds 	 * all. But careful, it tends to be safer to return too many
5241da177e4SLinus Torvalds 	 * bits than too few, and you can easily break real applications
5251da177e4SLinus Torvalds 	 * if you don't tell them that something has hung up!
5261da177e4SLinus Torvalds 	 *
5271da177e4SLinus Torvalds 	 * Check-me.
5281da177e4SLinus Torvalds 	 *
529a9a08845SLinus Torvalds 	 * Check number 1. EPOLLHUP is _UNMASKABLE_ event (see UNIX98 and
5301da177e4SLinus Torvalds 	 * our fs/select.c). It means that after we received EOF,
5311da177e4SLinus Torvalds 	 * poll always returns immediately, making impossible poll() on write()
532a9a08845SLinus Torvalds 	 * in state CLOSE_WAIT. One solution is evident --- to set EPOLLHUP
5331da177e4SLinus Torvalds 	 * if and only if shutdown has been made in both directions.
5341da177e4SLinus Torvalds 	 * Actually, it is interesting to look how Solaris and DUX
535a9a08845SLinus Torvalds 	 * solve this dilemma. I would prefer, if EPOLLHUP were maskable,
5361da177e4SLinus Torvalds 	 * then we could set it on SND_SHUTDOWN. BTW examples given
5371da177e4SLinus Torvalds 	 * in Stevens' books assume exactly this behaviour, it explains
538a9a08845SLinus Torvalds 	 * why EPOLLHUP is incompatible with EPOLLOUT.	--ANK
5391da177e4SLinus Torvalds 	 *
5401da177e4SLinus Torvalds 	 * NOTE. Check for TCP_CLOSE is added. The goal is to prevent
5411da177e4SLinus Torvalds 	 * blocking on fresh not-connected or disconnected socket. --ANK
5421da177e4SLinus Torvalds 	 */
54300fd38d9SEric Dumazet 	if (sk->sk_shutdown == SHUTDOWN_MASK || state == TCP_CLOSE)
544a9a08845SLinus Torvalds 		mask |= EPOLLHUP;
5451da177e4SLinus Torvalds 	if (sk->sk_shutdown & RCV_SHUTDOWN)
546a9a08845SLinus Torvalds 		mask |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP;
5471da177e4SLinus Torvalds 
5488336886fSJerry Chu 	/* Connected or passive Fast Open socket? */
54900fd38d9SEric Dumazet 	if (state != TCP_SYN_SENT &&
550d983ea6fSEric Dumazet 	    (state != TCP_SYN_RECV || rcu_access_pointer(tp->fastopen_rsk))) {
551c7004482SDavid S. Miller 		int target = sock_rcvlowat(sk, 0, INT_MAX);
5527b6a893aSEric Dumazet 		u16 urg_data = READ_ONCE(tp->urg_data);
553c7004482SDavid S. Miller 
554b96c51bdSEric Dumazet 		if (unlikely(urg_data) &&
5557b6a893aSEric Dumazet 		    READ_ONCE(tp->urg_seq) == READ_ONCE(tp->copied_seq) &&
5567b6a893aSEric Dumazet 		    !sock_flag(sk, SOCK_URGINLINE))
557b634f875SAlexandra Kossovsky 			target++;
558c7004482SDavid S. Miller 
55905dc72abSEric Dumazet 		if (tcp_stream_is_readable(sk, target))
560a9a08845SLinus Torvalds 			mask |= EPOLLIN | EPOLLRDNORM;
5611da177e4SLinus Torvalds 
5621da177e4SLinus Torvalds 		if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
5638ba3c9d1SSoheil Hassas Yeganeh 			if (__sk_stream_is_writeable(sk, 1)) {
564a9a08845SLinus Torvalds 				mask |= EPOLLOUT | EPOLLWRNORM;
5651da177e4SLinus Torvalds 			} else {  /* send SIGIO later */
5669cd3e072SEric Dumazet 				sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
5671da177e4SLinus Torvalds 				set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
5681da177e4SLinus Torvalds 
5691da177e4SLinus Torvalds 				/* Race breaker. If space is freed after
5701da177e4SLinus Torvalds 				 * wspace test but before the flags are set,
5713c715127Sjbaron@akamai.com 				 * IO signal will be lost. Memory barrier
5723c715127Sjbaron@akamai.com 				 * pairs with the input side.
5731da177e4SLinus Torvalds 				 */
5743c715127Sjbaron@akamai.com 				smp_mb__after_atomic();
5758ba3c9d1SSoheil Hassas Yeganeh 				if (__sk_stream_is_writeable(sk, 1))
576a9a08845SLinus Torvalds 					mask |= EPOLLOUT | EPOLLWRNORM;
5771da177e4SLinus Torvalds 			}
578d84ba638SKOSAKI Motohiro 		} else
579a9a08845SLinus Torvalds 			mask |= EPOLLOUT | EPOLLWRNORM;
5801da177e4SLinus Torvalds 
5817b6a893aSEric Dumazet 		if (urg_data & TCP_URG_VALID)
582a9a08845SLinus Torvalds 			mask |= EPOLLPRI;
583d68be71eSDavide Caratti 	} else if (state == TCP_SYN_SENT && inet_sk(sk)->defer_connect) {
58419f6d3f3SWei Wang 		/* Active TCP fastopen socket with defer_connect
585a9a08845SLinus Torvalds 		 * Return EPOLLOUT so application can call write()
58619f6d3f3SWei Wang 		 * in order for kernel to generate SYN+data
58719f6d3f3SWei Wang 		 */
588a9a08845SLinus Torvalds 		mask |= EPOLLOUT | EPOLLWRNORM;
5891da177e4SLinus Torvalds 	}
590a4d25803STom Marshall 	/* This barrier is coupled with smp_wmb() in tcp_reset() */
591a4d25803STom Marshall 	smp_rmb();
592e13ec3daSEric Dumazet 	if (READ_ONCE(sk->sk_err) ||
593e13ec3daSEric Dumazet 	    !skb_queue_empty_lockless(&sk->sk_error_queue))
594a9a08845SLinus Torvalds 		mask |= EPOLLERR;
595a4d25803STom Marshall 
5961da177e4SLinus Torvalds 	return mask;
5971da177e4SLinus Torvalds }
598a11e1d43SLinus Torvalds EXPORT_SYMBOL(tcp_poll);
5991da177e4SLinus Torvalds 
6001da177e4SLinus Torvalds int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
6011da177e4SLinus Torvalds {
6021da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
6031da177e4SLinus Torvalds 	int answ;
6040e71c55cSEric Dumazet 	bool slow;
6051da177e4SLinus Torvalds 
6061da177e4SLinus Torvalds 	switch (cmd) {
6071da177e4SLinus Torvalds 	case SIOCINQ:
6081da177e4SLinus Torvalds 		if (sk->sk_state == TCP_LISTEN)
6091da177e4SLinus Torvalds 			return -EINVAL;
6101da177e4SLinus Torvalds 
6110e71c55cSEric Dumazet 		slow = lock_sock_fast(sk);
612473bd239STom Herbert 		answ = tcp_inq(sk);
6130e71c55cSEric Dumazet 		unlock_sock_fast(sk, slow);
6141da177e4SLinus Torvalds 		break;
6151da177e4SLinus Torvalds 	case SIOCATMARK:
6167b6a893aSEric Dumazet 		answ = READ_ONCE(tp->urg_data) &&
617d9b55bf7SEric Dumazet 		       READ_ONCE(tp->urg_seq) == READ_ONCE(tp->copied_seq);
6181da177e4SLinus Torvalds 		break;
6191da177e4SLinus Torvalds 	case SIOCOUTQ:
6201da177e4SLinus Torvalds 		if (sk->sk_state == TCP_LISTEN)
6211da177e4SLinus Torvalds 			return -EINVAL;
6221da177e4SLinus Torvalds 
6231da177e4SLinus Torvalds 		if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
6241da177e4SLinus Torvalds 			answ = 0;
6251da177e4SLinus Torvalds 		else
6260f317464SEric Dumazet 			answ = READ_ONCE(tp->write_seq) - tp->snd_una;
6271da177e4SLinus Torvalds 		break;
6282f4e1b39SMario Schuknecht 	case SIOCOUTQNSD:
6292f4e1b39SMario Schuknecht 		if (sk->sk_state == TCP_LISTEN)
6302f4e1b39SMario Schuknecht 			return -EINVAL;
6312f4e1b39SMario Schuknecht 
6322f4e1b39SMario Schuknecht 		if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
6332f4e1b39SMario Schuknecht 			answ = 0;
6342f4e1b39SMario Schuknecht 		else
635e0d694d6SEric Dumazet 			answ = READ_ONCE(tp->write_seq) -
636e0d694d6SEric Dumazet 			       READ_ONCE(tp->snd_nxt);
6372f4e1b39SMario Schuknecht 		break;
6381da177e4SLinus Torvalds 	default:
6391da177e4SLinus Torvalds 		return -ENOIOCTLCMD;
6403ff50b79SStephen Hemminger 	}
6411da177e4SLinus Torvalds 
6421da177e4SLinus Torvalds 	return put_user(answ, (int __user *)arg);
6431da177e4SLinus Torvalds }
6444bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_ioctl);
6451da177e4SLinus Torvalds 
64604d8825cSPaolo Abeni void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb)
6471da177e4SLinus Torvalds {
6484de075e0SEric Dumazet 	TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
6491da177e4SLinus Torvalds 	tp->pushed_seq = tp->write_seq;
6501da177e4SLinus Torvalds }
6511da177e4SLinus Torvalds 
652a2a385d6SEric Dumazet static inline bool forced_push(const struct tcp_sock *tp)
6531da177e4SLinus Torvalds {
6541da177e4SLinus Torvalds 	return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1));
6551da177e4SLinus Torvalds }
6561da177e4SLinus Torvalds 
65704d8825cSPaolo Abeni void tcp_skb_entail(struct sock *sk, struct sk_buff *skb)
6581da177e4SLinus Torvalds {
6599e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
660352d4800SArnaldo Carvalho de Melo 	struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
661352d4800SArnaldo Carvalho de Melo 
662352d4800SArnaldo Carvalho de Melo 	tcb->seq     = tcb->end_seq = tp->write_seq;
6634de075e0SEric Dumazet 	tcb->tcp_flags = TCPHDR_ACK;
664f4a775d1SEric Dumazet 	__skb_header_release(skb);
665fe067e8aSDavid S. Miller 	tcp_add_write_queue_tail(sk, skb);
666ab4e846aSEric Dumazet 	sk_wmem_queued_add(sk, skb->truesize);
6673ab224beSHideo Aoki 	sk_mem_charge(sk, skb->truesize);
66889ebd197SDavid S. Miller 	if (tp->nonagle & TCP_NAGLE_PUSH)
6691da177e4SLinus Torvalds 		tp->nonagle &= ~TCP_NAGLE_PUSH;
6706f021c62SEric Dumazet 
6716f021c62SEric Dumazet 	tcp_slow_start_after_idle_check(sk);
6721da177e4SLinus Torvalds }
6731da177e4SLinus Torvalds 
674afeca340SKrishna Kumar static inline void tcp_mark_urg(struct tcp_sock *tp, int flags)
6751da177e4SLinus Torvalds {
67633f5f57eSIlpo Järvinen 	if (flags & MSG_OOB)
6771da177e4SLinus Torvalds 		tp->snd_up = tp->write_seq;
6781da177e4SLinus Torvalds }
6791da177e4SLinus Torvalds 
680f54b3111SEric Dumazet /* If a not yet filled skb is pushed, do not send it if
681a181ceb5SEric Dumazet  * we have data packets in Qdisc or NIC queues :
682f54b3111SEric Dumazet  * Because TX completion will happen shortly, it gives a chance
683f54b3111SEric Dumazet  * to coalesce future sendmsg() payload into this skb, without
684f54b3111SEric Dumazet  * need for a timer, and with no latency trade off.
685f54b3111SEric Dumazet  * As packets containing data payload have a bigger truesize
686a181ceb5SEric Dumazet  * than pure acks (dataless) packets, the last checks prevent
687a181ceb5SEric Dumazet  * autocorking if we only have an ACK in Qdisc/NIC queues,
688a181ceb5SEric Dumazet  * or if TX completion was delayed after we processed ACK packet.
689f54b3111SEric Dumazet  */
690f54b3111SEric Dumazet static bool tcp_should_autocork(struct sock *sk, struct sk_buff *skb,
691f54b3111SEric Dumazet 				int size_goal)
6921da177e4SLinus Torvalds {
693f54b3111SEric Dumazet 	return skb->len < size_goal &&
69485225e6fSKuniyuki Iwashima 	       READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_autocorking) &&
695114f39feSEric Dumazet 	       !tcp_rtx_queue_empty(sk) &&
696b0de0cf4SEric Dumazet 	       refcount_read(&sk->sk_wmem_alloc) > skb->truesize &&
697b0de0cf4SEric Dumazet 	       tcp_skb_can_collapse_to(skb);
698f54b3111SEric Dumazet }
6999e412ba7SIlpo Järvinen 
70035b2c321SMat Martineau void tcp_push(struct sock *sk, int flags, int mss_now,
701f54b3111SEric Dumazet 	      int nonagle, int size_goal)
702f54b3111SEric Dumazet {
703f54b3111SEric Dumazet 	struct tcp_sock *tp = tcp_sk(sk);
704f54b3111SEric Dumazet 	struct sk_buff *skb;
705f54b3111SEric Dumazet 
706f54b3111SEric Dumazet 	skb = tcp_write_queue_tail(sk);
70775c119afSEric Dumazet 	if (!skb)
70875c119afSEric Dumazet 		return;
7091da177e4SLinus Torvalds 	if (!(flags & MSG_MORE) || forced_push(tp))
710f54b3111SEric Dumazet 		tcp_mark_push(tp, skb);
711afeca340SKrishna Kumar 
712afeca340SKrishna Kumar 	tcp_mark_urg(tp, flags);
713f54b3111SEric Dumazet 
714f54b3111SEric Dumazet 	if (tcp_should_autocork(sk, skb, size_goal)) {
715f54b3111SEric Dumazet 
716f54b3111SEric Dumazet 		/* avoid atomic op if TSQ_THROTTLED bit is already set */
7177aa5470cSEric Dumazet 		if (!test_bit(TSQ_THROTTLED, &sk->sk_tsq_flags)) {
718f54b3111SEric Dumazet 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAUTOCORKING);
7197aa5470cSEric Dumazet 			set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags);
7201da177e4SLinus Torvalds 		}
721a181ceb5SEric Dumazet 		/* It is possible TX completion already happened
722a181ceb5SEric Dumazet 		 * before we set TSQ_THROTTLED.
723a181ceb5SEric Dumazet 		 */
72414afee4bSReshetova, Elena 		if (refcount_read(&sk->sk_wmem_alloc) > skb->truesize)
725f54b3111SEric Dumazet 			return;
726f54b3111SEric Dumazet 	}
727f54b3111SEric Dumazet 
728f54b3111SEric Dumazet 	if (flags & MSG_MORE)
729f54b3111SEric Dumazet 		nonagle = TCP_NAGLE_CORK;
730f54b3111SEric Dumazet 
731f54b3111SEric Dumazet 	__tcp_push_pending_frames(sk, mss_now, nonagle);
7321da177e4SLinus Torvalds }
7331da177e4SLinus Torvalds 
7346ff7751dSAdrian Bunk static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
7359c55e01cSJens Axboe 				unsigned int offset, size_t len)
7369c55e01cSJens Axboe {
7379c55e01cSJens Axboe 	struct tcp_splice_state *tss = rd_desc->arg.data;
73833966dd0SWilly Tarreau 	int ret;
7399c55e01cSJens Axboe 
740a60e3cc7SHannes Frederic Sowa 	ret = skb_splice_bits(skb, skb->sk, offset, tss->pipe,
74125869262SAl Viro 			      min(rd_desc->count, len), tss->flags);
74233966dd0SWilly Tarreau 	if (ret > 0)
74333966dd0SWilly Tarreau 		rd_desc->count -= ret;
74433966dd0SWilly Tarreau 	return ret;
7459c55e01cSJens Axboe }
7469c55e01cSJens Axboe 
7479c55e01cSJens Axboe static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss)
7489c55e01cSJens Axboe {
7499c55e01cSJens Axboe 	/* Store TCP splice context information in read_descriptor_t. */
7509c55e01cSJens Axboe 	read_descriptor_t rd_desc = {
7519c55e01cSJens Axboe 		.arg.data = tss,
75233966dd0SWilly Tarreau 		.count	  = tss->len,
7539c55e01cSJens Axboe 	};
7549c55e01cSJens Axboe 
7559c55e01cSJens Axboe 	return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv);
7569c55e01cSJens Axboe }
7579c55e01cSJens Axboe 
7589c55e01cSJens Axboe /**
7599c55e01cSJens Axboe  *  tcp_splice_read - splice data from TCP socket to a pipe
7609c55e01cSJens Axboe  * @sock:	socket to splice from
7619c55e01cSJens Axboe  * @ppos:	position (not valid)
7629c55e01cSJens Axboe  * @pipe:	pipe to splice to
7639c55e01cSJens Axboe  * @len:	number of bytes to splice
7649c55e01cSJens Axboe  * @flags:	splice modifier flags
7659c55e01cSJens Axboe  *
7669c55e01cSJens Axboe  * Description:
7679c55e01cSJens Axboe  *    Will read pages from given socket and fill them into a pipe.
7689c55e01cSJens Axboe  *
7699c55e01cSJens Axboe  **/
7709c55e01cSJens Axboe ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
7719c55e01cSJens Axboe 			struct pipe_inode_info *pipe, size_t len,
7729c55e01cSJens Axboe 			unsigned int flags)
7739c55e01cSJens Axboe {
7749c55e01cSJens Axboe 	struct sock *sk = sock->sk;
7759c55e01cSJens Axboe 	struct tcp_splice_state tss = {
7769c55e01cSJens Axboe 		.pipe = pipe,
7779c55e01cSJens Axboe 		.len = len,
7789c55e01cSJens Axboe 		.flags = flags,
7799c55e01cSJens Axboe 	};
7809c55e01cSJens Axboe 	long timeo;
7819c55e01cSJens Axboe 	ssize_t spliced;
7829c55e01cSJens Axboe 	int ret;
7839c55e01cSJens Axboe 
7843a047bf8SChangli Gao 	sock_rps_record_flow(sk);
7859c55e01cSJens Axboe 	/*
7869c55e01cSJens Axboe 	 * We can't seek on a socket input
7879c55e01cSJens Axboe 	 */
7889c55e01cSJens Axboe 	if (unlikely(*ppos))
7899c55e01cSJens Axboe 		return -ESPIPE;
7909c55e01cSJens Axboe 
7919c55e01cSJens Axboe 	ret = spliced = 0;
7929c55e01cSJens Axboe 
7939c55e01cSJens Axboe 	lock_sock(sk);
7949c55e01cSJens Axboe 
79542324c62SEric Dumazet 	timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
7969c55e01cSJens Axboe 	while (tss.len) {
7979c55e01cSJens Axboe 		ret = __tcp_splice_read(sk, &tss);
7989c55e01cSJens Axboe 		if (ret < 0)
7999c55e01cSJens Axboe 			break;
8009c55e01cSJens Axboe 		else if (!ret) {
8019c55e01cSJens Axboe 			if (spliced)
8029c55e01cSJens Axboe 				break;
8039c55e01cSJens Axboe 			if (sock_flag(sk, SOCK_DONE))
8049c55e01cSJens Axboe 				break;
8059c55e01cSJens Axboe 			if (sk->sk_err) {
8069c55e01cSJens Axboe 				ret = sock_error(sk);
8079c55e01cSJens Axboe 				break;
8089c55e01cSJens Axboe 			}
8099c55e01cSJens Axboe 			if (sk->sk_shutdown & RCV_SHUTDOWN)
8109c55e01cSJens Axboe 				break;
8119c55e01cSJens Axboe 			if (sk->sk_state == TCP_CLOSE) {
8129c55e01cSJens Axboe 				/*
8139c55e01cSJens Axboe 				 * This occurs when user tries to read
8149c55e01cSJens Axboe 				 * from never connected socket.
8159c55e01cSJens Axboe 				 */
8169c55e01cSJens Axboe 				ret = -ENOTCONN;
8179c55e01cSJens Axboe 				break;
8189c55e01cSJens Axboe 			}
8199c55e01cSJens Axboe 			if (!timeo) {
8209c55e01cSJens Axboe 				ret = -EAGAIN;
8219c55e01cSJens Axboe 				break;
8229c55e01cSJens Axboe 			}
823ccf7abb9SEric Dumazet 			/* if __tcp_splice_read() got nothing while we have
824ccf7abb9SEric Dumazet 			 * an skb in receive queue, we do not want to loop.
825ccf7abb9SEric Dumazet 			 * This might happen with URG data.
826ccf7abb9SEric Dumazet 			 */
827ccf7abb9SEric Dumazet 			if (!skb_queue_empty(&sk->sk_receive_queue))
828ccf7abb9SEric Dumazet 				break;
829dfbafc99SSabrina Dubroca 			sk_wait_data(sk, &timeo, NULL);
8309c55e01cSJens Axboe 			if (signal_pending(current)) {
8319c55e01cSJens Axboe 				ret = sock_intr_errno(timeo);
8329c55e01cSJens Axboe 				break;
8339c55e01cSJens Axboe 			}
8349c55e01cSJens Axboe 			continue;
8359c55e01cSJens Axboe 		}
8369c55e01cSJens Axboe 		tss.len -= ret;
8379c55e01cSJens Axboe 		spliced += ret;
8389c55e01cSJens Axboe 
83933966dd0SWilly Tarreau 		if (!timeo)
84033966dd0SWilly Tarreau 			break;
8419c55e01cSJens Axboe 		release_sock(sk);
8429c55e01cSJens Axboe 		lock_sock(sk);
8439c55e01cSJens Axboe 
8449c55e01cSJens Axboe 		if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
84533966dd0SWilly Tarreau 		    (sk->sk_shutdown & RCV_SHUTDOWN) ||
8469c55e01cSJens Axboe 		    signal_pending(current))
8479c55e01cSJens Axboe 			break;
8489c55e01cSJens Axboe 	}
8499c55e01cSJens Axboe 
8509c55e01cSJens Axboe 	release_sock(sk);
8519c55e01cSJens Axboe 
8529c55e01cSJens Axboe 	if (spliced)
8539c55e01cSJens Axboe 		return spliced;
8549c55e01cSJens Axboe 
8559c55e01cSJens Axboe 	return ret;
8569c55e01cSJens Axboe }
8574bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_splice_read);
8589c55e01cSJens Axboe 
859f8dd3b8dSEric Dumazet struct sk_buff *tcp_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp,
860eb934478SEric Dumazet 				     bool force_schedule)
861f561d0f2SPavel Emelyanov {
862f561d0f2SPavel Emelyanov 	struct sk_buff *skb;
863f561d0f2SPavel Emelyanov 
8648a794df6SEric Dumazet 	skb = alloc_skb_fclone(size + MAX_TCP_HEADER, gfp);
8658e4d980aSEric Dumazet 	if (likely(skb)) {
866eb934478SEric Dumazet 		bool mem_scheduled;
8678e4d980aSEric Dumazet 
8689b65b17dSTalal Ahmad 		skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
869eb934478SEric Dumazet 		if (force_schedule) {
870eb934478SEric Dumazet 			mem_scheduled = true;
8718e4d980aSEric Dumazet 			sk_forced_mem_schedule(sk, skb->truesize);
8728e4d980aSEric Dumazet 		} else {
873eb934478SEric Dumazet 			mem_scheduled = sk_wmem_schedule(sk, skb->truesize);
8748e4d980aSEric Dumazet 		}
875eb934478SEric Dumazet 		if (likely(mem_scheduled)) {
8768a794df6SEric Dumazet 			skb_reserve(skb, MAX_TCP_HEADER);
877a52fe46eSEric Dumazet 			skb->ip_summed = CHECKSUM_PARTIAL;
878e2080072SEric Dumazet 			INIT_LIST_HEAD(&skb->tcp_tsorted_anchor);
879f561d0f2SPavel Emelyanov 			return skb;
880f561d0f2SPavel Emelyanov 		}
881f561d0f2SPavel Emelyanov 		__kfree_skb(skb);
882f561d0f2SPavel Emelyanov 	} else {
8835c52ba17SPavel Emelyanov 		sk->sk_prot->enter_memory_pressure(sk);
884f561d0f2SPavel Emelyanov 		sk_stream_moderate_sndbuf(sk);
885f561d0f2SPavel Emelyanov 	}
886f561d0f2SPavel Emelyanov 	return NULL;
887f561d0f2SPavel Emelyanov }
888f561d0f2SPavel Emelyanov 
8890c54b85fSIlpo Järvinen static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now,
8900c54b85fSIlpo Järvinen 				       int large_allowed)
8910c54b85fSIlpo Järvinen {
8920c54b85fSIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
8936c09fa09SEric Dumazet 	u32 new_size_goal, size_goal;
8940c54b85fSIlpo Järvinen 
89574d4a8f8SEric Dumazet 	if (!large_allowed)
896605ad7f1SEric Dumazet 		return mss_now;
8970c54b85fSIlpo Järvinen 
8986c09fa09SEric Dumazet 	/* Note : tcp_tso_autosize() will eventually split this later */
899ab14f180SDavid Ahern 	new_size_goal = tcp_bound_to_half_wnd(tp, sk->sk_gso_max_size);
9002a3a041cSIlpo Järvinen 
9012a3a041cSIlpo Järvinen 	/* We try hard to avoid divides here */
902605ad7f1SEric Dumazet 	size_goal = tp->gso_segs * mss_now;
903605ad7f1SEric Dumazet 	if (unlikely(new_size_goal < size_goal ||
904605ad7f1SEric Dumazet 		     new_size_goal >= size_goal + mss_now)) {
905605ad7f1SEric Dumazet 		tp->gso_segs = min_t(u16, new_size_goal / mss_now,
9061485348dSBen Hutchings 				     sk->sk_gso_max_segs);
907605ad7f1SEric Dumazet 		size_goal = tp->gso_segs * mss_now;
9080c54b85fSIlpo Järvinen 	}
9090c54b85fSIlpo Järvinen 
910605ad7f1SEric Dumazet 	return max(size_goal, mss_now);
9110c54b85fSIlpo Järvinen }
9120c54b85fSIlpo Järvinen 
91335b2c321SMat Martineau int tcp_send_mss(struct sock *sk, int *size_goal, int flags)
9140c54b85fSIlpo Järvinen {
9150c54b85fSIlpo Järvinen 	int mss_now;
9160c54b85fSIlpo Järvinen 
9170c54b85fSIlpo Järvinen 	mss_now = tcp_current_mss(sk);
9180c54b85fSIlpo Järvinen 	*size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB));
9190c54b85fSIlpo Järvinen 
9200c54b85fSIlpo Järvinen 	return mss_now;
9210c54b85fSIlpo Järvinen }
9220c54b85fSIlpo Järvinen 
923fdfc5c85SEric Dumazet /* In some cases, both sendpage() and sendmsg() could have added
924fdfc5c85SEric Dumazet  * an skb to the write queue, but failed adding payload on it.
925fdfc5c85SEric Dumazet  * We need to remove it to consume less memory, but more
926fdfc5c85SEric Dumazet  * importantly be able to generate EPOLLOUT for Edge Trigger epoll()
927fdfc5c85SEric Dumazet  * users.
928fdfc5c85SEric Dumazet  */
92927728ba8SEric Dumazet void tcp_remove_empty_skb(struct sock *sk)
930fdfc5c85SEric Dumazet {
93127728ba8SEric Dumazet 	struct sk_buff *skb = tcp_write_queue_tail(sk);
93227728ba8SEric Dumazet 
933cf12e6f9SJon Maxwell 	if (skb && TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq) {
934fdfc5c85SEric Dumazet 		tcp_unlink_write_queue(skb, sk);
935fdfc5c85SEric Dumazet 		if (tcp_write_queue_empty(sk))
936fdfc5c85SEric Dumazet 			tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
93703271f3aSTalal Ahmad 		tcp_wmem_free_skb(sk, skb);
938fdfc5c85SEric Dumazet 	}
939fdfc5c85SEric Dumazet }
940fdfc5c85SEric Dumazet 
941f8d9d938SEric Dumazet /* skb changing from pure zc to mixed, must charge zc */
942f8d9d938SEric Dumazet static int tcp_downgrade_zcopy_pure(struct sock *sk, struct sk_buff *skb)
943f8d9d938SEric Dumazet {
944f8d9d938SEric Dumazet 	if (unlikely(skb_zcopy_pure(skb))) {
945f8d9d938SEric Dumazet 		u32 extra = skb->truesize -
946f8d9d938SEric Dumazet 			    SKB_TRUESIZE(skb_end_offset(skb));
947f8d9d938SEric Dumazet 
948f8d9d938SEric Dumazet 		if (!sk_wmem_schedule(sk, extra))
949f8d9d938SEric Dumazet 			return -ENOMEM;
950f8d9d938SEric Dumazet 
951f8d9d938SEric Dumazet 		sk_mem_charge(sk, extra);
952f8d9d938SEric Dumazet 		skb_shinfo(skb)->flags &= ~SKBFL_PURE_ZEROCOPY;
953f8d9d938SEric Dumazet 	}
954f8d9d938SEric Dumazet 	return 0;
955f8d9d938SEric Dumazet }
956f8d9d938SEric Dumazet 
957849b425cSEric Dumazet 
958f54755f6SEric Dumazet static int tcp_wmem_schedule(struct sock *sk, int copy)
959f54755f6SEric Dumazet {
960f54755f6SEric Dumazet 	int left;
961f54755f6SEric Dumazet 
962f54755f6SEric Dumazet 	if (likely(sk_wmem_schedule(sk, copy)))
963f54755f6SEric Dumazet 		return copy;
964f54755f6SEric Dumazet 
965f54755f6SEric Dumazet 	/* We could be in trouble if we have nothing queued.
966f54755f6SEric Dumazet 	 * Use whatever is left in sk->sk_forward_alloc and tcp_wmem[0]
967f54755f6SEric Dumazet 	 * to guarantee some progress.
968f54755f6SEric Dumazet 	 */
969f54755f6SEric Dumazet 	left = sock_net(sk)->ipv4.sysctl_tcp_wmem[0] - sk->sk_wmem_queued;
970f54755f6SEric Dumazet 	if (left > 0)
971f54755f6SEric Dumazet 		sk_forced_mem_schedule(sk, min(left, copy));
972f54755f6SEric Dumazet 	return min(copy, sk->sk_forward_alloc);
973f54755f6SEric Dumazet }
974f54755f6SEric Dumazet 
975ff6fb083SPaolo Abeni static struct sk_buff *tcp_build_frag(struct sock *sk, int size_goal, int flags,
976b796d04bSPaolo Abeni 				      struct page *page, int offset, size_t *size)
977b796d04bSPaolo Abeni {
978b796d04bSPaolo Abeni 	struct sk_buff *skb = tcp_write_queue_tail(sk);
979b796d04bSPaolo Abeni 	struct tcp_sock *tp = tcp_sk(sk);
980b796d04bSPaolo Abeni 	bool can_coalesce;
981b796d04bSPaolo Abeni 	int copy, i;
982b796d04bSPaolo Abeni 
983b796d04bSPaolo Abeni 	if (!skb || (copy = size_goal - skb->len) <= 0 ||
984b796d04bSPaolo Abeni 	    !tcp_skb_can_collapse_to(skb)) {
985b796d04bSPaolo Abeni new_segment:
986b796d04bSPaolo Abeni 		if (!sk_stream_memory_free(sk))
987b796d04bSPaolo Abeni 			return NULL;
988b796d04bSPaolo Abeni 
989f8dd3b8dSEric Dumazet 		skb = tcp_stream_alloc_skb(sk, 0, sk->sk_allocation,
990b796d04bSPaolo Abeni 					   tcp_rtx_and_write_queues_empty(sk));
991b796d04bSPaolo Abeni 		if (!skb)
992b796d04bSPaolo Abeni 			return NULL;
993b796d04bSPaolo Abeni 
994b796d04bSPaolo Abeni #ifdef CONFIG_TLS_DEVICE
995b796d04bSPaolo Abeni 		skb->decrypted = !!(flags & MSG_SENDPAGE_DECRYPTED);
996b796d04bSPaolo Abeni #endif
99704d8825cSPaolo Abeni 		tcp_skb_entail(sk, skb);
998b796d04bSPaolo Abeni 		copy = size_goal;
999b796d04bSPaolo Abeni 	}
1000b796d04bSPaolo Abeni 
1001b796d04bSPaolo Abeni 	if (copy > *size)
1002b796d04bSPaolo Abeni 		copy = *size;
1003b796d04bSPaolo Abeni 
1004b796d04bSPaolo Abeni 	i = skb_shinfo(skb)->nr_frags;
1005b796d04bSPaolo Abeni 	can_coalesce = skb_can_coalesce(skb, i, page, offset);
1006657b991aSKuniyuki Iwashima 	if (!can_coalesce && i >= READ_ONCE(sysctl_max_skb_frags)) {
1007b796d04bSPaolo Abeni 		tcp_mark_push(tp, skb);
1008b796d04bSPaolo Abeni 		goto new_segment;
1009b796d04bSPaolo Abeni 	}
1010849b425cSEric Dumazet 	if (tcp_downgrade_zcopy_pure(sk, skb))
1011849b425cSEric Dumazet 		return NULL;
1012849b425cSEric Dumazet 
1013849b425cSEric Dumazet 	copy = tcp_wmem_schedule(sk, copy);
1014849b425cSEric Dumazet 	if (!copy)
1015b796d04bSPaolo Abeni 		return NULL;
1016b796d04bSPaolo Abeni 
1017b796d04bSPaolo Abeni 	if (can_coalesce) {
1018b796d04bSPaolo Abeni 		skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
1019b796d04bSPaolo Abeni 	} else {
1020b796d04bSPaolo Abeni 		get_page(page);
102132614006SEric Dumazet 		skb_fill_page_desc_noacc(skb, i, page, offset, copy);
1022b796d04bSPaolo Abeni 	}
1023b796d04bSPaolo Abeni 
1024b796d04bSPaolo Abeni 	if (!(flags & MSG_NO_SHARED_FRAGS))
102506b4feb3SJonathan Lemon 		skb_shinfo(skb)->flags |= SKBFL_SHARED_FRAG;
1026b796d04bSPaolo Abeni 
1027b796d04bSPaolo Abeni 	skb->len += copy;
1028b796d04bSPaolo Abeni 	skb->data_len += copy;
1029b796d04bSPaolo Abeni 	skb->truesize += copy;
1030b796d04bSPaolo Abeni 	sk_wmem_queued_add(sk, copy);
1031b796d04bSPaolo Abeni 	sk_mem_charge(sk, copy);
1032b796d04bSPaolo Abeni 	WRITE_ONCE(tp->write_seq, tp->write_seq + copy);
1033b796d04bSPaolo Abeni 	TCP_SKB_CB(skb)->end_seq += copy;
1034b796d04bSPaolo Abeni 	tcp_skb_pcount_set(skb, 0);
1035b796d04bSPaolo Abeni 
1036b796d04bSPaolo Abeni 	*size = copy;
1037b796d04bSPaolo Abeni 	return skb;
1038b796d04bSPaolo Abeni }
1039b796d04bSPaolo Abeni 
1040e3b5616aSDave Watson ssize_t do_tcp_sendpages(struct sock *sk, struct page *page, int offset,
104164022d0bSEric Dumazet 			 size_t size, int flags)
10421da177e4SLinus Torvalds {
10431da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
1044c1b4a7e6SDavid S. Miller 	int mss_now, size_goal;
10451da177e4SLinus Torvalds 	int err;
10461da177e4SLinus Torvalds 	ssize_t copied;
10471da177e4SLinus Torvalds 	long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
10481da177e4SLinus Torvalds 
1049a10674bfSVasily Averin 	if (IS_ENABLED(CONFIG_DEBUG_VM) &&
1050cf83a17eSColy Li 	    WARN_ONCE(!sendpage_ok(page),
1051cf83a17eSColy Li 		      "page must not be a Slab one and have page_count > 0"))
1052a10674bfSVasily Averin 		return -EINVAL;
1053a10674bfSVasily Averin 
10548336886fSJerry Chu 	/* Wait for a connection to finish. One exception is TCP Fast Open
10558336886fSJerry Chu 	 * (passive side) where data is allowed to be sent before a connection
10568336886fSJerry Chu 	 * is fully established.
10578336886fSJerry Chu 	 */
10588336886fSJerry Chu 	if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
10598336886fSJerry Chu 	    !tcp_passive_fastopen(sk)) {
1060686a5624SYuvaraja Mariappan 		err = sk_stream_wait_connect(sk, &timeo);
1061686a5624SYuvaraja Mariappan 		if (err != 0)
10621da177e4SLinus Torvalds 			goto out_err;
10638336886fSJerry Chu 	}
10641da177e4SLinus Torvalds 
10659cd3e072SEric Dumazet 	sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
10661da177e4SLinus Torvalds 
10670c54b85fSIlpo Järvinen 	mss_now = tcp_send_mss(sk, &size_goal, flags);
10681da177e4SLinus Torvalds 	copied = 0;
10691da177e4SLinus Torvalds 
10701da177e4SLinus Torvalds 	err = -EPIPE;
10711da177e4SLinus Torvalds 	if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
10720d6a775eSIlpo Järvinen 		goto out_err;
10731da177e4SLinus Torvalds 
107464022d0bSEric Dumazet 	while (size > 0) {
1075b796d04bSPaolo Abeni 		struct sk_buff *skb;
1076b796d04bSPaolo Abeni 		size_t copy = size;
10771da177e4SLinus Torvalds 
1078b796d04bSPaolo Abeni 		skb = tcp_build_frag(sk, size_goal, flags, page, offset, &copy);
10791da177e4SLinus Torvalds 		if (!skb)
1080afb83012SSoheil Hassas Yeganeh 			goto wait_for_space;
10811da177e4SLinus Torvalds 
10821da177e4SLinus Torvalds 		if (!copied)
10834de075e0SEric Dumazet 			TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
10841da177e4SLinus Torvalds 
10851da177e4SLinus Torvalds 		copied += copy;
108664022d0bSEric Dumazet 		offset += copy;
1087686a5624SYuvaraja Mariappan 		size -= copy;
1088ad02c4f5SSoheil Hassas Yeganeh 		if (!size)
10891da177e4SLinus Torvalds 			goto out;
10901da177e4SLinus Torvalds 
109169d15067SHerbert Xu 		if (skb->len < size_goal || (flags & MSG_OOB))
10921da177e4SLinus Torvalds 			continue;
10931da177e4SLinus Torvalds 
10941da177e4SLinus Torvalds 		if (forced_push(tp)) {
10951da177e4SLinus Torvalds 			tcp_mark_push(tp, skb);
10969e412ba7SIlpo Järvinen 			__tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
1097fe067e8aSDavid S. Miller 		} else if (skb == tcp_send_head(sk))
10981da177e4SLinus Torvalds 			tcp_push_one(sk, mss_now);
10991da177e4SLinus Torvalds 		continue;
11001da177e4SLinus Torvalds 
1101afb83012SSoheil Hassas Yeganeh wait_for_space:
11021da177e4SLinus Torvalds 		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1103f54b3111SEric Dumazet 		tcp_push(sk, flags & ~MSG_MORE, mss_now,
1104f54b3111SEric Dumazet 			 TCP_NAGLE_PUSH, size_goal);
11051da177e4SLinus Torvalds 
1106686a5624SYuvaraja Mariappan 		err = sk_stream_wait_memory(sk, &timeo);
1107686a5624SYuvaraja Mariappan 		if (err != 0)
11081da177e4SLinus Torvalds 			goto do_error;
11091da177e4SLinus Torvalds 
11100c54b85fSIlpo Järvinen 		mss_now = tcp_send_mss(sk, &size_goal, flags);
11111da177e4SLinus Torvalds 	}
11121da177e4SLinus Torvalds 
11131da177e4SLinus Torvalds out:
1114ad02c4f5SSoheil Hassas Yeganeh 	if (copied) {
11154e8cc228SEric Dumazet 		tcp_tx_timestamp(sk, sk->sk_tsflags);
1116ad02c4f5SSoheil Hassas Yeganeh 		if (!(flags & MSG_SENDPAGE_NOTLAST))
1117f54b3111SEric Dumazet 			tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
1118ad02c4f5SSoheil Hassas Yeganeh 	}
11191da177e4SLinus Torvalds 	return copied;
11201da177e4SLinus Torvalds 
11211da177e4SLinus Torvalds do_error:
112227728ba8SEric Dumazet 	tcp_remove_empty_skb(sk);
11231da177e4SLinus Torvalds 	if (copied)
11241da177e4SLinus Torvalds 		goto out;
11251da177e4SLinus Torvalds out_err:
1126ce5ec440SJason Baron 	/* make sure we wake any epoll edge trigger waiter */
1127216808c6SEric Dumazet 	if (unlikely(tcp_rtx_and_write_queues_empty(sk) && err == -EAGAIN)) {
1128ce5ec440SJason Baron 		sk->sk_write_space(sk);
1129b0f71bd3SFrancis Yan 		tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
1130b0f71bd3SFrancis Yan 	}
11311da177e4SLinus Torvalds 	return sk_stream_error(sk, flags, err);
11321da177e4SLinus Torvalds }
1133e3b5616aSDave Watson EXPORT_SYMBOL_GPL(do_tcp_sendpages);
11341da177e4SLinus Torvalds 
1135306b13ebSTom Herbert int tcp_sendpage_locked(struct sock *sk, struct page *page, int offset,
11361da177e4SLinus Torvalds 			size_t size, int flags)
11371da177e4SLinus Torvalds {
1138dead7cdbSEric Dumazet 	if (!(sk->sk_route_caps & NETIF_F_SG))
1139bd9dfc54SEric Dumazet 		return sock_no_sendpage_locked(sk, page, offset, size, flags);
11401da177e4SLinus Torvalds 
1141d7722e85SSoheil Hassas Yeganeh 	tcp_rate_check_app_limited(sk);  /* is sending application-limited? */
1142d7722e85SSoheil Hassas Yeganeh 
1143306b13ebSTom Herbert 	return do_tcp_sendpages(sk, page, offset, size, flags);
1144306b13ebSTom Herbert }
1145774c4673SDavid S. Miller EXPORT_SYMBOL_GPL(tcp_sendpage_locked);
1146306b13ebSTom Herbert 
1147306b13ebSTom Herbert int tcp_sendpage(struct sock *sk, struct page *page, int offset,
1148306b13ebSTom Herbert 		 size_t size, int flags)
1149306b13ebSTom Herbert {
1150306b13ebSTom Herbert 	int ret;
1151306b13ebSTom Herbert 
1152306b13ebSTom Herbert 	lock_sock(sk);
1153306b13ebSTom Herbert 	ret = tcp_sendpage_locked(sk, page, offset, size, flags);
11541da177e4SLinus Torvalds 	release_sock(sk);
1155306b13ebSTom Herbert 
1156306b13ebSTom Herbert 	return ret;
11571da177e4SLinus Torvalds }
11584bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_sendpage);
11591da177e4SLinus Torvalds 
1160cf60af03SYuchung Cheng void tcp_free_fastopen_req(struct tcp_sock *tp)
1161cf60af03SYuchung Cheng {
116200db4124SIan Morris 	if (tp->fastopen_req) {
1163cf60af03SYuchung Cheng 		kfree(tp->fastopen_req);
1164cf60af03SYuchung Cheng 		tp->fastopen_req = NULL;
1165cf60af03SYuchung Cheng 	}
1166cf60af03SYuchung Cheng }
1167cf60af03SYuchung Cheng 
11683242abebSBenjamin Hesmans int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg, int *copied,
11693242abebSBenjamin Hesmans 			 size_t size, struct ubuf_info *uarg)
1170cf60af03SYuchung Cheng {
1171cf60af03SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
117219f6d3f3SWei Wang 	struct inet_sock *inet = inet_sk(sk);
1173ba615f67SWei Wang 	struct sockaddr *uaddr = msg->msg_name;
1174cf60af03SYuchung Cheng 	int err, flags;
1175cf60af03SYuchung Cheng 
11765a542133SKuniyuki Iwashima 	if (!(READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_fastopen) &
11775a542133SKuniyuki Iwashima 	      TFO_CLIENT_ENABLE) ||
1178ba615f67SWei Wang 	    (uaddr && msg->msg_namelen >= sizeof(uaddr->sa_family) &&
1179ba615f67SWei Wang 	     uaddr->sa_family == AF_UNSPEC))
1180cf60af03SYuchung Cheng 		return -EOPNOTSUPP;
118100db4124SIan Morris 	if (tp->fastopen_req)
1182cf60af03SYuchung Cheng 		return -EALREADY; /* Another Fast Open is in progress */
1183cf60af03SYuchung Cheng 
1184cf60af03SYuchung Cheng 	tp->fastopen_req = kzalloc(sizeof(struct tcp_fastopen_request),
1185cf60af03SYuchung Cheng 				   sk->sk_allocation);
118651456b29SIan Morris 	if (unlikely(!tp->fastopen_req))
1187cf60af03SYuchung Cheng 		return -ENOBUFS;
1188cf60af03SYuchung Cheng 	tp->fastopen_req->data = msg;
1189f5ddcbbbSEric Dumazet 	tp->fastopen_req->size = size;
1190f859a448SWillem de Bruijn 	tp->fastopen_req->uarg = uarg;
1191cf60af03SYuchung Cheng 
119219f6d3f3SWei Wang 	if (inet->defer_connect) {
119319f6d3f3SWei Wang 		err = tcp_connect(sk);
119419f6d3f3SWei Wang 		/* Same failure procedure as in tcp_v4/6_connect */
119519f6d3f3SWei Wang 		if (err) {
119619f6d3f3SWei Wang 			tcp_set_state(sk, TCP_CLOSE);
119719f6d3f3SWei Wang 			inet->inet_dport = 0;
119819f6d3f3SWei Wang 			sk->sk_route_caps = 0;
119919f6d3f3SWei Wang 		}
120019f6d3f3SWei Wang 	}
1201cf60af03SYuchung Cheng 	flags = (msg->msg_flags & MSG_DONTWAIT) ? O_NONBLOCK : 0;
1202ba615f67SWei Wang 	err = __inet_stream_connect(sk->sk_socket, uaddr,
12033979ad7eSWilly Tarreau 				    msg->msg_namelen, flags, 1);
12047db92362SWei Wang 	/* fastopen_req could already be freed in __inet_stream_connect
12057db92362SWei Wang 	 * if the connection times out or gets rst
12067db92362SWei Wang 	 */
12077db92362SWei Wang 	if (tp->fastopen_req) {
1208f5ddcbbbSEric Dumazet 		*copied = tp->fastopen_req->copied;
1209cf60af03SYuchung Cheng 		tcp_free_fastopen_req(tp);
12107db92362SWei Wang 		inet->defer_connect = 0;
12117db92362SWei Wang 	}
1212cf60af03SYuchung Cheng 	return err;
1213cf60af03SYuchung Cheng }
1214cf60af03SYuchung Cheng 
1215306b13ebSTom Herbert int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
12161da177e4SLinus Torvalds {
12171da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
1218f214f915SWillem de Bruijn 	struct ubuf_info *uarg = NULL;
12191da177e4SLinus Torvalds 	struct sk_buff *skb;
1220c14ac945SSoheil Hassas Yeganeh 	struct sockcm_cookie sockc;
122157be5bdaSAl Viro 	int flags, err, copied = 0;
122257be5bdaSAl Viro 	int mss_now = 0, size_goal, copied_syn = 0;
12231a991488SEric Dumazet 	int process_backlog = 0;
122474d4a8f8SEric Dumazet 	bool zc = false;
12251da177e4SLinus Torvalds 	long timeo;
12261da177e4SLinus Torvalds 
12271da177e4SLinus Torvalds 	flags = msg->msg_flags;
1228f214f915SWillem de Bruijn 
1229eb315a7dSPavel Begunkov 	if ((flags & MSG_ZEROCOPY) && size) {
123075c119afSEric Dumazet 		skb = tcp_write_queue_tail(sk);
1231eb315a7dSPavel Begunkov 
1232eb315a7dSPavel Begunkov 		if (msg->msg_ubuf) {
1233eb315a7dSPavel Begunkov 			uarg = msg->msg_ubuf;
1234eb315a7dSPavel Begunkov 			net_zcopy_get(uarg);
1235eb315a7dSPavel Begunkov 			zc = sk->sk_route_caps & NETIF_F_SG;
1236eb315a7dSPavel Begunkov 		} else if (sock_flag(sk, SOCK_ZEROCOPY)) {
12378c793822SJonathan Lemon 			uarg = msg_zerocopy_realloc(sk, size, skb_zcopy(skb));
1238f214f915SWillem de Bruijn 			if (!uarg) {
1239f214f915SWillem de Bruijn 				err = -ENOBUFS;
1240f214f915SWillem de Bruijn 				goto out_err;
1241f214f915SWillem de Bruijn 			}
1242dead7cdbSEric Dumazet 			zc = sk->sk_route_caps & NETIF_F_SG;
124302583adeSWillem de Bruijn 			if (!zc)
1244e7d2b510SPavel Begunkov 				uarg_to_msgzc(uarg)->zerocopy = 0;
1245f214f915SWillem de Bruijn 		}
1246eb315a7dSPavel Begunkov 	}
1247f214f915SWillem de Bruijn 
124816ae6aa1SYuchung Cheng 	if (unlikely(flags & MSG_FASTOPEN || inet_sk(sk)->defer_connect) &&
124916ae6aa1SYuchung Cheng 	    !tp->repair) {
1250f859a448SWillem de Bruijn 		err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size, uarg);
1251cf60af03SYuchung Cheng 		if (err == -EINPROGRESS && copied_syn > 0)
1252cf60af03SYuchung Cheng 			goto out;
1253cf60af03SYuchung Cheng 		else if (err)
1254cf60af03SYuchung Cheng 			goto out_err;
1255cf60af03SYuchung Cheng 	}
1256cf60af03SYuchung Cheng 
12571da177e4SLinus Torvalds 	timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
12581da177e4SLinus Torvalds 
1259d7722e85SSoheil Hassas Yeganeh 	tcp_rate_check_app_limited(sk);  /* is sending application-limited? */
1260d7722e85SSoheil Hassas Yeganeh 
12618336886fSJerry Chu 	/* Wait for a connection to finish. One exception is TCP Fast Open
12628336886fSJerry Chu 	 * (passive side) where data is allowed to be sent before a connection
12638336886fSJerry Chu 	 * is fully established.
12648336886fSJerry Chu 	 */
12658336886fSJerry Chu 	if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
12668336886fSJerry Chu 	    !tcp_passive_fastopen(sk)) {
1267686a5624SYuvaraja Mariappan 		err = sk_stream_wait_connect(sk, &timeo);
1268686a5624SYuvaraja Mariappan 		if (err != 0)
1269cf60af03SYuchung Cheng 			goto do_error;
12708336886fSJerry Chu 	}
12711da177e4SLinus Torvalds 
1272c0e88ff0SPavel Emelyanov 	if (unlikely(tp->repair)) {
1273c0e88ff0SPavel Emelyanov 		if (tp->repair_queue == TCP_RECV_QUEUE) {
1274c0e88ff0SPavel Emelyanov 			copied = tcp_send_rcvq(sk, msg, size);
12755924f17aSChristoph Paasch 			goto out_nopush;
1276c0e88ff0SPavel Emelyanov 		}
1277c0e88ff0SPavel Emelyanov 
1278c0e88ff0SPavel Emelyanov 		err = -EINVAL;
1279c0e88ff0SPavel Emelyanov 		if (tp->repair_queue == TCP_NO_QUEUE)
1280c0e88ff0SPavel Emelyanov 			goto out_err;
1281c0e88ff0SPavel Emelyanov 
1282c0e88ff0SPavel Emelyanov 		/* 'common' sending to sendq */
1283c0e88ff0SPavel Emelyanov 	}
1284c0e88ff0SPavel Emelyanov 
1285657a0667SWillem de Bruijn 	sockcm_init(&sockc, sk);
1286c14ac945SSoheil Hassas Yeganeh 	if (msg->msg_controllen) {
1287c14ac945SSoheil Hassas Yeganeh 		err = sock_cmsg_send(sk, msg, &sockc);
1288c14ac945SSoheil Hassas Yeganeh 		if (unlikely(err)) {
1289c14ac945SSoheil Hassas Yeganeh 			err = -EINVAL;
1290c14ac945SSoheil Hassas Yeganeh 			goto out_err;
1291c14ac945SSoheil Hassas Yeganeh 		}
1292c14ac945SSoheil Hassas Yeganeh 	}
1293c14ac945SSoheil Hassas Yeganeh 
12941da177e4SLinus Torvalds 	/* This should be in poll */
12959cd3e072SEric Dumazet 	sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
12961da177e4SLinus Torvalds 
12971da177e4SLinus Torvalds 	/* Ok commence sending. */
12981da177e4SLinus Torvalds 	copied = 0;
12991da177e4SLinus Torvalds 
1300d41a69f1SEric Dumazet restart:
1301d41a69f1SEric Dumazet 	mss_now = tcp_send_mss(sk, &size_goal, flags);
1302d41a69f1SEric Dumazet 
13031da177e4SLinus Torvalds 	err = -EPIPE;
13041da177e4SLinus Torvalds 	if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
130579d8665bSEric Dumazet 		goto do_error;
13061da177e4SLinus Torvalds 
130701e97e65SAl Viro 	while (msg_data_left(msg)) {
13086828b92bSHerbert Xu 		int copy = 0;
13091da177e4SLinus Torvalds 
1310fe067e8aSDavid S. Miller 		skb = tcp_write_queue_tail(sk);
131165ec6097SEric Dumazet 		if (skb)
131265ec6097SEric Dumazet 			copy = size_goal - skb->len;
13131da177e4SLinus Torvalds 
1314c134ecb8SMartin KaFai Lau 		if (copy <= 0 || !tcp_skb_can_collapse_to(skb)) {
13153613b3dbSEric Dumazet 			bool first_skb;
13163613b3dbSEric Dumazet 
13171da177e4SLinus Torvalds new_segment:
13181da177e4SLinus Torvalds 			if (!sk_stream_memory_free(sk))
1319afb83012SSoheil Hassas Yeganeh 				goto wait_for_space;
13201da177e4SLinus Torvalds 
13211a991488SEric Dumazet 			if (unlikely(process_backlog >= 16)) {
13221a991488SEric Dumazet 				process_backlog = 0;
13231a991488SEric Dumazet 				if (sk_flush_backlog(sk))
1324d41a69f1SEric Dumazet 					goto restart;
1325d4011239SEric Dumazet 			}
132675c119afSEric Dumazet 			first_skb = tcp_rtx_and_write_queues_empty(sk);
1327f8dd3b8dSEric Dumazet 			skb = tcp_stream_alloc_skb(sk, 0, sk->sk_allocation,
13283613b3dbSEric Dumazet 						   first_skb);
13291da177e4SLinus Torvalds 			if (!skb)
1330afb83012SSoheil Hassas Yeganeh 				goto wait_for_space;
13311da177e4SLinus Torvalds 
13321a991488SEric Dumazet 			process_backlog++;
13331da177e4SLinus Torvalds 
133404d8825cSPaolo Abeni 			tcp_skb_entail(sk, skb);
1335c1b4a7e6SDavid S. Miller 			copy = size_goal;
13369d186cacSAndrey Vagin 
13379d186cacSAndrey Vagin 			/* All packets are restored as if they have
1338d3edd06eSEric Dumazet 			 * already been sent. skb_mstamp_ns isn't set to
13399d186cacSAndrey Vagin 			 * avoid wrong rtt estimation.
13409d186cacSAndrey Vagin 			 */
13419d186cacSAndrey Vagin 			if (tp->repair)
13429d186cacSAndrey Vagin 				TCP_SKB_CB(skb)->sacked |= TCPCB_REPAIRED;
13431da177e4SLinus Torvalds 		}
13441da177e4SLinus Torvalds 
13451da177e4SLinus Torvalds 		/* Try to append data to the end of skb. */
134601e97e65SAl Viro 		if (copy > msg_data_left(msg))
134701e97e65SAl Viro 			copy = msg_data_left(msg);
13481da177e4SLinus Torvalds 
13493ded97bcSEric Dumazet 		if (!zc) {
13505640f768SEric Dumazet 			bool merge = true;
13511da177e4SLinus Torvalds 			int i = skb_shinfo(skb)->nr_frags;
13525640f768SEric Dumazet 			struct page_frag *pfrag = sk_page_frag(sk);
1353761965eaSEric Dumazet 
13545640f768SEric Dumazet 			if (!sk_page_frag_refill(sk, pfrag))
1355afb83012SSoheil Hassas Yeganeh 				goto wait_for_space;
1356761965eaSEric Dumazet 
13575640f768SEric Dumazet 			if (!skb_can_coalesce(skb, i, pfrag->page,
13585640f768SEric Dumazet 					      pfrag->offset)) {
1359657b991aSKuniyuki Iwashima 				if (i >= READ_ONCE(sysctl_max_skb_frags)) {
13601da177e4SLinus Torvalds 					tcp_mark_push(tp, skb);
13611da177e4SLinus Torvalds 					goto new_segment;
13621da177e4SLinus Torvalds 				}
13635640f768SEric Dumazet 				merge = false;
13645640f768SEric Dumazet 			}
1365ef015786SHerbert Xu 
13665640f768SEric Dumazet 			copy = min_t(int, copy, pfrag->size - pfrag->offset);
1367ef015786SHerbert Xu 
1368eb315a7dSPavel Begunkov 			if (unlikely(skb_zcopy_pure(skb) || skb_zcopy_managed(skb))) {
1369849b425cSEric Dumazet 				if (tcp_downgrade_zcopy_pure(sk, skb))
1370849b425cSEric Dumazet 					goto wait_for_space;
1371eb315a7dSPavel Begunkov 				skb_zcopy_downgrade_managed(skb);
1372eb315a7dSPavel Begunkov 			}
1373849b425cSEric Dumazet 
1374849b425cSEric Dumazet 			copy = tcp_wmem_schedule(sk, copy);
1375849b425cSEric Dumazet 			if (!copy)
1376afb83012SSoheil Hassas Yeganeh 				goto wait_for_space;
13771da177e4SLinus Torvalds 
137857be5bdaSAl Viro 			err = skb_copy_to_page_nocache(sk, &msg->msg_iter, skb,
13795640f768SEric Dumazet 						       pfrag->page,
13805640f768SEric Dumazet 						       pfrag->offset,
13815640f768SEric Dumazet 						       copy);
13825640f768SEric Dumazet 			if (err)
13831da177e4SLinus Torvalds 				goto do_error;
13841da177e4SLinus Torvalds 
13851da177e4SLinus Torvalds 			/* Update the skb. */
13861da177e4SLinus Torvalds 			if (merge) {
13879e903e08SEric Dumazet 				skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
13881da177e4SLinus Torvalds 			} else {
13895640f768SEric Dumazet 				skb_fill_page_desc(skb, i, pfrag->page,
13905640f768SEric Dumazet 						   pfrag->offset, copy);
13914e33e346SEric Dumazet 				page_ref_inc(pfrag->page);
13921da177e4SLinus Torvalds 			}
13935640f768SEric Dumazet 			pfrag->offset += copy;
1394f214f915SWillem de Bruijn 		} else {
13959b65b17dSTalal Ahmad 			/* First append to a fragless skb builds initial
13969b65b17dSTalal Ahmad 			 * pure zerocopy skb
13979b65b17dSTalal Ahmad 			 */
13989b65b17dSTalal Ahmad 			if (!skb->len)
13999b65b17dSTalal Ahmad 				skb_shinfo(skb)->flags |= SKBFL_PURE_ZEROCOPY;
14009b65b17dSTalal Ahmad 
14019b65b17dSTalal Ahmad 			if (!skb_zcopy_pure(skb)) {
1402849b425cSEric Dumazet 				copy = tcp_wmem_schedule(sk, copy);
1403849b425cSEric Dumazet 				if (!copy)
1404358ed624STalal Ahmad 					goto wait_for_space;
14059b65b17dSTalal Ahmad 			}
1406358ed624STalal Ahmad 
1407f214f915SWillem de Bruijn 			err = skb_zerocopy_iter_stream(sk, skb, msg, copy, uarg);
1408111856c7SWillem de Bruijn 			if (err == -EMSGSIZE || err == -EEXIST) {
1409111856c7SWillem de Bruijn 				tcp_mark_push(tp, skb);
1410f214f915SWillem de Bruijn 				goto new_segment;
1411111856c7SWillem de Bruijn 			}
1412f214f915SWillem de Bruijn 			if (err < 0)
1413f214f915SWillem de Bruijn 				goto do_error;
1414f214f915SWillem de Bruijn 			copy = err;
14151da177e4SLinus Torvalds 		}
14161da177e4SLinus Torvalds 
14171da177e4SLinus Torvalds 		if (!copied)
14184de075e0SEric Dumazet 			TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
14191da177e4SLinus Torvalds 
14200f317464SEric Dumazet 		WRITE_ONCE(tp->write_seq, tp->write_seq + copy);
14211da177e4SLinus Torvalds 		TCP_SKB_CB(skb)->end_seq += copy;
1422cd7d8498SEric Dumazet 		tcp_skb_pcount_set(skb, 0);
14231da177e4SLinus Torvalds 
14241da177e4SLinus Torvalds 		copied += copy;
142501e97e65SAl Viro 		if (!msg_data_left(msg)) {
1426c134ecb8SMartin KaFai Lau 			if (unlikely(flags & MSG_EOR))
1427c134ecb8SMartin KaFai Lau 				TCP_SKB_CB(skb)->eor = 1;
14281da177e4SLinus Torvalds 			goto out;
14294ed2d765SWillem de Bruijn 		}
14301da177e4SLinus Torvalds 
143165ec6097SEric Dumazet 		if (skb->len < size_goal || (flags & MSG_OOB) || unlikely(tp->repair))
14321da177e4SLinus Torvalds 			continue;
14331da177e4SLinus Torvalds 
14341da177e4SLinus Torvalds 		if (forced_push(tp)) {
14351da177e4SLinus Torvalds 			tcp_mark_push(tp, skb);
14369e412ba7SIlpo Järvinen 			__tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
1437fe067e8aSDavid S. Miller 		} else if (skb == tcp_send_head(sk))
14381da177e4SLinus Torvalds 			tcp_push_one(sk, mss_now);
14391da177e4SLinus Torvalds 		continue;
14401da177e4SLinus Torvalds 
1441afb83012SSoheil Hassas Yeganeh wait_for_space:
14421da177e4SLinus Torvalds 		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1443ec342325SAndrew Vagin 		if (copied)
1444f54b3111SEric Dumazet 			tcp_push(sk, flags & ~MSG_MORE, mss_now,
1445f54b3111SEric Dumazet 				 TCP_NAGLE_PUSH, size_goal);
14461da177e4SLinus Torvalds 
1447686a5624SYuvaraja Mariappan 		err = sk_stream_wait_memory(sk, &timeo);
1448686a5624SYuvaraja Mariappan 		if (err != 0)
14491da177e4SLinus Torvalds 			goto do_error;
14501da177e4SLinus Torvalds 
14510c54b85fSIlpo Järvinen 		mss_now = tcp_send_mss(sk, &size_goal, flags);
14521da177e4SLinus Torvalds 	}
14531da177e4SLinus Torvalds 
14541da177e4SLinus Torvalds out:
1455ad02c4f5SSoheil Hassas Yeganeh 	if (copied) {
14564e8cc228SEric Dumazet 		tcp_tx_timestamp(sk, sockc.tsflags);
1457f54b3111SEric Dumazet 		tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
1458ad02c4f5SSoheil Hassas Yeganeh 	}
14595924f17aSChristoph Paasch out_nopush:
14608e044917SJonathan Lemon 	net_zcopy_put(uarg);
1461cf60af03SYuchung Cheng 	return copied + copied_syn;
14621da177e4SLinus Torvalds 
14631da177e4SLinus Torvalds do_error:
146427728ba8SEric Dumazet 	tcp_remove_empty_skb(sk);
1465fdfc5c85SEric Dumazet 
1466cf60af03SYuchung Cheng 	if (copied + copied_syn)
14671da177e4SLinus Torvalds 		goto out;
14681da177e4SLinus Torvalds out_err:
14698e044917SJonathan Lemon 	net_zcopy_put_abort(uarg, true);
14701da177e4SLinus Torvalds 	err = sk_stream_error(sk, flags, err);
1471ce5ec440SJason Baron 	/* make sure we wake any epoll edge trigger waiter */
1472216808c6SEric Dumazet 	if (unlikely(tcp_rtx_and_write_queues_empty(sk) && err == -EAGAIN)) {
1473ce5ec440SJason Baron 		sk->sk_write_space(sk);
1474b0f71bd3SFrancis Yan 		tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
1475b0f71bd3SFrancis Yan 	}
14761da177e4SLinus Torvalds 	return err;
14771da177e4SLinus Torvalds }
1478774c4673SDavid S. Miller EXPORT_SYMBOL_GPL(tcp_sendmsg_locked);
1479306b13ebSTom Herbert 
1480306b13ebSTom Herbert int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
1481306b13ebSTom Herbert {
1482306b13ebSTom Herbert 	int ret;
1483306b13ebSTom Herbert 
1484306b13ebSTom Herbert 	lock_sock(sk);
1485306b13ebSTom Herbert 	ret = tcp_sendmsg_locked(sk, msg, size);
1486306b13ebSTom Herbert 	release_sock(sk);
1487306b13ebSTom Herbert 
1488306b13ebSTom Herbert 	return ret;
1489306b13ebSTom Herbert }
14904bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_sendmsg);
14911da177e4SLinus Torvalds 
14921da177e4SLinus Torvalds /*
14931da177e4SLinus Torvalds  *	Handle reading urgent data. BSD has very simple semantics for
14941da177e4SLinus Torvalds  *	this, no blocking and very strange errors 8)
14951da177e4SLinus Torvalds  */
14961da177e4SLinus Torvalds 
1497377f0a08SRami Rosen static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags)
14981da177e4SLinus Torvalds {
14991da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
15001da177e4SLinus Torvalds 
15011da177e4SLinus Torvalds 	/* No URG data to read. */
15021da177e4SLinus Torvalds 	if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
15031da177e4SLinus Torvalds 	    tp->urg_data == TCP_URG_READ)
15041da177e4SLinus Torvalds 		return -EINVAL;	/* Yes this is right ! */
15051da177e4SLinus Torvalds 
15061da177e4SLinus Torvalds 	if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
15071da177e4SLinus Torvalds 		return -ENOTCONN;
15081da177e4SLinus Torvalds 
15091da177e4SLinus Torvalds 	if (tp->urg_data & TCP_URG_VALID) {
15101da177e4SLinus Torvalds 		int err = 0;
15111da177e4SLinus Torvalds 		char c = tp->urg_data;
15121da177e4SLinus Torvalds 
15131da177e4SLinus Torvalds 		if (!(flags & MSG_PEEK))
15147b6a893aSEric Dumazet 			WRITE_ONCE(tp->urg_data, TCP_URG_READ);
15151da177e4SLinus Torvalds 
15161da177e4SLinus Torvalds 		/* Read urgent data. */
15171da177e4SLinus Torvalds 		msg->msg_flags |= MSG_OOB;
15181da177e4SLinus Torvalds 
15191da177e4SLinus Torvalds 		if (len > 0) {
15201da177e4SLinus Torvalds 			if (!(flags & MSG_TRUNC))
15217eab8d9eSAl Viro 				err = memcpy_to_msg(msg, &c, 1);
15221da177e4SLinus Torvalds 			len = 1;
15231da177e4SLinus Torvalds 		} else
15241da177e4SLinus Torvalds 			msg->msg_flags |= MSG_TRUNC;
15251da177e4SLinus Torvalds 
15261da177e4SLinus Torvalds 		return err ? -EFAULT : len;
15271da177e4SLinus Torvalds 	}
15281da177e4SLinus Torvalds 
15291da177e4SLinus Torvalds 	if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
15301da177e4SLinus Torvalds 		return 0;
15311da177e4SLinus Torvalds 
15321da177e4SLinus Torvalds 	/* Fixed the recv(..., MSG_OOB) behaviour.  BSD docs and
15331da177e4SLinus Torvalds 	 * the available implementations agree in this case:
15341da177e4SLinus Torvalds 	 * this call should never block, independent of the
15351da177e4SLinus Torvalds 	 * blocking state of the socket.
15361da177e4SLinus Torvalds 	 * Mike <pall@rz.uni-karlsruhe.de>
15371da177e4SLinus Torvalds 	 */
15381da177e4SLinus Torvalds 	return -EAGAIN;
15391da177e4SLinus Torvalds }
15401da177e4SLinus Torvalds 
1541c0e88ff0SPavel Emelyanov static int tcp_peek_sndq(struct sock *sk, struct msghdr *msg, int len)
1542c0e88ff0SPavel Emelyanov {
1543c0e88ff0SPavel Emelyanov 	struct sk_buff *skb;
1544c0e88ff0SPavel Emelyanov 	int copied = 0, err = 0;
1545c0e88ff0SPavel Emelyanov 
1546c0e88ff0SPavel Emelyanov 	/* XXX -- need to support SO_PEEK_OFF */
1547c0e88ff0SPavel Emelyanov 
154875c119afSEric Dumazet 	skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
154975c119afSEric Dumazet 		err = skb_copy_datagram_msg(skb, 0, msg, skb->len);
155075c119afSEric Dumazet 		if (err)
155175c119afSEric Dumazet 			return err;
155275c119afSEric Dumazet 		copied += skb->len;
155375c119afSEric Dumazet 	}
155475c119afSEric Dumazet 
1555c0e88ff0SPavel Emelyanov 	skb_queue_walk(&sk->sk_write_queue, skb) {
155651f3d02bSDavid S. Miller 		err = skb_copy_datagram_msg(skb, 0, msg, skb->len);
1557c0e88ff0SPavel Emelyanov 		if (err)
1558c0e88ff0SPavel Emelyanov 			break;
1559c0e88ff0SPavel Emelyanov 
1560c0e88ff0SPavel Emelyanov 		copied += skb->len;
1561c0e88ff0SPavel Emelyanov 	}
1562c0e88ff0SPavel Emelyanov 
1563c0e88ff0SPavel Emelyanov 	return err ?: copied;
1564c0e88ff0SPavel Emelyanov }
1565c0e88ff0SPavel Emelyanov 
15661da177e4SLinus Torvalds /* Clean up the receive buffer for full frames taken by the user,
15671da177e4SLinus Torvalds  * then send an ACK if necessary.  COPIED is the number of bytes
15681da177e4SLinus Torvalds  * tcp_recvmsg has given to the user so far, it speeds up the
15691da177e4SLinus Torvalds  * calculation of whether or not we must ACK for the sake of
15701da177e4SLinus Torvalds  * a window update.
15711da177e4SLinus Torvalds  */
1572c457985aSCong Wang static void __tcp_cleanup_rbuf(struct sock *sk, int copied)
15731da177e4SLinus Torvalds {
15741da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
1575a2a385d6SEric Dumazet 	bool time_to_ack = false;
15761da177e4SLinus Torvalds 
1577463c84b9SArnaldo Carvalho de Melo 	if (inet_csk_ack_scheduled(sk)) {
1578463c84b9SArnaldo Carvalho de Melo 		const struct inet_connection_sock *icsk = inet_csk(sk);
1579b6b6d653SEric Dumazet 
1580b6b6d653SEric Dumazet 		if (/* Once-per-two-segments ACK was not sent by tcp_input.c */
1581463c84b9SArnaldo Carvalho de Melo 		    tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss ||
15821da177e4SLinus Torvalds 		    /*
15831da177e4SLinus Torvalds 		     * If this read emptied read buffer, we send ACK, if
15841da177e4SLinus Torvalds 		     * connection is not bidirectional, user drained
15851da177e4SLinus Torvalds 		     * receive buffer and there was a small segment
15861da177e4SLinus Torvalds 		     * in queue.
15871da177e4SLinus Torvalds 		     */
15881ef9696cSAlexey Kuznetsov 		    (copied > 0 &&
15891ef9696cSAlexey Kuznetsov 		     ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
15901ef9696cSAlexey Kuznetsov 		      ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
159131954cd8SWei Wang 		       !inet_csk_in_pingpong_mode(sk))) &&
15921ef9696cSAlexey Kuznetsov 		      !atomic_read(&sk->sk_rmem_alloc)))
1593a2a385d6SEric Dumazet 			time_to_ack = true;
15941da177e4SLinus Torvalds 	}
15951da177e4SLinus Torvalds 
15961da177e4SLinus Torvalds 	/* We send an ACK if we can now advertise a non-zero window
15971da177e4SLinus Torvalds 	 * which has been raised "significantly".
15981da177e4SLinus Torvalds 	 *
15991da177e4SLinus Torvalds 	 * Even if window raised up to infinity, do not send window open ACK
16001da177e4SLinus Torvalds 	 * in states, where we will not receive more. It is useless.
16011da177e4SLinus Torvalds 	 */
16021da177e4SLinus Torvalds 	if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
16031da177e4SLinus Torvalds 		__u32 rcv_window_now = tcp_receive_window(tp);
16041da177e4SLinus Torvalds 
16051da177e4SLinus Torvalds 		/* Optimize, __tcp_select_window() is not cheap. */
16061da177e4SLinus Torvalds 		if (2*rcv_window_now <= tp->window_clamp) {
16071da177e4SLinus Torvalds 			__u32 new_window = __tcp_select_window(sk);
16081da177e4SLinus Torvalds 
16091da177e4SLinus Torvalds 			/* Send ACK now, if this read freed lots of space
16101da177e4SLinus Torvalds 			 * in our buffer. Certainly, new_window is new window.
16111da177e4SLinus Torvalds 			 * We can advertise it now, if it is not less than current one.
16121da177e4SLinus Torvalds 			 * "Lots" means "at least twice" here.
16131da177e4SLinus Torvalds 			 */
16141da177e4SLinus Torvalds 			if (new_window && new_window >= 2 * rcv_window_now)
1615a2a385d6SEric Dumazet 				time_to_ack = true;
16161da177e4SLinus Torvalds 		}
16171da177e4SLinus Torvalds 	}
16181da177e4SLinus Torvalds 	if (time_to_ack)
16191da177e4SLinus Torvalds 		tcp_send_ack(sk);
16201da177e4SLinus Torvalds }
16211da177e4SLinus Torvalds 
1622c457985aSCong Wang void tcp_cleanup_rbuf(struct sock *sk, int copied)
1623c457985aSCong Wang {
1624c457985aSCong Wang 	struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
1625c457985aSCong Wang 	struct tcp_sock *tp = tcp_sk(sk);
1626c457985aSCong Wang 
1627c457985aSCong Wang 	WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq),
1628c457985aSCong Wang 	     "cleanup rbuf bug: copied %X seq %X rcvnxt %X\n",
1629c457985aSCong Wang 	     tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt);
1630c457985aSCong Wang 	__tcp_cleanup_rbuf(sk, copied);
1631c457985aSCong Wang }
1632c457985aSCong Wang 
16333df684c1SEric Dumazet static void tcp_eat_recv_skb(struct sock *sk, struct sk_buff *skb)
16343df684c1SEric Dumazet {
1635f35f8219SEric Dumazet 	__skb_unlink(skb, &sk->sk_receive_queue);
16363df684c1SEric Dumazet 	if (likely(skb->destructor == sock_rfree)) {
16373df684c1SEric Dumazet 		sock_rfree(skb);
16383df684c1SEric Dumazet 		skb->destructor = NULL;
16393df684c1SEric Dumazet 		skb->sk = NULL;
164068822bdfSEric Dumazet 		return skb_attempt_defer_free(skb);
1641f35f8219SEric Dumazet 	}
1642f35f8219SEric Dumazet 	__kfree_skb(skb);
16433df684c1SEric Dumazet }
16443df684c1SEric Dumazet 
16453f92a64eSJakub Kicinski struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
16461da177e4SLinus Torvalds {
16471da177e4SLinus Torvalds 	struct sk_buff *skb;
16481da177e4SLinus Torvalds 	u32 offset;
16491da177e4SLinus Torvalds 
1650f26845b4SEric Dumazet 	while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
16511da177e4SLinus Torvalds 		offset = seq - TCP_SKB_CB(skb)->seq;
16529d691539SEric Dumazet 		if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
16539d691539SEric Dumazet 			pr_err_once("%s: found a SYN, please report !\n", __func__);
16541da177e4SLinus Torvalds 			offset--;
16559d691539SEric Dumazet 		}
1656e11ecddfSEric Dumazet 		if (offset < skb->len || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)) {
16571da177e4SLinus Torvalds 			*off = offset;
16581da177e4SLinus Torvalds 			return skb;
16591da177e4SLinus Torvalds 		}
1660f26845b4SEric Dumazet 		/* This looks weird, but this can happen if TCP collapsing
1661f26845b4SEric Dumazet 		 * splitted a fat GRO packet, while we released socket lock
1662f26845b4SEric Dumazet 		 * in skb_splice_bits()
1663f26845b4SEric Dumazet 		 */
16643df684c1SEric Dumazet 		tcp_eat_recv_skb(sk, skb);
16651da177e4SLinus Torvalds 	}
16661da177e4SLinus Torvalds 	return NULL;
16671da177e4SLinus Torvalds }
16683f92a64eSJakub Kicinski EXPORT_SYMBOL(tcp_recv_skb);
16691da177e4SLinus Torvalds 
16701da177e4SLinus Torvalds /*
16711da177e4SLinus Torvalds  * This routine provides an alternative to tcp_recvmsg() for routines
16721da177e4SLinus Torvalds  * that would like to handle copying from skbuffs directly in 'sendfile'
16731da177e4SLinus Torvalds  * fashion.
16741da177e4SLinus Torvalds  * Note:
16751da177e4SLinus Torvalds  *	- It is assumed that the socket was locked by the caller.
16761da177e4SLinus Torvalds  *	- The routine does not block.
16771da177e4SLinus Torvalds  *	- At present, there is no support for reading OOB data
16781da177e4SLinus Torvalds  *	  or for 'peeking' the socket using this routine
16791da177e4SLinus Torvalds  *	  (although both would be easy to implement).
16801da177e4SLinus Torvalds  */
16811da177e4SLinus Torvalds int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
16821da177e4SLinus Torvalds 		  sk_read_actor_t recv_actor)
16831da177e4SLinus Torvalds {
16841da177e4SLinus Torvalds 	struct sk_buff *skb;
16851da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
16861da177e4SLinus Torvalds 	u32 seq = tp->copied_seq;
16871da177e4SLinus Torvalds 	u32 offset;
16881da177e4SLinus Torvalds 	int copied = 0;
16891da177e4SLinus Torvalds 
16901da177e4SLinus Torvalds 	if (sk->sk_state == TCP_LISTEN)
16911da177e4SLinus Torvalds 		return -ENOTCONN;
16921da177e4SLinus Torvalds 	while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
16931da177e4SLinus Torvalds 		if (offset < skb->len) {
1694374e7b59SOctavian Purdila 			int used;
1695374e7b59SOctavian Purdila 			size_t len;
16961da177e4SLinus Torvalds 
16971da177e4SLinus Torvalds 			len = skb->len - offset;
16981da177e4SLinus Torvalds 			/* Stop reading if we hit a patch of urgent data */
1699b96c51bdSEric Dumazet 			if (unlikely(tp->urg_data)) {
17001da177e4SLinus Torvalds 				u32 urg_offset = tp->urg_seq - seq;
17011da177e4SLinus Torvalds 				if (urg_offset < len)
17021da177e4SLinus Torvalds 					len = urg_offset;
17031da177e4SLinus Torvalds 				if (!len)
17041da177e4SLinus Torvalds 					break;
17051da177e4SLinus Torvalds 			}
17061da177e4SLinus Torvalds 			used = recv_actor(desc, skb, offset, len);
1707ff905b1eSEric Dumazet 			if (used <= 0) {
1708ddb61a57SJens Axboe 				if (!copied)
1709ddb61a57SJens Axboe 					copied = used;
1710ddb61a57SJens Axboe 				break;
1711e3d5ea2cSEric Dumazet 			}
1712e3d5ea2cSEric Dumazet 			if (WARN_ON_ONCE(used > len))
1713e3d5ea2cSEric Dumazet 				used = len;
17141da177e4SLinus Torvalds 			seq += used;
17151da177e4SLinus Torvalds 			copied += used;
17161da177e4SLinus Torvalds 			offset += used;
1717e3d5ea2cSEric Dumazet 
171802275a2eSWilly Tarreau 			/* If recv_actor drops the lock (e.g. TCP splice
1719293ad604SOctavian Purdila 			 * receive) the skb pointer might be invalid when
1720293ad604SOctavian Purdila 			 * getting here: tcp_collapse might have deleted it
1721293ad604SOctavian Purdila 			 * while aggregating skbs from the socket queue.
1722293ad604SOctavian Purdila 			 */
1723293ad604SOctavian Purdila 			skb = tcp_recv_skb(sk, seq - 1, &offset);
172402275a2eSWilly Tarreau 			if (!skb)
17251da177e4SLinus Torvalds 				break;
172602275a2eSWilly Tarreau 			/* TCP coalescing might have appended data to the skb.
172702275a2eSWilly Tarreau 			 * Try to splice more frags
172802275a2eSWilly Tarreau 			 */
172902275a2eSWilly Tarreau 			if (offset + 1 != skb->len)
173002275a2eSWilly Tarreau 				continue;
17311da177e4SLinus Torvalds 		}
1732e11ecddfSEric Dumazet 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) {
17333df684c1SEric Dumazet 			tcp_eat_recv_skb(sk, skb);
17341da177e4SLinus Torvalds 			++seq;
17351da177e4SLinus Torvalds 			break;
17361da177e4SLinus Torvalds 		}
17373df684c1SEric Dumazet 		tcp_eat_recv_skb(sk, skb);
17381da177e4SLinus Torvalds 		if (!desc->count)
17391da177e4SLinus Torvalds 			break;
17407db48e98SEric Dumazet 		WRITE_ONCE(tp->copied_seq, seq);
17411da177e4SLinus Torvalds 	}
17427db48e98SEric Dumazet 	WRITE_ONCE(tp->copied_seq, seq);
17431da177e4SLinus Torvalds 
17441da177e4SLinus Torvalds 	tcp_rcv_space_adjust(sk);
17451da177e4SLinus Torvalds 
17461da177e4SLinus Torvalds 	/* Clean up data we have read: This will do ACK frames. */
1747f26845b4SEric Dumazet 	if (copied > 0) {
1748f26845b4SEric Dumazet 		tcp_recv_skb(sk, seq, &offset);
17490e4b4992SChris Leech 		tcp_cleanup_rbuf(sk, copied);
1750f26845b4SEric Dumazet 	}
17511da177e4SLinus Torvalds 	return copied;
17521da177e4SLinus Torvalds }
17534bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_read_sock);
17541da177e4SLinus Torvalds 
1755965b57b4SCong Wang int tcp_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
175604919bedSCong Wang {
175704919bedSCong Wang 	struct tcp_sock *tp = tcp_sk(sk);
175804919bedSCong Wang 	u32 seq = tp->copied_seq;
175904919bedSCong Wang 	struct sk_buff *skb;
176004919bedSCong Wang 	int copied = 0;
176104919bedSCong Wang 	u32 offset;
176204919bedSCong Wang 
176304919bedSCong Wang 	if (sk->sk_state == TCP_LISTEN)
176404919bedSCong Wang 		return -ENOTCONN;
176504919bedSCong Wang 
1766db4192a7SCong Wang 	while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
1767db4192a7SCong Wang 		u8 tcp_flags;
1768db4192a7SCong Wang 		int used;
176904919bedSCong Wang 
177004919bedSCong Wang 		__skb_unlink(skb, &sk->sk_receive_queue);
177196628951SPeilin Ye 		WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk));
1772db4192a7SCong Wang 		tcp_flags = TCP_SKB_CB(skb)->tcp_flags;
1773db4192a7SCong Wang 		used = recv_actor(sk, skb);
1774c457985aSCong Wang 		consume_skb(skb);
1775db4192a7SCong Wang 		if (used < 0) {
1776db4192a7SCong Wang 			if (!copied)
1777db4192a7SCong Wang 				copied = used;
1778db4192a7SCong Wang 			break;
1779db4192a7SCong Wang 		}
1780db4192a7SCong Wang 		seq += used;
1781db4192a7SCong Wang 		copied += used;
1782db4192a7SCong Wang 
1783db4192a7SCong Wang 		if (tcp_flags & TCPHDR_FIN) {
1784db4192a7SCong Wang 			++seq;
1785db4192a7SCong Wang 			break;
1786db4192a7SCong Wang 		}
1787db4192a7SCong Wang 	}
178804919bedSCong Wang 	WRITE_ONCE(tp->copied_seq, seq);
178904919bedSCong Wang 
179004919bedSCong Wang 	tcp_rcv_space_adjust(sk);
179104919bedSCong Wang 
179204919bedSCong Wang 	/* Clean up data we have read: This will do ACK frames. */
179304919bedSCong Wang 	if (copied > 0)
1794c457985aSCong Wang 		__tcp_cleanup_rbuf(sk, copied);
179504919bedSCong Wang 
179604919bedSCong Wang 	return copied;
179704919bedSCong Wang }
179804919bedSCong Wang EXPORT_SYMBOL(tcp_read_skb);
179904919bedSCong Wang 
18003f92a64eSJakub Kicinski void tcp_read_done(struct sock *sk, size_t len)
18013f92a64eSJakub Kicinski {
18023f92a64eSJakub Kicinski 	struct tcp_sock *tp = tcp_sk(sk);
18033f92a64eSJakub Kicinski 	u32 seq = tp->copied_seq;
18043f92a64eSJakub Kicinski 	struct sk_buff *skb;
18053f92a64eSJakub Kicinski 	size_t left;
18063f92a64eSJakub Kicinski 	u32 offset;
18073f92a64eSJakub Kicinski 
18083f92a64eSJakub Kicinski 	if (sk->sk_state == TCP_LISTEN)
18093f92a64eSJakub Kicinski 		return;
18103f92a64eSJakub Kicinski 
18113f92a64eSJakub Kicinski 	left = len;
18123f92a64eSJakub Kicinski 	while (left && (skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
18133f92a64eSJakub Kicinski 		int used;
18143f92a64eSJakub Kicinski 
18153f92a64eSJakub Kicinski 		used = min_t(size_t, skb->len - offset, left);
18163f92a64eSJakub Kicinski 		seq += used;
18173f92a64eSJakub Kicinski 		left -= used;
18183f92a64eSJakub Kicinski 
18193f92a64eSJakub Kicinski 		if (skb->len > offset + used)
18203f92a64eSJakub Kicinski 			break;
18213f92a64eSJakub Kicinski 
18223f92a64eSJakub Kicinski 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) {
18233f92a64eSJakub Kicinski 			tcp_eat_recv_skb(sk, skb);
18243f92a64eSJakub Kicinski 			++seq;
18253f92a64eSJakub Kicinski 			break;
18263f92a64eSJakub Kicinski 		}
18273f92a64eSJakub Kicinski 		tcp_eat_recv_skb(sk, skb);
18283f92a64eSJakub Kicinski 	}
18293f92a64eSJakub Kicinski 	WRITE_ONCE(tp->copied_seq, seq);
18303f92a64eSJakub Kicinski 
18313f92a64eSJakub Kicinski 	tcp_rcv_space_adjust(sk);
18323f92a64eSJakub Kicinski 
18333f92a64eSJakub Kicinski 	/* Clean up data we have read: This will do ACK frames. */
18343f92a64eSJakub Kicinski 	if (left != len)
18353f92a64eSJakub Kicinski 		tcp_cleanup_rbuf(sk, len - left);
18363f92a64eSJakub Kicinski }
18373f92a64eSJakub Kicinski EXPORT_SYMBOL(tcp_read_done);
18383f92a64eSJakub Kicinski 
183932035585STom Herbert int tcp_peek_len(struct socket *sock)
184032035585STom Herbert {
184132035585STom Herbert 	return tcp_inq(sock->sk);
184232035585STom Herbert }
184332035585STom Herbert EXPORT_SYMBOL(tcp_peek_len);
184432035585STom Herbert 
1845d1361840SEric Dumazet /* Make sure sk_rcvbuf is big enough to satisfy SO_RCVLOWAT hint */
1846d1361840SEric Dumazet int tcp_set_rcvlowat(struct sock *sk, int val)
1847d1361840SEric Dumazet {
1848867f816bSSoheil Hassas Yeganeh 	int cap;
1849867f816bSSoheil Hassas Yeganeh 
1850867f816bSSoheil Hassas Yeganeh 	if (sk->sk_userlocks & SOCK_RCVBUF_LOCK)
1851867f816bSSoheil Hassas Yeganeh 		cap = sk->sk_rcvbuf >> 1;
1852867f816bSSoheil Hassas Yeganeh 	else
185302739545SKuniyuki Iwashima 		cap = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2]) >> 1;
1854867f816bSSoheil Hassas Yeganeh 	val = min(val, cap);
1855eac66402SEric Dumazet 	WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
185603f45c88SEric Dumazet 
185703f45c88SEric Dumazet 	/* Check if we need to signal EPOLLIN right now */
185803f45c88SEric Dumazet 	tcp_data_ready(sk);
185903f45c88SEric Dumazet 
1860d1361840SEric Dumazet 	if (sk->sk_userlocks & SOCK_RCVBUF_LOCK)
1861d1361840SEric Dumazet 		return 0;
1862d1361840SEric Dumazet 
1863d1361840SEric Dumazet 	val <<= 1;
1864d1361840SEric Dumazet 	if (val > sk->sk_rcvbuf) {
1865ebb3b78dSEric Dumazet 		WRITE_ONCE(sk->sk_rcvbuf, val);
1866d1361840SEric Dumazet 		tcp_sk(sk)->window_clamp = tcp_win_from_space(sk, val);
1867d1361840SEric Dumazet 	}
1868d1361840SEric Dumazet 	return 0;
1869d1361840SEric Dumazet }
1870d1361840SEric Dumazet EXPORT_SYMBOL(tcp_set_rcvlowat);
1871d1361840SEric Dumazet 
1872892bfd3dSFlorian Westphal void tcp_update_recv_tstamps(struct sk_buff *skb,
18737eeba170SArjun Roy 			     struct scm_timestamping_internal *tss)
18747eeba170SArjun Roy {
18757eeba170SArjun Roy 	if (skb->tstamp)
18767eeba170SArjun Roy 		tss->ts[0] = ktime_to_timespec64(skb->tstamp);
18777eeba170SArjun Roy 	else
18787eeba170SArjun Roy 		tss->ts[0] = (struct timespec64) {0};
18797eeba170SArjun Roy 
18807eeba170SArjun Roy 	if (skb_hwtstamps(skb)->hwtstamp)
18817eeba170SArjun Roy 		tss->ts[2] = ktime_to_timespec64(skb_hwtstamps(skb)->hwtstamp);
18827eeba170SArjun Roy 	else
18837eeba170SArjun Roy 		tss->ts[2] = (struct timespec64) {0};
18847eeba170SArjun Roy }
18857eeba170SArjun Roy 
188605255b82SEric Dumazet #ifdef CONFIG_MMU
188705255b82SEric Dumazet static const struct vm_operations_struct tcp_vm_ops = {
188805255b82SEric Dumazet };
188905255b82SEric Dumazet 
189093ab6cc6SEric Dumazet int tcp_mmap(struct file *file, struct socket *sock,
189193ab6cc6SEric Dumazet 	     struct vm_area_struct *vma)
189293ab6cc6SEric Dumazet {
189305255b82SEric Dumazet 	if (vma->vm_flags & (VM_WRITE | VM_EXEC))
189405255b82SEric Dumazet 		return -EPERM;
18951c71222eSSuren Baghdasaryan 	vm_flags_clear(vma, VM_MAYWRITE | VM_MAYEXEC);
189605255b82SEric Dumazet 
18973e4e28c5SMichel Lespinasse 	/* Instruct vm_insert_page() to not mmap_read_lock(mm) */
18981c71222eSSuren Baghdasaryan 	vm_flags_set(vma, VM_MIXEDMAP);
189905255b82SEric Dumazet 
190005255b82SEric Dumazet 	vma->vm_ops = &tcp_vm_ops;
190105255b82SEric Dumazet 	return 0;
190205255b82SEric Dumazet }
190305255b82SEric Dumazet EXPORT_SYMBOL(tcp_mmap);
190405255b82SEric Dumazet 
19057fba5309SArjun Roy static skb_frag_t *skb_advance_to_frag(struct sk_buff *skb, u32 offset_skb,
19067fba5309SArjun Roy 				       u32 *offset_frag)
19077fba5309SArjun Roy {
19087fba5309SArjun Roy 	skb_frag_t *frag;
19097fba5309SArjun Roy 
191070701b83SArjun Roy 	if (unlikely(offset_skb >= skb->len))
191170701b83SArjun Roy 		return NULL;
191270701b83SArjun Roy 
19137fba5309SArjun Roy 	offset_skb -= skb_headlen(skb);
19147fba5309SArjun Roy 	if ((int)offset_skb < 0 || skb_has_frag_list(skb))
19157fba5309SArjun Roy 		return NULL;
19167fba5309SArjun Roy 
19177fba5309SArjun Roy 	frag = skb_shinfo(skb)->frags;
19187fba5309SArjun Roy 	while (offset_skb) {
19197fba5309SArjun Roy 		if (skb_frag_size(frag) > offset_skb) {
19207fba5309SArjun Roy 			*offset_frag = offset_skb;
19217fba5309SArjun Roy 			return frag;
19227fba5309SArjun Roy 		}
19237fba5309SArjun Roy 		offset_skb -= skb_frag_size(frag);
19247fba5309SArjun Roy 		++frag;
19257fba5309SArjun Roy 	}
19267fba5309SArjun Roy 	*offset_frag = 0;
19277fba5309SArjun Roy 	return frag;
19287fba5309SArjun Roy }
19297fba5309SArjun Roy 
193098917cf0SArjun Roy static bool can_map_frag(const skb_frag_t *frag)
193198917cf0SArjun Roy {
193298917cf0SArjun Roy 	return skb_frag_size(frag) == PAGE_SIZE && !skb_frag_off(frag);
193398917cf0SArjun Roy }
193498917cf0SArjun Roy 
193598917cf0SArjun Roy static int find_next_mappable_frag(const skb_frag_t *frag,
193698917cf0SArjun Roy 				   int remaining_in_skb)
193798917cf0SArjun Roy {
193898917cf0SArjun Roy 	int offset = 0;
193998917cf0SArjun Roy 
194098917cf0SArjun Roy 	if (likely(can_map_frag(frag)))
194198917cf0SArjun Roy 		return 0;
194298917cf0SArjun Roy 
194398917cf0SArjun Roy 	while (offset < remaining_in_skb && !can_map_frag(frag)) {
194498917cf0SArjun Roy 		offset += skb_frag_size(frag);
194598917cf0SArjun Roy 		++frag;
194698917cf0SArjun Roy 	}
194798917cf0SArjun Roy 	return offset;
194898917cf0SArjun Roy }
194998917cf0SArjun Roy 
19500c3936d3SArjun Roy static void tcp_zerocopy_set_hint_for_skb(struct sock *sk,
19510c3936d3SArjun Roy 					  struct tcp_zerocopy_receive *zc,
19520c3936d3SArjun Roy 					  struct sk_buff *skb, u32 offset)
19530c3936d3SArjun Roy {
19540c3936d3SArjun Roy 	u32 frag_offset, partial_frag_remainder = 0;
19550c3936d3SArjun Roy 	int mappable_offset;
19560c3936d3SArjun Roy 	skb_frag_t *frag;
19570c3936d3SArjun Roy 
19580c3936d3SArjun Roy 	/* worst case: skip to next skb. try to improve on this case below */
19590c3936d3SArjun Roy 	zc->recv_skip_hint = skb->len - offset;
19600c3936d3SArjun Roy 
19610c3936d3SArjun Roy 	/* Find the frag containing this offset (and how far into that frag) */
19620c3936d3SArjun Roy 	frag = skb_advance_to_frag(skb, offset, &frag_offset);
19630c3936d3SArjun Roy 	if (!frag)
19640c3936d3SArjun Roy 		return;
19650c3936d3SArjun Roy 
19660c3936d3SArjun Roy 	if (frag_offset) {
19670c3936d3SArjun Roy 		struct skb_shared_info *info = skb_shinfo(skb);
19680c3936d3SArjun Roy 
19690c3936d3SArjun Roy 		/* We read part of the last frag, must recvmsg() rest of skb. */
19700c3936d3SArjun Roy 		if (frag == &info->frags[info->nr_frags - 1])
19710c3936d3SArjun Roy 			return;
19720c3936d3SArjun Roy 
19730c3936d3SArjun Roy 		/* Else, we must at least read the remainder in this frag. */
19740c3936d3SArjun Roy 		partial_frag_remainder = skb_frag_size(frag) - frag_offset;
19750c3936d3SArjun Roy 		zc->recv_skip_hint -= partial_frag_remainder;
19760c3936d3SArjun Roy 		++frag;
19770c3936d3SArjun Roy 	}
19780c3936d3SArjun Roy 
19790c3936d3SArjun Roy 	/* partial_frag_remainder: If part way through a frag, must read rest.
19800c3936d3SArjun Roy 	 * mappable_offset: Bytes till next mappable frag, *not* counting bytes
19810c3936d3SArjun Roy 	 * in partial_frag_remainder.
19820c3936d3SArjun Roy 	 */
19830c3936d3SArjun Roy 	mappable_offset = find_next_mappable_frag(frag, zc->recv_skip_hint);
19840c3936d3SArjun Roy 	zc->recv_skip_hint = mappable_offset + partial_frag_remainder;
19850c3936d3SArjun Roy }
19860c3936d3SArjun Roy 
1987f21a3c48SArjun Roy static int tcp_recvmsg_locked(struct sock *sk, struct msghdr *msg, size_t len,
1988ec095263SOliver Hartkopp 			      int flags, struct scm_timestamping_internal *tss,
1989f21a3c48SArjun Roy 			      int *cmsg_flags);
1990f21a3c48SArjun Roy static int receive_fallback_to_copy(struct sock *sk,
19917eeba170SArjun Roy 				    struct tcp_zerocopy_receive *zc, int inq,
19927eeba170SArjun Roy 				    struct scm_timestamping_internal *tss)
1993f21a3c48SArjun Roy {
1994f21a3c48SArjun Roy 	unsigned long copy_address = (unsigned long)zc->copybuf_address;
1995f21a3c48SArjun Roy 	struct msghdr msg = {};
1996f21a3c48SArjun Roy 	struct iovec iov;
19977eeba170SArjun Roy 	int err;
1998f21a3c48SArjun Roy 
1999f21a3c48SArjun Roy 	zc->length = 0;
2000f21a3c48SArjun Roy 	zc->recv_skip_hint = 0;
2001f21a3c48SArjun Roy 
2002f21a3c48SArjun Roy 	if (copy_address != zc->copybuf_address)
2003f21a3c48SArjun Roy 		return -EINVAL;
2004f21a3c48SArjun Roy 
2005de4eda9dSAl Viro 	err = import_single_range(ITER_DEST, (void __user *)copy_address,
2006f21a3c48SArjun Roy 				  inq, &iov, &msg.msg_iter);
2007f21a3c48SArjun Roy 	if (err)
2008f21a3c48SArjun Roy 		return err;
2009f21a3c48SArjun Roy 
2010ec095263SOliver Hartkopp 	err = tcp_recvmsg_locked(sk, &msg, inq, MSG_DONTWAIT,
20117eeba170SArjun Roy 				 tss, &zc->msg_flags);
2012f21a3c48SArjun Roy 	if (err < 0)
2013f21a3c48SArjun Roy 		return err;
2014f21a3c48SArjun Roy 
2015f21a3c48SArjun Roy 	zc->copybuf_len = err;
20160c3936d3SArjun Roy 	if (likely(zc->copybuf_len)) {
20170c3936d3SArjun Roy 		struct sk_buff *skb;
20180c3936d3SArjun Roy 		u32 offset;
20190c3936d3SArjun Roy 
20200c3936d3SArjun Roy 		skb = tcp_recv_skb(sk, tcp_sk(sk)->copied_seq, &offset);
20210c3936d3SArjun Roy 		if (skb)
20220c3936d3SArjun Roy 			tcp_zerocopy_set_hint_for_skb(sk, zc, skb, offset);
20230c3936d3SArjun Roy 	}
2024f21a3c48SArjun Roy 	return 0;
2025f21a3c48SArjun Roy }
2026f21a3c48SArjun Roy 
202718fb76edSArjun Roy static int tcp_copy_straggler_data(struct tcp_zerocopy_receive *zc,
202818fb76edSArjun Roy 				   struct sk_buff *skb, u32 copylen,
202918fb76edSArjun Roy 				   u32 *offset, u32 *seq)
203018fb76edSArjun Roy {
203118fb76edSArjun Roy 	unsigned long copy_address = (unsigned long)zc->copybuf_address;
203218fb76edSArjun Roy 	struct msghdr msg = {};
203318fb76edSArjun Roy 	struct iovec iov;
203418fb76edSArjun Roy 	int err;
203518fb76edSArjun Roy 
203618fb76edSArjun Roy 	if (copy_address != zc->copybuf_address)
203718fb76edSArjun Roy 		return -EINVAL;
203818fb76edSArjun Roy 
2039de4eda9dSAl Viro 	err = import_single_range(ITER_DEST, (void __user *)copy_address,
204018fb76edSArjun Roy 				  copylen, &iov, &msg.msg_iter);
204118fb76edSArjun Roy 	if (err)
204218fb76edSArjun Roy 		return err;
204318fb76edSArjun Roy 	err = skb_copy_datagram_msg(skb, *offset, &msg, copylen);
204418fb76edSArjun Roy 	if (err)
204518fb76edSArjun Roy 		return err;
204618fb76edSArjun Roy 	zc->recv_skip_hint -= copylen;
204718fb76edSArjun Roy 	*offset += copylen;
204818fb76edSArjun Roy 	*seq += copylen;
204918fb76edSArjun Roy 	return (__s32)copylen;
205018fb76edSArjun Roy }
205118fb76edSArjun Roy 
20527eeba170SArjun Roy static int tcp_zc_handle_leftover(struct tcp_zerocopy_receive *zc,
205318fb76edSArjun Roy 				  struct sock *sk,
205418fb76edSArjun Roy 				  struct sk_buff *skb,
205518fb76edSArjun Roy 				  u32 *seq,
20567eeba170SArjun Roy 				  s32 copybuf_len,
20577eeba170SArjun Roy 				  struct scm_timestamping_internal *tss)
205818fb76edSArjun Roy {
205918fb76edSArjun Roy 	u32 offset, copylen = min_t(u32, copybuf_len, zc->recv_skip_hint);
206018fb76edSArjun Roy 
206118fb76edSArjun Roy 	if (!copylen)
206218fb76edSArjun Roy 		return 0;
206318fb76edSArjun Roy 	/* skb is null if inq < PAGE_SIZE. */
20647eeba170SArjun Roy 	if (skb) {
206518fb76edSArjun Roy 		offset = *seq - TCP_SKB_CB(skb)->seq;
20667eeba170SArjun Roy 	} else {
206718fb76edSArjun Roy 		skb = tcp_recv_skb(sk, *seq, &offset);
20687eeba170SArjun Roy 		if (TCP_SKB_CB(skb)->has_rxtstamp) {
20697eeba170SArjun Roy 			tcp_update_recv_tstamps(skb, tss);
20707eeba170SArjun Roy 			zc->msg_flags |= TCP_CMSG_TS;
20717eeba170SArjun Roy 		}
20727eeba170SArjun Roy 	}
207318fb76edSArjun Roy 
207418fb76edSArjun Roy 	zc->copybuf_len = tcp_copy_straggler_data(zc, skb, copylen, &offset,
207518fb76edSArjun Roy 						  seq);
207618fb76edSArjun Roy 	return zc->copybuf_len < 0 ? 0 : copylen;
207718fb76edSArjun Roy }
207818fb76edSArjun Roy 
207994ab9eb9SArjun Roy static int tcp_zerocopy_vm_insert_batch_error(struct vm_area_struct *vma,
208094ab9eb9SArjun Roy 					      struct page **pending_pages,
208194ab9eb9SArjun Roy 					      unsigned long pages_remaining,
208294ab9eb9SArjun Roy 					      unsigned long *address,
208394ab9eb9SArjun Roy 					      u32 *length,
208494ab9eb9SArjun Roy 					      u32 *seq,
208594ab9eb9SArjun Roy 					      struct tcp_zerocopy_receive *zc,
208694ab9eb9SArjun Roy 					      u32 total_bytes_to_map,
208794ab9eb9SArjun Roy 					      int err)
208894ab9eb9SArjun Roy {
208994ab9eb9SArjun Roy 	/* At least one page did not map. Try zapping if we skipped earlier. */
209094ab9eb9SArjun Roy 	if (err == -EBUSY &&
209194ab9eb9SArjun Roy 	    zc->flags & TCP_RECEIVE_ZEROCOPY_FLAG_TLB_CLEAN_HINT) {
209294ab9eb9SArjun Roy 		u32 maybe_zap_len;
209394ab9eb9SArjun Roy 
209494ab9eb9SArjun Roy 		maybe_zap_len = total_bytes_to_map -  /* All bytes to map */
209594ab9eb9SArjun Roy 				*length + /* Mapped or pending */
209694ab9eb9SArjun Roy 				(pages_remaining * PAGE_SIZE); /* Failed map. */
2097e9adcfecSMike Kravetz 		zap_page_range_single(vma, *address, maybe_zap_len, NULL);
209894ab9eb9SArjun Roy 		err = 0;
209994ab9eb9SArjun Roy 	}
210094ab9eb9SArjun Roy 
210194ab9eb9SArjun Roy 	if (!err) {
210294ab9eb9SArjun Roy 		unsigned long leftover_pages = pages_remaining;
210394ab9eb9SArjun Roy 		int bytes_mapped;
210494ab9eb9SArjun Roy 
2105e9adcfecSMike Kravetz 		/* We called zap_page_range_single, try to reinsert. */
210694ab9eb9SArjun Roy 		err = vm_insert_pages(vma, *address,
210794ab9eb9SArjun Roy 				      pending_pages,
210894ab9eb9SArjun Roy 				      &pages_remaining);
210994ab9eb9SArjun Roy 		bytes_mapped = PAGE_SIZE * (leftover_pages - pages_remaining);
211094ab9eb9SArjun Roy 		*seq += bytes_mapped;
211194ab9eb9SArjun Roy 		*address += bytes_mapped;
211294ab9eb9SArjun Roy 	}
211394ab9eb9SArjun Roy 	if (err) {
211494ab9eb9SArjun Roy 		/* Either we were unable to zap, OR we zapped, retried an
211594ab9eb9SArjun Roy 		 * insert, and still had an issue. Either ways, pages_remaining
211694ab9eb9SArjun Roy 		 * is the number of pages we were unable to map, and we unroll
211794ab9eb9SArjun Roy 		 * some state we speculatively touched before.
211894ab9eb9SArjun Roy 		 */
211994ab9eb9SArjun Roy 		const int bytes_not_mapped = PAGE_SIZE * pages_remaining;
212094ab9eb9SArjun Roy 
212194ab9eb9SArjun Roy 		*length -= bytes_not_mapped;
212294ab9eb9SArjun Roy 		zc->recv_skip_hint += bytes_not_mapped;
212394ab9eb9SArjun Roy 	}
212494ab9eb9SArjun Roy 	return err;
212594ab9eb9SArjun Roy }
212694ab9eb9SArjun Roy 
21273763a24cSArjun Roy static int tcp_zerocopy_vm_insert_batch(struct vm_area_struct *vma,
21283763a24cSArjun Roy 					struct page **pages,
212994ab9eb9SArjun Roy 					unsigned int pages_to_map,
213094ab9eb9SArjun Roy 					unsigned long *address,
213194ab9eb9SArjun Roy 					u32 *length,
21323763a24cSArjun Roy 					u32 *seq,
213394ab9eb9SArjun Roy 					struct tcp_zerocopy_receive *zc,
213494ab9eb9SArjun Roy 					u32 total_bytes_to_map)
21353763a24cSArjun Roy {
21363763a24cSArjun Roy 	unsigned long pages_remaining = pages_to_map;
213794ab9eb9SArjun Roy 	unsigned int pages_mapped;
213894ab9eb9SArjun Roy 	unsigned int bytes_mapped;
213994ab9eb9SArjun Roy 	int err;
21403763a24cSArjun Roy 
214194ab9eb9SArjun Roy 	err = vm_insert_pages(vma, *address, pages, &pages_remaining);
214294ab9eb9SArjun Roy 	pages_mapped = pages_to_map - (unsigned int)pages_remaining;
214394ab9eb9SArjun Roy 	bytes_mapped = PAGE_SIZE * pages_mapped;
21443763a24cSArjun Roy 	/* Even if vm_insert_pages fails, it may have partially succeeded in
21453763a24cSArjun Roy 	 * mapping (some but not all of the pages).
21463763a24cSArjun Roy 	 */
21473763a24cSArjun Roy 	*seq += bytes_mapped;
214894ab9eb9SArjun Roy 	*address += bytes_mapped;
214994ab9eb9SArjun Roy 
215094ab9eb9SArjun Roy 	if (likely(!err))
215194ab9eb9SArjun Roy 		return 0;
215294ab9eb9SArjun Roy 
215394ab9eb9SArjun Roy 	/* Error: maybe zap and retry + rollback state for failed inserts. */
215494ab9eb9SArjun Roy 	return tcp_zerocopy_vm_insert_batch_error(vma, pages + pages_mapped,
215594ab9eb9SArjun Roy 		pages_remaining, address, length, seq, zc, total_bytes_to_map,
215694ab9eb9SArjun Roy 		err);
21573763a24cSArjun Roy }
21583763a24cSArjun Roy 
21593c5a2fd0SArjun Roy #define TCP_VALID_ZC_MSG_FLAGS   (TCP_CMSG_TS)
21607eeba170SArjun Roy static void tcp_zc_finalize_rx_tstamp(struct sock *sk,
21617eeba170SArjun Roy 				      struct tcp_zerocopy_receive *zc,
21627eeba170SArjun Roy 				      struct scm_timestamping_internal *tss)
21637eeba170SArjun Roy {
21647eeba170SArjun Roy 	unsigned long msg_control_addr;
21657eeba170SArjun Roy 	struct msghdr cmsg_dummy;
21667eeba170SArjun Roy 
21677eeba170SArjun Roy 	msg_control_addr = (unsigned long)zc->msg_control;
21687eeba170SArjun Roy 	cmsg_dummy.msg_control = (void *)msg_control_addr;
21697eeba170SArjun Roy 	cmsg_dummy.msg_controllen =
21707eeba170SArjun Roy 		(__kernel_size_t)zc->msg_controllen;
21717eeba170SArjun Roy 	cmsg_dummy.msg_flags = in_compat_syscall()
21727eeba170SArjun Roy 		? MSG_CMSG_COMPAT : 0;
2173a6f8ee58SArjun Roy 	cmsg_dummy.msg_control_is_user = true;
21747eeba170SArjun Roy 	zc->msg_flags = 0;
21757eeba170SArjun Roy 	if (zc->msg_control == msg_control_addr &&
21767eeba170SArjun Roy 	    zc->msg_controllen == cmsg_dummy.msg_controllen) {
21777eeba170SArjun Roy 		tcp_recv_timestamp(&cmsg_dummy, sk, tss);
21787eeba170SArjun Roy 		zc->msg_control = (__u64)
21797eeba170SArjun Roy 			((uintptr_t)cmsg_dummy.msg_control);
21807eeba170SArjun Roy 		zc->msg_controllen =
21817eeba170SArjun Roy 			(__u64)cmsg_dummy.msg_controllen;
21827eeba170SArjun Roy 		zc->msg_flags = (__u32)cmsg_dummy.msg_flags;
21837eeba170SArjun Roy 	}
21847eeba170SArjun Roy }
21857eeba170SArjun Roy 
218694ab9eb9SArjun Roy #define TCP_ZEROCOPY_PAGE_BATCH_SIZE 32
218705255b82SEric Dumazet static int tcp_zerocopy_receive(struct sock *sk,
21887eeba170SArjun Roy 				struct tcp_zerocopy_receive *zc,
21897eeba170SArjun Roy 				struct scm_timestamping_internal *tss)
219005255b82SEric Dumazet {
219194ab9eb9SArjun Roy 	u32 length = 0, offset, vma_len, avail_len, copylen = 0;
219205255b82SEric Dumazet 	unsigned long address = (unsigned long)zc->address;
219394ab9eb9SArjun Roy 	struct page *pages[TCP_ZEROCOPY_PAGE_BATCH_SIZE];
219418fb76edSArjun Roy 	s32 copybuf_len = zc->copybuf_len;
219518fb76edSArjun Roy 	struct tcp_sock *tp = tcp_sk(sk);
219605255b82SEric Dumazet 	const skb_frag_t *frags = NULL;
219794ab9eb9SArjun Roy 	unsigned int pages_to_map = 0;
219805255b82SEric Dumazet 	struct vm_area_struct *vma;
219905255b82SEric Dumazet 	struct sk_buff *skb = NULL;
220018fb76edSArjun Roy 	u32 seq = tp->copied_seq;
220194ab9eb9SArjun Roy 	u32 total_bytes_to_map;
220218fb76edSArjun Roy 	int inq = tcp_inq(sk);
220393ab6cc6SEric Dumazet 	int ret;
220493ab6cc6SEric Dumazet 
220518fb76edSArjun Roy 	zc->copybuf_len = 0;
22067eeba170SArjun Roy 	zc->msg_flags = 0;
220718fb76edSArjun Roy 
220805255b82SEric Dumazet 	if (address & (PAGE_SIZE - 1) || address != zc->address)
220993ab6cc6SEric Dumazet 		return -EINVAL;
221093ab6cc6SEric Dumazet 
221193ab6cc6SEric Dumazet 	if (sk->sk_state == TCP_LISTEN)
221205255b82SEric Dumazet 		return -ENOTCONN;
221393ab6cc6SEric Dumazet 
221493ab6cc6SEric Dumazet 	sock_rps_record_flow(sk);
221593ab6cc6SEric Dumazet 
2216f21a3c48SArjun Roy 	if (inq && inq <= copybuf_len)
22177eeba170SArjun Roy 		return receive_fallback_to_copy(sk, zc, inq, tss);
2218f21a3c48SArjun Roy 
2219936ced41SArjun Roy 	if (inq < PAGE_SIZE) {
2220936ced41SArjun Roy 		zc->length = 0;
2221936ced41SArjun Roy 		zc->recv_skip_hint = inq;
2222936ced41SArjun Roy 		if (!inq && sock_flag(sk, SOCK_DONE))
2223936ced41SArjun Roy 			return -EIO;
2224936ced41SArjun Roy 		return 0;
2225936ced41SArjun Roy 	}
2226936ced41SArjun Roy 
2227d8ed45c5SMichel Lespinasse 	mmap_read_lock(current->mm);
222893ab6cc6SEric Dumazet 
222947bdd1dbSLiam Howlett 	vma = vma_lookup(current->mm, address);
223047bdd1dbSLiam Howlett 	if (!vma || vma->vm_ops != &tcp_vm_ops) {
2231d8ed45c5SMichel Lespinasse 		mmap_read_unlock(current->mm);
2232e776af60SEric Dumazet 		return -EINVAL;
2233e776af60SEric Dumazet 	}
223418fb76edSArjun Roy 	vma_len = min_t(unsigned long, zc->length, vma->vm_end - address);
223518fb76edSArjun Roy 	avail_len = min_t(u32, vma_len, inq);
223694ab9eb9SArjun Roy 	total_bytes_to_map = avail_len & ~(PAGE_SIZE - 1);
223794ab9eb9SArjun Roy 	if (total_bytes_to_map) {
223894ab9eb9SArjun Roy 		if (!(zc->flags & TCP_RECEIVE_ZEROCOPY_FLAG_TLB_CLEAN_HINT))
2239e9adcfecSMike Kravetz 			zap_page_range_single(vma, address, total_bytes_to_map,
2240e9adcfecSMike Kravetz 					      NULL);
224194ab9eb9SArjun Roy 		zc->length = total_bytes_to_map;
224205255b82SEric Dumazet 		zc->recv_skip_hint = 0;
22438f2b0293SSoheil Hassas Yeganeh 	} else {
224418fb76edSArjun Roy 		zc->length = avail_len;
224518fb76edSArjun Roy 		zc->recv_skip_hint = avail_len;
22468f2b0293SSoheil Hassas Yeganeh 	}
224705255b82SEric Dumazet 	ret = 0;
224805255b82SEric Dumazet 	while (length + PAGE_SIZE <= zc->length) {
224998917cf0SArjun Roy 		int mappable_offset;
225094ab9eb9SArjun Roy 		struct page *page;
225198917cf0SArjun Roy 
225205255b82SEric Dumazet 		if (zc->recv_skip_hint < PAGE_SIZE) {
22537fba5309SArjun Roy 			u32 offset_frag;
22547fba5309SArjun Roy 
225505255b82SEric Dumazet 			if (skb) {
22560e627190SArjun Roy 				if (zc->recv_skip_hint > 0)
22570e627190SArjun Roy 					break;
225805255b82SEric Dumazet 				skb = skb->next;
225905255b82SEric Dumazet 				offset = seq - TCP_SKB_CB(skb)->seq;
226005255b82SEric Dumazet 			} else {
226193ab6cc6SEric Dumazet 				skb = tcp_recv_skb(sk, seq, &offset);
226205255b82SEric Dumazet 			}
22637eeba170SArjun Roy 
22647eeba170SArjun Roy 			if (TCP_SKB_CB(skb)->has_rxtstamp) {
22657eeba170SArjun Roy 				tcp_update_recv_tstamps(skb, tss);
22667eeba170SArjun Roy 				zc->msg_flags |= TCP_CMSG_TS;
22677eeba170SArjun Roy 			}
226805255b82SEric Dumazet 			zc->recv_skip_hint = skb->len - offset;
22697fba5309SArjun Roy 			frags = skb_advance_to_frag(skb, offset, &offset_frag);
22707fba5309SArjun Roy 			if (!frags || offset_frag)
227105255b82SEric Dumazet 				break;
227205255b82SEric Dumazet 		}
2273789762ceSSoheil Hassas Yeganeh 
227498917cf0SArjun Roy 		mappable_offset = find_next_mappable_frag(frags,
227598917cf0SArjun Roy 							  zc->recv_skip_hint);
227698917cf0SArjun Roy 		if (mappable_offset) {
227798917cf0SArjun Roy 			zc->recv_skip_hint = mappable_offset;
227805255b82SEric Dumazet 			break;
2279789762ceSSoheil Hassas Yeganeh 		}
228094ab9eb9SArjun Roy 		page = skb_frag_page(frags);
228194ab9eb9SArjun Roy 		prefetchw(page);
228294ab9eb9SArjun Roy 		pages[pages_to_map++] = page;
228305255b82SEric Dumazet 		length += PAGE_SIZE;
228405255b82SEric Dumazet 		zc->recv_skip_hint -= PAGE_SIZE;
228505255b82SEric Dumazet 		frags++;
228694ab9eb9SArjun Roy 		if (pages_to_map == TCP_ZEROCOPY_PAGE_BATCH_SIZE ||
228794ab9eb9SArjun Roy 		    zc->recv_skip_hint < PAGE_SIZE) {
228894ab9eb9SArjun Roy 			/* Either full batch, or we're about to go to next skb
228994ab9eb9SArjun Roy 			 * (and we cannot unroll failed ops across skbs).
229094ab9eb9SArjun Roy 			 */
229194ab9eb9SArjun Roy 			ret = tcp_zerocopy_vm_insert_batch(vma, pages,
229294ab9eb9SArjun Roy 							   pages_to_map,
229394ab9eb9SArjun Roy 							   &address, &length,
229494ab9eb9SArjun Roy 							   &seq, zc,
229594ab9eb9SArjun Roy 							   total_bytes_to_map);
22963763a24cSArjun Roy 			if (ret)
22973763a24cSArjun Roy 				goto out;
229894ab9eb9SArjun Roy 			pages_to_map = 0;
22993763a24cSArjun Roy 		}
23003763a24cSArjun Roy 	}
230194ab9eb9SArjun Roy 	if (pages_to_map) {
230294ab9eb9SArjun Roy 		ret = tcp_zerocopy_vm_insert_batch(vma, pages, pages_to_map,
230394ab9eb9SArjun Roy 						   &address, &length, &seq,
230494ab9eb9SArjun Roy 						   zc, total_bytes_to_map);
230593ab6cc6SEric Dumazet 	}
230605255b82SEric Dumazet out:
2307d8ed45c5SMichel Lespinasse 	mmap_read_unlock(current->mm);
230818fb76edSArjun Roy 	/* Try to copy straggler data. */
230918fb76edSArjun Roy 	if (!ret)
23107eeba170SArjun Roy 		copylen = tcp_zc_handle_leftover(zc, sk, skb, &seq, copybuf_len, tss);
231118fb76edSArjun Roy 
231218fb76edSArjun Roy 	if (length + copylen) {
23137db48e98SEric Dumazet 		WRITE_ONCE(tp->copied_seq, seq);
231493ab6cc6SEric Dumazet 		tcp_rcv_space_adjust(sk);
231593ab6cc6SEric Dumazet 
231693ab6cc6SEric Dumazet 		/* Clean up data we have read: This will do ACK frames. */
231793ab6cc6SEric Dumazet 		tcp_recv_skb(sk, seq, &offset);
231818fb76edSArjun Roy 		tcp_cleanup_rbuf(sk, length + copylen);
231993ab6cc6SEric Dumazet 		ret = 0;
232005255b82SEric Dumazet 		if (length == zc->length)
232105255b82SEric Dumazet 			zc->recv_skip_hint = 0;
232205255b82SEric Dumazet 	} else {
232305255b82SEric Dumazet 		if (!zc->recv_skip_hint && sock_flag(sk, SOCK_DONE))
232405255b82SEric Dumazet 			ret = -EIO;
232505255b82SEric Dumazet 	}
232605255b82SEric Dumazet 	zc->length = length;
232793ab6cc6SEric Dumazet 	return ret;
232893ab6cc6SEric Dumazet }
232905255b82SEric Dumazet #endif
233093ab6cc6SEric Dumazet 
233198aaa913SMike Maloney /* Similar to __sock_recv_timestamp, but does not require an skb */
2332892bfd3dSFlorian Westphal void tcp_recv_timestamp(struct msghdr *msg, const struct sock *sk,
23339718475eSDeepa Dinamani 			struct scm_timestamping_internal *tss)
233498aaa913SMike Maloney {
2335887feae3SDeepa Dinamani 	int new_tstamp = sock_flag(sk, SOCK_TSTAMP_NEW);
233698aaa913SMike Maloney 	bool has_timestamping = false;
233798aaa913SMike Maloney 
233898aaa913SMike Maloney 	if (tss->ts[0].tv_sec || tss->ts[0].tv_nsec) {
233998aaa913SMike Maloney 		if (sock_flag(sk, SOCK_RCVTSTAMP)) {
234098aaa913SMike Maloney 			if (sock_flag(sk, SOCK_RCVTSTAMPNS)) {
2341887feae3SDeepa Dinamani 				if (new_tstamp) {
2342df1b4ba9SArnd Bergmann 					struct __kernel_timespec kts = {
2343df1b4ba9SArnd Bergmann 						.tv_sec = tss->ts[0].tv_sec,
2344df1b4ba9SArnd Bergmann 						.tv_nsec = tss->ts[0].tv_nsec,
2345df1b4ba9SArnd Bergmann 					};
2346887feae3SDeepa Dinamani 					put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMPNS_NEW,
2347887feae3SDeepa Dinamani 						 sizeof(kts), &kts);
2348887feae3SDeepa Dinamani 				} else {
2349df1b4ba9SArnd Bergmann 					struct __kernel_old_timespec ts_old = {
2350df1b4ba9SArnd Bergmann 						.tv_sec = tss->ts[0].tv_sec,
2351df1b4ba9SArnd Bergmann 						.tv_nsec = tss->ts[0].tv_nsec,
2352df1b4ba9SArnd Bergmann 					};
23537f1bc6e9SDeepa Dinamani 					put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMPNS_OLD,
23549718475eSDeepa Dinamani 						 sizeof(ts_old), &ts_old);
2355887feae3SDeepa Dinamani 				}
235698aaa913SMike Maloney 			} else {
2357887feae3SDeepa Dinamani 				if (new_tstamp) {
2358df1b4ba9SArnd Bergmann 					struct __kernel_sock_timeval stv = {
2359df1b4ba9SArnd Bergmann 						.tv_sec = tss->ts[0].tv_sec,
2360df1b4ba9SArnd Bergmann 						.tv_usec = tss->ts[0].tv_nsec / 1000,
2361df1b4ba9SArnd Bergmann 					};
2362887feae3SDeepa Dinamani 					put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_NEW,
2363887feae3SDeepa Dinamani 						 sizeof(stv), &stv);
2364887feae3SDeepa Dinamani 				} else {
2365df1b4ba9SArnd Bergmann 					struct __kernel_old_timeval tv = {
2366df1b4ba9SArnd Bergmann 						.tv_sec = tss->ts[0].tv_sec,
2367df1b4ba9SArnd Bergmann 						.tv_usec = tss->ts[0].tv_nsec / 1000,
2368df1b4ba9SArnd Bergmann 					};
23697f1bc6e9SDeepa Dinamani 					put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_OLD,
237098aaa913SMike Maloney 						 sizeof(tv), &tv);
237198aaa913SMike Maloney 				}
237298aaa913SMike Maloney 			}
2373887feae3SDeepa Dinamani 		}
237498aaa913SMike Maloney 
237598aaa913SMike Maloney 		if (sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE)
237698aaa913SMike Maloney 			has_timestamping = true;
237798aaa913SMike Maloney 		else
23789718475eSDeepa Dinamani 			tss->ts[0] = (struct timespec64) {0};
237998aaa913SMike Maloney 	}
238098aaa913SMike Maloney 
238198aaa913SMike Maloney 	if (tss->ts[2].tv_sec || tss->ts[2].tv_nsec) {
238298aaa913SMike Maloney 		if (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE)
238398aaa913SMike Maloney 			has_timestamping = true;
238498aaa913SMike Maloney 		else
23859718475eSDeepa Dinamani 			tss->ts[2] = (struct timespec64) {0};
238698aaa913SMike Maloney 	}
238798aaa913SMike Maloney 
238898aaa913SMike Maloney 	if (has_timestamping) {
23899718475eSDeepa Dinamani 		tss->ts[1] = (struct timespec64) {0};
23909718475eSDeepa Dinamani 		if (sock_flag(sk, SOCK_TSTAMP_NEW))
23919718475eSDeepa Dinamani 			put_cmsg_scm_timestamping64(msg, tss);
23929718475eSDeepa Dinamani 		else
23939718475eSDeepa Dinamani 			put_cmsg_scm_timestamping(msg, tss);
239498aaa913SMike Maloney 	}
239598aaa913SMike Maloney }
239698aaa913SMike Maloney 
2397b75eba76SSoheil Hassas Yeganeh static int tcp_inq_hint(struct sock *sk)
2398b75eba76SSoheil Hassas Yeganeh {
2399b75eba76SSoheil Hassas Yeganeh 	const struct tcp_sock *tp = tcp_sk(sk);
2400b75eba76SSoheil Hassas Yeganeh 	u32 copied_seq = READ_ONCE(tp->copied_seq);
2401b75eba76SSoheil Hassas Yeganeh 	u32 rcv_nxt = READ_ONCE(tp->rcv_nxt);
2402b75eba76SSoheil Hassas Yeganeh 	int inq;
2403b75eba76SSoheil Hassas Yeganeh 
2404b75eba76SSoheil Hassas Yeganeh 	inq = rcv_nxt - copied_seq;
2405b75eba76SSoheil Hassas Yeganeh 	if (unlikely(inq < 0 || copied_seq != READ_ONCE(tp->copied_seq))) {
2406b75eba76SSoheil Hassas Yeganeh 		lock_sock(sk);
2407b75eba76SSoheil Hassas Yeganeh 		inq = tp->rcv_nxt - tp->copied_seq;
2408b75eba76SSoheil Hassas Yeganeh 		release_sock(sk);
2409b75eba76SSoheil Hassas Yeganeh 	}
24106466e715SSoheil Hassas Yeganeh 	/* After receiving a FIN, tell the user-space to continue reading
24116466e715SSoheil Hassas Yeganeh 	 * by returning a non-zero inq.
24126466e715SSoheil Hassas Yeganeh 	 */
24136466e715SSoheil Hassas Yeganeh 	if (inq == 0 && sock_flag(sk, SOCK_DONE))
24146466e715SSoheil Hassas Yeganeh 		inq = 1;
2415b75eba76SSoheil Hassas Yeganeh 	return inq;
2416b75eba76SSoheil Hassas Yeganeh }
2417b75eba76SSoheil Hassas Yeganeh 
24181da177e4SLinus Torvalds /*
24191da177e4SLinus Torvalds  *	This routine copies from a sock struct into the user buffer.
24201da177e4SLinus Torvalds  *
24211da177e4SLinus Torvalds  *	Technical note: in 2.3 we work on _locked_ socket, so that
24221da177e4SLinus Torvalds  *	tricks with *seq access order and skb->users are not required.
24231da177e4SLinus Torvalds  *	Probably, code can be easily improved even more.
24241da177e4SLinus Torvalds  */
24251da177e4SLinus Torvalds 
24262cd81161SArjun Roy static int tcp_recvmsg_locked(struct sock *sk, struct msghdr *msg, size_t len,
2427ec095263SOliver Hartkopp 			      int flags, struct scm_timestamping_internal *tss,
24282cd81161SArjun Roy 			      int *cmsg_flags)
24291da177e4SLinus Torvalds {
24301da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
24311da177e4SLinus Torvalds 	int copied = 0;
24321da177e4SLinus Torvalds 	u32 peek_seq;
24331da177e4SLinus Torvalds 	u32 *seq;
24341da177e4SLinus Torvalds 	unsigned long used;
24352cd81161SArjun Roy 	int err;
24361da177e4SLinus Torvalds 	int target;		/* Read at least this many bytes */
24371da177e4SLinus Torvalds 	long timeo;
2438dfbafc99SSabrina Dubroca 	struct sk_buff *skb, *last;
243977527313SIlpo Järvinen 	u32 urg_hole = 0;
24401da177e4SLinus Torvalds 
24411da177e4SLinus Torvalds 	err = -ENOTCONN;
24421da177e4SLinus Torvalds 	if (sk->sk_state == TCP_LISTEN)
24431da177e4SLinus Torvalds 		goto out;
24441da177e4SLinus Torvalds 
2445f94fd25cSJens Axboe 	if (tp->recvmsg_inq) {
2446925bba24SArjun Roy 		*cmsg_flags = TCP_CMSG_INQ;
2447f94fd25cSJens Axboe 		msg->msg_get_inq = 1;
2448f94fd25cSJens Axboe 	}
2449ec095263SOliver Hartkopp 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
24501da177e4SLinus Torvalds 
24511da177e4SLinus Torvalds 	/* Urgent data needs to be handled specially. */
24521da177e4SLinus Torvalds 	if (flags & MSG_OOB)
24531da177e4SLinus Torvalds 		goto recv_urg;
24541da177e4SLinus Torvalds 
2455c0e88ff0SPavel Emelyanov 	if (unlikely(tp->repair)) {
2456c0e88ff0SPavel Emelyanov 		err = -EPERM;
2457c0e88ff0SPavel Emelyanov 		if (!(flags & MSG_PEEK))
2458c0e88ff0SPavel Emelyanov 			goto out;
2459c0e88ff0SPavel Emelyanov 
2460c0e88ff0SPavel Emelyanov 		if (tp->repair_queue == TCP_SEND_QUEUE)
2461c0e88ff0SPavel Emelyanov 			goto recv_sndq;
2462c0e88ff0SPavel Emelyanov 
2463c0e88ff0SPavel Emelyanov 		err = -EINVAL;
2464c0e88ff0SPavel Emelyanov 		if (tp->repair_queue == TCP_NO_QUEUE)
2465c0e88ff0SPavel Emelyanov 			goto out;
2466c0e88ff0SPavel Emelyanov 
2467c0e88ff0SPavel Emelyanov 		/* 'common' recv queue MSG_PEEK-ing */
2468c0e88ff0SPavel Emelyanov 	}
2469c0e88ff0SPavel Emelyanov 
24701da177e4SLinus Torvalds 	seq = &tp->copied_seq;
24711da177e4SLinus Torvalds 	if (flags & MSG_PEEK) {
24721da177e4SLinus Torvalds 		peek_seq = tp->copied_seq;
24731da177e4SLinus Torvalds 		seq = &peek_seq;
24741da177e4SLinus Torvalds 	}
24751da177e4SLinus Torvalds 
24761da177e4SLinus Torvalds 	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
24771da177e4SLinus Torvalds 
24781da177e4SLinus Torvalds 	do {
24791da177e4SLinus Torvalds 		u32 offset;
24801da177e4SLinus Torvalds 
24811da177e4SLinus Torvalds 		/* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
2482b96c51bdSEric Dumazet 		if (unlikely(tp->urg_data) && tp->urg_seq == *seq) {
24831da177e4SLinus Torvalds 			if (copied)
24841da177e4SLinus Torvalds 				break;
24851da177e4SLinus Torvalds 			if (signal_pending(current)) {
24861da177e4SLinus Torvalds 				copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
24871da177e4SLinus Torvalds 				break;
24881da177e4SLinus Torvalds 			}
24891da177e4SLinus Torvalds 		}
24901da177e4SLinus Torvalds 
24911da177e4SLinus Torvalds 		/* Next get a buffer. */
24921da177e4SLinus Torvalds 
2493dfbafc99SSabrina Dubroca 		last = skb_peek_tail(&sk->sk_receive_queue);
249491521944SDavid S. Miller 		skb_queue_walk(&sk->sk_receive_queue, skb) {
2495dfbafc99SSabrina Dubroca 			last = skb;
24961da177e4SLinus Torvalds 			/* Now that we have two receive queues this
24971da177e4SLinus Torvalds 			 * shouldn't happen.
24981da177e4SLinus Torvalds 			 */
2499d792c100SIlpo Järvinen 			if (WARN(before(*seq, TCP_SKB_CB(skb)->seq),
2500e56b8ce3SRandy Dunlap 				 "TCP recvmsg seq # bug: copied %X, seq %X, rcvnxt %X, fl %X\n",
25012af6fd8bSJoe Perches 				 *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt,
2502d792c100SIlpo Järvinen 				 flags))
25031da177e4SLinus Torvalds 				break;
2504d792c100SIlpo Järvinen 
25051da177e4SLinus Torvalds 			offset = *seq - TCP_SKB_CB(skb)->seq;
25069d691539SEric Dumazet 			if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
25079d691539SEric Dumazet 				pr_err_once("%s: found a SYN, please report !\n", __func__);
25081da177e4SLinus Torvalds 				offset--;
25099d691539SEric Dumazet 			}
25101da177e4SLinus Torvalds 			if (offset < skb->len)
25111da177e4SLinus Torvalds 				goto found_ok_skb;
2512e11ecddfSEric Dumazet 			if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
25131da177e4SLinus Torvalds 				goto found_fin_ok;
25142af6fd8bSJoe Perches 			WARN(!(flags & MSG_PEEK),
2515e56b8ce3SRandy Dunlap 			     "TCP recvmsg seq # bug 2: copied %X, seq %X, rcvnxt %X, fl %X\n",
25162af6fd8bSJoe Perches 			     *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags);
251791521944SDavid S. Miller 		}
25181da177e4SLinus Torvalds 
25191da177e4SLinus Torvalds 		/* Well, if we have backlog, try to process it now yet. */
25201da177e4SLinus Torvalds 
25219ed498c6SEric Dumazet 		if (copied >= target && !READ_ONCE(sk->sk_backlog.tail))
25221da177e4SLinus Torvalds 			break;
25231da177e4SLinus Torvalds 
25241da177e4SLinus Torvalds 		if (copied) {
25258bd172b7SEric Dumazet 			if (!timeo ||
25268bd172b7SEric Dumazet 			    sk->sk_err ||
25271da177e4SLinus Torvalds 			    sk->sk_state == TCP_CLOSE ||
25281da177e4SLinus Torvalds 			    (sk->sk_shutdown & RCV_SHUTDOWN) ||
2529518a09efSDavid S. Miller 			    signal_pending(current))
25301da177e4SLinus Torvalds 				break;
25311da177e4SLinus Torvalds 		} else {
25321da177e4SLinus Torvalds 			if (sock_flag(sk, SOCK_DONE))
25331da177e4SLinus Torvalds 				break;
25341da177e4SLinus Torvalds 
25351da177e4SLinus Torvalds 			if (sk->sk_err) {
25361da177e4SLinus Torvalds 				copied = sock_error(sk);
25371da177e4SLinus Torvalds 				break;
25381da177e4SLinus Torvalds 			}
25391da177e4SLinus Torvalds 
25401da177e4SLinus Torvalds 			if (sk->sk_shutdown & RCV_SHUTDOWN)
25411da177e4SLinus Torvalds 				break;
25421da177e4SLinus Torvalds 
25431da177e4SLinus Torvalds 			if (sk->sk_state == TCP_CLOSE) {
25441da177e4SLinus Torvalds 				/* This occurs when user tries to read
25451da177e4SLinus Torvalds 				 * from never connected socket.
25461da177e4SLinus Torvalds 				 */
25471da177e4SLinus Torvalds 				copied = -ENOTCONN;
25481da177e4SLinus Torvalds 				break;
25491da177e4SLinus Torvalds 			}
25501da177e4SLinus Torvalds 
25511da177e4SLinus Torvalds 			if (!timeo) {
25521da177e4SLinus Torvalds 				copied = -EAGAIN;
25531da177e4SLinus Torvalds 				break;
25541da177e4SLinus Torvalds 			}
25551da177e4SLinus Torvalds 
25561da177e4SLinus Torvalds 			if (signal_pending(current)) {
25571da177e4SLinus Torvalds 				copied = sock_intr_errno(timeo);
25581da177e4SLinus Torvalds 				break;
25591da177e4SLinus Torvalds 			}
25601da177e4SLinus Torvalds 		}
25611da177e4SLinus Torvalds 
25621da177e4SLinus Torvalds 		if (copied >= target) {
25631da177e4SLinus Torvalds 			/* Do not sleep, just process backlog. */
256493afcfd1SEric Dumazet 			__sk_flush_backlog(sk);
2565dfbafc99SSabrina Dubroca 		} else {
256629fbc26eSEric Dumazet 			tcp_cleanup_rbuf(sk, copied);
2567dfbafc99SSabrina Dubroca 			sk_wait_data(sk, &timeo, last);
2568dfbafc99SSabrina Dubroca 		}
25691da177e4SLinus Torvalds 
257077527313SIlpo Järvinen 		if ((flags & MSG_PEEK) &&
257177527313SIlpo Järvinen 		    (peek_seq - copied - urg_hole != tp->copied_seq)) {
2572e87cc472SJoe Perches 			net_dbg_ratelimited("TCP(%s:%d): Application bug, race in MSG_PEEK\n",
2573e87cc472SJoe Perches 					    current->comm,
2574e87cc472SJoe Perches 					    task_pid_nr(current));
25751da177e4SLinus Torvalds 			peek_seq = tp->copied_seq;
25761da177e4SLinus Torvalds 		}
25771da177e4SLinus Torvalds 		continue;
25781da177e4SLinus Torvalds 
25791da177e4SLinus Torvalds found_ok_skb:
25801da177e4SLinus Torvalds 		/* Ok so how much can we use? */
25811da177e4SLinus Torvalds 		used = skb->len - offset;
25821da177e4SLinus Torvalds 		if (len < used)
25831da177e4SLinus Torvalds 			used = len;
25841da177e4SLinus Torvalds 
25851da177e4SLinus Torvalds 		/* Do we have urgent data here? */
2586b96c51bdSEric Dumazet 		if (unlikely(tp->urg_data)) {
25871da177e4SLinus Torvalds 			u32 urg_offset = tp->urg_seq - *seq;
25881da177e4SLinus Torvalds 			if (urg_offset < used) {
25891da177e4SLinus Torvalds 				if (!urg_offset) {
25901da177e4SLinus Torvalds 					if (!sock_flag(sk, SOCK_URGINLINE)) {
25917db48e98SEric Dumazet 						WRITE_ONCE(*seq, *seq + 1);
259277527313SIlpo Järvinen 						urg_hole++;
25931da177e4SLinus Torvalds 						offset++;
25941da177e4SLinus Torvalds 						used--;
25951da177e4SLinus Torvalds 						if (!used)
25961da177e4SLinus Torvalds 							goto skip_copy;
25971da177e4SLinus Torvalds 					}
25981da177e4SLinus Torvalds 				} else
25991da177e4SLinus Torvalds 					used = urg_offset;
26001da177e4SLinus Torvalds 			}
26011da177e4SLinus Torvalds 		}
26021da177e4SLinus Torvalds 
26031da177e4SLinus Torvalds 		if (!(flags & MSG_TRUNC)) {
260451f3d02bSDavid S. Miller 			err = skb_copy_datagram_msg(skb, offset, msg, used);
26051da177e4SLinus Torvalds 			if (err) {
26061da177e4SLinus Torvalds 				/* Exception. Bailout! */
26071da177e4SLinus Torvalds 				if (!copied)
26081da177e4SLinus Torvalds 					copied = -EFAULT;
26091da177e4SLinus Torvalds 				break;
26101da177e4SLinus Torvalds 			}
26111da177e4SLinus Torvalds 		}
26121da177e4SLinus Torvalds 
26137db48e98SEric Dumazet 		WRITE_ONCE(*seq, *seq + used);
26141da177e4SLinus Torvalds 		copied += used;
26151da177e4SLinus Torvalds 		len -= used;
26161da177e4SLinus Torvalds 
26171da177e4SLinus Torvalds 		tcp_rcv_space_adjust(sk);
26181da177e4SLinus Torvalds 
26191da177e4SLinus Torvalds skip_copy:
2620b96c51bdSEric Dumazet 		if (unlikely(tp->urg_data) && after(tp->copied_seq, tp->urg_seq)) {
26217b6a893aSEric Dumazet 			WRITE_ONCE(tp->urg_data, 0);
262231770e34SFlorian Westphal 			tcp_fast_path_check(sk);
262331770e34SFlorian Westphal 		}
26241da177e4SLinus Torvalds 
262598aaa913SMike Maloney 		if (TCP_SKB_CB(skb)->has_rxtstamp) {
26262cd81161SArjun Roy 			tcp_update_recv_tstamps(skb, tss);
2627925bba24SArjun Roy 			*cmsg_flags |= TCP_CMSG_TS;
262898aaa913SMike Maloney 		}
2629cc4de047SKelly Littlepage 
2630cc4de047SKelly Littlepage 		if (used + offset < skb->len)
2631cc4de047SKelly Littlepage 			continue;
2632cc4de047SKelly Littlepage 
2633e11ecddfSEric Dumazet 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
26341da177e4SLinus Torvalds 			goto found_fin_ok;
26357bced397SDan Williams 		if (!(flags & MSG_PEEK))
26363df684c1SEric Dumazet 			tcp_eat_recv_skb(sk, skb);
26371da177e4SLinus Torvalds 		continue;
26381da177e4SLinus Torvalds 
26391da177e4SLinus Torvalds found_fin_ok:
26401da177e4SLinus Torvalds 		/* Process the FIN. */
26417db48e98SEric Dumazet 		WRITE_ONCE(*seq, *seq + 1);
26427bced397SDan Williams 		if (!(flags & MSG_PEEK))
26433df684c1SEric Dumazet 			tcp_eat_recv_skb(sk, skb);
26441da177e4SLinus Torvalds 		break;
26451da177e4SLinus Torvalds 	} while (len > 0);
26461da177e4SLinus Torvalds 
26471da177e4SLinus Torvalds 	/* According to UNIX98, msg_name/msg_namelen are ignored
26481da177e4SLinus Torvalds 	 * on connected socket. I was just happy when found this 8) --ANK
26491da177e4SLinus Torvalds 	 */
26501da177e4SLinus Torvalds 
26511da177e4SLinus Torvalds 	/* Clean up data we have read: This will do ACK frames. */
26520e4b4992SChris Leech 	tcp_cleanup_rbuf(sk, copied);
26531da177e4SLinus Torvalds 	return copied;
26541da177e4SLinus Torvalds 
26551da177e4SLinus Torvalds out:
26561da177e4SLinus Torvalds 	return err;
26571da177e4SLinus Torvalds 
26581da177e4SLinus Torvalds recv_urg:
2659377f0a08SRami Rosen 	err = tcp_recv_urg(sk, msg, len, flags);
26601da177e4SLinus Torvalds 	goto out;
2661c0e88ff0SPavel Emelyanov 
2662c0e88ff0SPavel Emelyanov recv_sndq:
2663c0e88ff0SPavel Emelyanov 	err = tcp_peek_sndq(sk, msg, len);
2664c0e88ff0SPavel Emelyanov 	goto out;
26651da177e4SLinus Torvalds }
26662cd81161SArjun Roy 
2667ec095263SOliver Hartkopp int tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags,
2668ec095263SOliver Hartkopp 		int *addr_len)
26692cd81161SArjun Roy {
2670f94fd25cSJens Axboe 	int cmsg_flags = 0, ret;
26712cd81161SArjun Roy 	struct scm_timestamping_internal tss;
26722cd81161SArjun Roy 
26732cd81161SArjun Roy 	if (unlikely(flags & MSG_ERRQUEUE))
26742cd81161SArjun Roy 		return inet_recv_error(sk, msg, len, addr_len);
26752cd81161SArjun Roy 
26762cd81161SArjun Roy 	if (sk_can_busy_loop(sk) &&
26772cd81161SArjun Roy 	    skb_queue_empty_lockless(&sk->sk_receive_queue) &&
26782cd81161SArjun Roy 	    sk->sk_state == TCP_ESTABLISHED)
2679ec095263SOliver Hartkopp 		sk_busy_loop(sk, flags & MSG_DONTWAIT);
26802cd81161SArjun Roy 
26812cd81161SArjun Roy 	lock_sock(sk);
2682ec095263SOliver Hartkopp 	ret = tcp_recvmsg_locked(sk, msg, len, flags, &tss, &cmsg_flags);
26832cd81161SArjun Roy 	release_sock(sk);
26842cd81161SArjun Roy 
2685f94fd25cSJens Axboe 	if ((cmsg_flags || msg->msg_get_inq) && ret >= 0) {
2686925bba24SArjun Roy 		if (cmsg_flags & TCP_CMSG_TS)
26872cd81161SArjun Roy 			tcp_recv_timestamp(msg, sk, &tss);
2688f94fd25cSJens Axboe 		if (msg->msg_get_inq) {
2689f94fd25cSJens Axboe 			msg->msg_inq = tcp_inq_hint(sk);
2690f94fd25cSJens Axboe 			if (cmsg_flags & TCP_CMSG_INQ)
2691f94fd25cSJens Axboe 				put_cmsg(msg, SOL_TCP, TCP_CM_INQ,
2692f94fd25cSJens Axboe 					 sizeof(msg->msg_inq), &msg->msg_inq);
26932cd81161SArjun Roy 		}
26942cd81161SArjun Roy 	}
26952cd81161SArjun Roy 	return ret;
26962cd81161SArjun Roy }
26974bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_recvmsg);
26981da177e4SLinus Torvalds 
2699490d5046SIlpo Järvinen void tcp_set_state(struct sock *sk, int state)
2700490d5046SIlpo Järvinen {
2701490d5046SIlpo Järvinen 	int oldstate = sk->sk_state;
2702490d5046SIlpo Järvinen 
2703d4487491SLawrence Brakmo 	/* We defined a new enum for TCP states that are exported in BPF
2704d4487491SLawrence Brakmo 	 * so as not force the internal TCP states to be frozen. The
2705d4487491SLawrence Brakmo 	 * following checks will detect if an internal state value ever
2706d4487491SLawrence Brakmo 	 * differs from the BPF value. If this ever happens, then we will
2707d4487491SLawrence Brakmo 	 * need to remap the internal value to the BPF value before calling
2708d4487491SLawrence Brakmo 	 * tcp_call_bpf_2arg.
2709d4487491SLawrence Brakmo 	 */
2710d4487491SLawrence Brakmo 	BUILD_BUG_ON((int)BPF_TCP_ESTABLISHED != (int)TCP_ESTABLISHED);
2711d4487491SLawrence Brakmo 	BUILD_BUG_ON((int)BPF_TCP_SYN_SENT != (int)TCP_SYN_SENT);
2712d4487491SLawrence Brakmo 	BUILD_BUG_ON((int)BPF_TCP_SYN_RECV != (int)TCP_SYN_RECV);
2713d4487491SLawrence Brakmo 	BUILD_BUG_ON((int)BPF_TCP_FIN_WAIT1 != (int)TCP_FIN_WAIT1);
2714d4487491SLawrence Brakmo 	BUILD_BUG_ON((int)BPF_TCP_FIN_WAIT2 != (int)TCP_FIN_WAIT2);
2715d4487491SLawrence Brakmo 	BUILD_BUG_ON((int)BPF_TCP_TIME_WAIT != (int)TCP_TIME_WAIT);
2716d4487491SLawrence Brakmo 	BUILD_BUG_ON((int)BPF_TCP_CLOSE != (int)TCP_CLOSE);
2717d4487491SLawrence Brakmo 	BUILD_BUG_ON((int)BPF_TCP_CLOSE_WAIT != (int)TCP_CLOSE_WAIT);
2718d4487491SLawrence Brakmo 	BUILD_BUG_ON((int)BPF_TCP_LAST_ACK != (int)TCP_LAST_ACK);
2719d4487491SLawrence Brakmo 	BUILD_BUG_ON((int)BPF_TCP_LISTEN != (int)TCP_LISTEN);
2720d4487491SLawrence Brakmo 	BUILD_BUG_ON((int)BPF_TCP_CLOSING != (int)TCP_CLOSING);
2721d4487491SLawrence Brakmo 	BUILD_BUG_ON((int)BPF_TCP_NEW_SYN_RECV != (int)TCP_NEW_SYN_RECV);
2722d4487491SLawrence Brakmo 	BUILD_BUG_ON((int)BPF_TCP_MAX_STATES != (int)TCP_MAX_STATES);
2723d4487491SLawrence Brakmo 
272497a19cafSYonghong Song 	/* bpf uapi header bpf.h defines an anonymous enum with values
272597a19cafSYonghong Song 	 * BPF_TCP_* used by bpf programs. Currently gcc built vmlinux
272697a19cafSYonghong Song 	 * is able to emit this enum in DWARF due to the above BUILD_BUG_ON.
272797a19cafSYonghong Song 	 * But clang built vmlinux does not have this enum in DWARF
272897a19cafSYonghong Song 	 * since clang removes the above code before generating IR/debuginfo.
272997a19cafSYonghong Song 	 * Let us explicitly emit the type debuginfo to ensure the
273097a19cafSYonghong Song 	 * above-mentioned anonymous enum in the vmlinux DWARF and hence BTF
273197a19cafSYonghong Song 	 * regardless of which compiler is used.
273297a19cafSYonghong Song 	 */
273397a19cafSYonghong Song 	BTF_TYPE_EMIT_ENUM(BPF_TCP_ESTABLISHED);
273497a19cafSYonghong Song 
2735d4487491SLawrence Brakmo 	if (BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), BPF_SOCK_OPS_STATE_CB_FLAG))
2736d4487491SLawrence Brakmo 		tcp_call_bpf_2arg(sk, BPF_SOCK_OPS_STATE_CB, oldstate, state);
2737e8fce239SSong Liu 
2738490d5046SIlpo Järvinen 	switch (state) {
2739490d5046SIlpo Järvinen 	case TCP_ESTABLISHED:
2740490d5046SIlpo Järvinen 		if (oldstate != TCP_ESTABLISHED)
274181cc8a75SPavel Emelyanov 			TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
2742490d5046SIlpo Järvinen 		break;
2743490d5046SIlpo Järvinen 
2744490d5046SIlpo Järvinen 	case TCP_CLOSE:
2745490d5046SIlpo Järvinen 		if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
274681cc8a75SPavel Emelyanov 			TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS);
2747490d5046SIlpo Järvinen 
2748490d5046SIlpo Järvinen 		sk->sk_prot->unhash(sk);
2749490d5046SIlpo Järvinen 		if (inet_csk(sk)->icsk_bind_hash &&
2750490d5046SIlpo Järvinen 		    !(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
2751ab1e0a13SArnaldo Carvalho de Melo 			inet_put_port(sk);
2752a8eceea8SJoe Perches 		fallthrough;
2753490d5046SIlpo Järvinen 	default:
2754490d5046SIlpo Järvinen 		if (oldstate == TCP_ESTABLISHED)
275574688e48SPavel Emelyanov 			TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
2756490d5046SIlpo Järvinen 	}
2757490d5046SIlpo Järvinen 
2758490d5046SIlpo Järvinen 	/* Change state AFTER socket is unhashed to avoid closed
2759490d5046SIlpo Järvinen 	 * socket sitting in hash tables.
2760490d5046SIlpo Järvinen 	 */
2761563e0bb0SYafang Shao 	inet_sk_state_store(sk, state);
2762490d5046SIlpo Järvinen }
2763490d5046SIlpo Järvinen EXPORT_SYMBOL_GPL(tcp_set_state);
2764490d5046SIlpo Järvinen 
27651da177e4SLinus Torvalds /*
27661da177e4SLinus Torvalds  *	State processing on a close. This implements the state shift for
27671da177e4SLinus Torvalds  *	sending our FIN frame. Note that we only send a FIN for some
27681da177e4SLinus Torvalds  *	states. A shutdown() may have already sent the FIN, or we may be
27691da177e4SLinus Torvalds  *	closed.
27701da177e4SLinus Torvalds  */
27711da177e4SLinus Torvalds 
27729b5b5cffSArjan van de Ven static const unsigned char new_state[16] = {
27731da177e4SLinus Torvalds   /* current state:        new state:      action:	*/
27740980c1e3SEric Dumazet   [0 /* (Invalid) */]	= TCP_CLOSE,
27750980c1e3SEric Dumazet   [TCP_ESTABLISHED]	= TCP_FIN_WAIT1 | TCP_ACTION_FIN,
27760980c1e3SEric Dumazet   [TCP_SYN_SENT]	= TCP_CLOSE,
27770980c1e3SEric Dumazet   [TCP_SYN_RECV]	= TCP_FIN_WAIT1 | TCP_ACTION_FIN,
27780980c1e3SEric Dumazet   [TCP_FIN_WAIT1]	= TCP_FIN_WAIT1,
27790980c1e3SEric Dumazet   [TCP_FIN_WAIT2]	= TCP_FIN_WAIT2,
27800980c1e3SEric Dumazet   [TCP_TIME_WAIT]	= TCP_CLOSE,
27810980c1e3SEric Dumazet   [TCP_CLOSE]		= TCP_CLOSE,
27820980c1e3SEric Dumazet   [TCP_CLOSE_WAIT]	= TCP_LAST_ACK  | TCP_ACTION_FIN,
27830980c1e3SEric Dumazet   [TCP_LAST_ACK]	= TCP_LAST_ACK,
27840980c1e3SEric Dumazet   [TCP_LISTEN]		= TCP_CLOSE,
27850980c1e3SEric Dumazet   [TCP_CLOSING]		= TCP_CLOSING,
27860980c1e3SEric Dumazet   [TCP_NEW_SYN_RECV]	= TCP_CLOSE,	/* should not happen ! */
27871da177e4SLinus Torvalds };
27881da177e4SLinus Torvalds 
27891da177e4SLinus Torvalds static int tcp_close_state(struct sock *sk)
27901da177e4SLinus Torvalds {
27911da177e4SLinus Torvalds 	int next = (int)new_state[sk->sk_state];
27921da177e4SLinus Torvalds 	int ns = next & TCP_STATE_MASK;
27931da177e4SLinus Torvalds 
27941da177e4SLinus Torvalds 	tcp_set_state(sk, ns);
27951da177e4SLinus Torvalds 
27961da177e4SLinus Torvalds 	return next & TCP_ACTION_FIN;
27971da177e4SLinus Torvalds }
27981da177e4SLinus Torvalds 
27991da177e4SLinus Torvalds /*
28001da177e4SLinus Torvalds  *	Shutdown the sending side of a connection. Much like close except
28011f29b058SSatoru SATOH  *	that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD).
28021da177e4SLinus Torvalds  */
28031da177e4SLinus Torvalds 
28041da177e4SLinus Torvalds void tcp_shutdown(struct sock *sk, int how)
28051da177e4SLinus Torvalds {
28061da177e4SLinus Torvalds 	/*	We need to grab some memory, and put together a FIN,
28071da177e4SLinus Torvalds 	 *	and then put it into the queue to be sent.
28081da177e4SLinus Torvalds 	 *		Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
28091da177e4SLinus Torvalds 	 */
28101da177e4SLinus Torvalds 	if (!(how & SEND_SHUTDOWN))
28111da177e4SLinus Torvalds 		return;
28121da177e4SLinus Torvalds 
28131da177e4SLinus Torvalds 	/* If we've already sent a FIN, or it's a closed state, skip this. */
28141da177e4SLinus Torvalds 	if ((1 << sk->sk_state) &
28151da177e4SLinus Torvalds 	    (TCPF_ESTABLISHED | TCPF_SYN_SENT |
28161da177e4SLinus Torvalds 	     TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) {
28171da177e4SLinus Torvalds 		/* Clear out any half completed packets.  FIN if needed. */
28181da177e4SLinus Torvalds 		if (tcp_close_state(sk))
28191da177e4SLinus Torvalds 			tcp_send_fin(sk);
28201da177e4SLinus Torvalds 	}
28211da177e4SLinus Torvalds }
28224bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_shutdown);
28231da177e4SLinus Torvalds 
282419757cebSEric Dumazet int tcp_orphan_count_sum(void)
282519757cebSEric Dumazet {
282619757cebSEric Dumazet 	int i, total = 0;
282719757cebSEric Dumazet 
282819757cebSEric Dumazet 	for_each_possible_cpu(i)
282919757cebSEric Dumazet 		total += per_cpu(tcp_orphan_count, i);
283019757cebSEric Dumazet 
283119757cebSEric Dumazet 	return max(total, 0);
283219757cebSEric Dumazet }
283319757cebSEric Dumazet 
283419757cebSEric Dumazet static int tcp_orphan_cache;
283519757cebSEric Dumazet static struct timer_list tcp_orphan_timer;
283619757cebSEric Dumazet #define TCP_ORPHAN_TIMER_PERIOD msecs_to_jiffies(100)
283719757cebSEric Dumazet 
283819757cebSEric Dumazet static void tcp_orphan_update(struct timer_list *unused)
283919757cebSEric Dumazet {
284019757cebSEric Dumazet 	WRITE_ONCE(tcp_orphan_cache, tcp_orphan_count_sum());
284119757cebSEric Dumazet 	mod_timer(&tcp_orphan_timer, jiffies + TCP_ORPHAN_TIMER_PERIOD);
284219757cebSEric Dumazet }
284319757cebSEric Dumazet 
284419757cebSEric Dumazet static bool tcp_too_many_orphans(int shift)
284519757cebSEric Dumazet {
284647e6ab24SKuniyuki Iwashima 	return READ_ONCE(tcp_orphan_cache) << shift >
284747e6ab24SKuniyuki Iwashima 		READ_ONCE(sysctl_tcp_max_orphans);
284819757cebSEric Dumazet }
284919757cebSEric Dumazet 
2850efcdbf24SArun Sharma bool tcp_check_oom(struct sock *sk, int shift)
2851efcdbf24SArun Sharma {
2852efcdbf24SArun Sharma 	bool too_many_orphans, out_of_socket_memory;
2853efcdbf24SArun Sharma 
285419757cebSEric Dumazet 	too_many_orphans = tcp_too_many_orphans(shift);
2855efcdbf24SArun Sharma 	out_of_socket_memory = tcp_out_of_memory(sk);
2856efcdbf24SArun Sharma 
2857e87cc472SJoe Perches 	if (too_many_orphans)
2858e87cc472SJoe Perches 		net_info_ratelimited("too many orphaned sockets\n");
2859e87cc472SJoe Perches 	if (out_of_socket_memory)
2860e87cc472SJoe Perches 		net_info_ratelimited("out of memory -- consider tuning tcp_mem\n");
2861efcdbf24SArun Sharma 	return too_many_orphans || out_of_socket_memory;
2862efcdbf24SArun Sharma }
2863efcdbf24SArun Sharma 
286477c3c956SPaolo Abeni void __tcp_close(struct sock *sk, long timeout)
28651da177e4SLinus Torvalds {
28661da177e4SLinus Torvalds 	struct sk_buff *skb;
28671da177e4SLinus Torvalds 	int data_was_unread = 0;
286875c2d907SHerbert Xu 	int state;
28691da177e4SLinus Torvalds 
28701da177e4SLinus Torvalds 	sk->sk_shutdown = SHUTDOWN_MASK;
28711da177e4SLinus Torvalds 
28721da177e4SLinus Torvalds 	if (sk->sk_state == TCP_LISTEN) {
28731da177e4SLinus Torvalds 		tcp_set_state(sk, TCP_CLOSE);
28741da177e4SLinus Torvalds 
28751da177e4SLinus Torvalds 		/* Special case. */
28760a5578cfSArnaldo Carvalho de Melo 		inet_csk_listen_stop(sk);
28771da177e4SLinus Torvalds 
28781da177e4SLinus Torvalds 		goto adjudge_to_death;
28791da177e4SLinus Torvalds 	}
28801da177e4SLinus Torvalds 
28811da177e4SLinus Torvalds 	/*  We need to flush the recv. buffs.  We do this only on the
28821da177e4SLinus Torvalds 	 *  descriptor close, not protocol-sourced closes, because the
28831da177e4SLinus Torvalds 	 *  reader process may not have drained the data yet!
28841da177e4SLinus Torvalds 	 */
28851da177e4SLinus Torvalds 	while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
2886e11ecddfSEric Dumazet 		u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq;
2887e11ecddfSEric Dumazet 
2888e11ecddfSEric Dumazet 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
2889e11ecddfSEric Dumazet 			len--;
28901da177e4SLinus Torvalds 		data_was_unread += len;
28911da177e4SLinus Torvalds 		__kfree_skb(skb);
28921da177e4SLinus Torvalds 	}
28931da177e4SLinus Torvalds 
2894565b7b2dSKonstantin Khorenko 	/* If socket has been already reset (e.g. in tcp_reset()) - kill it. */
2895565b7b2dSKonstantin Khorenko 	if (sk->sk_state == TCP_CLOSE)
2896565b7b2dSKonstantin Khorenko 		goto adjudge_to_death;
2897565b7b2dSKonstantin Khorenko 
289865bb723cSGerrit Renker 	/* As outlined in RFC 2525, section 2.17, we send a RST here because
289965bb723cSGerrit Renker 	 * data was lost. To witness the awful effects of the old behavior of
290065bb723cSGerrit Renker 	 * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk
290165bb723cSGerrit Renker 	 * GET in an FTP client, suspend the process, wait for the client to
290265bb723cSGerrit Renker 	 * advertise a zero window, then kill -9 the FTP client, wheee...
290365bb723cSGerrit Renker 	 * Note: timeout is always zero in such a case.
29041da177e4SLinus Torvalds 	 */
2905ee995283SPavel Emelyanov 	if (unlikely(tcp_sk(sk)->repair)) {
2906ee995283SPavel Emelyanov 		sk->sk_prot->disconnect(sk, 0);
2907ee995283SPavel Emelyanov 	} else if (data_was_unread) {
29081da177e4SLinus Torvalds 		/* Unread data was tossed, zap the connection. */
29096aef70a8SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE);
29101da177e4SLinus Torvalds 		tcp_set_state(sk, TCP_CLOSE);
2911aa133076SWu Fengguang 		tcp_send_active_reset(sk, sk->sk_allocation);
29121da177e4SLinus Torvalds 	} else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
29131da177e4SLinus Torvalds 		/* Check zero linger _after_ checking for unread data. */
29141da177e4SLinus Torvalds 		sk->sk_prot->disconnect(sk, 0);
29156aef70a8SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
29161da177e4SLinus Torvalds 	} else if (tcp_close_state(sk)) {
29171da177e4SLinus Torvalds 		/* We FIN if the application ate all the data before
29181da177e4SLinus Torvalds 		 * zapping the connection.
29191da177e4SLinus Torvalds 		 */
29201da177e4SLinus Torvalds 
29211da177e4SLinus Torvalds 		/* RED-PEN. Formally speaking, we have broken TCP state
29221da177e4SLinus Torvalds 		 * machine. State transitions:
29231da177e4SLinus Torvalds 		 *
29241da177e4SLinus Torvalds 		 * TCP_ESTABLISHED -> TCP_FIN_WAIT1
29251da177e4SLinus Torvalds 		 * TCP_SYN_RECV	-> TCP_FIN_WAIT1 (forget it, it's impossible)
29261da177e4SLinus Torvalds 		 * TCP_CLOSE_WAIT -> TCP_LAST_ACK
29271da177e4SLinus Torvalds 		 *
29281da177e4SLinus Torvalds 		 * are legal only when FIN has been sent (i.e. in window),
29291da177e4SLinus Torvalds 		 * rather than queued out of window. Purists blame.
29301da177e4SLinus Torvalds 		 *
29311da177e4SLinus Torvalds 		 * F.e. "RFC state" is ESTABLISHED,
29321da177e4SLinus Torvalds 		 * if Linux state is FIN-WAIT-1, but FIN is still not sent.
29331da177e4SLinus Torvalds 		 *
29341da177e4SLinus Torvalds 		 * The visible declinations are that sometimes
29351da177e4SLinus Torvalds 		 * we enter time-wait state, when it is not required really
29361da177e4SLinus Torvalds 		 * (harmless), do not send active resets, when they are
29371da177e4SLinus Torvalds 		 * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
29381da177e4SLinus Torvalds 		 * they look as CLOSING or LAST_ACK for Linux)
29391da177e4SLinus Torvalds 		 * Probably, I missed some more holelets.
29401da177e4SLinus Torvalds 		 * 						--ANK
29418336886fSJerry Chu 		 * XXX (TFO) - To start off we don't support SYN+ACK+FIN
29428336886fSJerry Chu 		 * in a single packet! (May consider it later but will
29438336886fSJerry Chu 		 * probably need API support or TCP_CORK SYN-ACK until
29448336886fSJerry Chu 		 * data is written and socket is closed.)
29451da177e4SLinus Torvalds 		 */
29461da177e4SLinus Torvalds 		tcp_send_fin(sk);
29471da177e4SLinus Torvalds 	}
29481da177e4SLinus Torvalds 
29491da177e4SLinus Torvalds 	sk_stream_wait_close(sk, timeout);
29501da177e4SLinus Torvalds 
29511da177e4SLinus Torvalds adjudge_to_death:
295275c2d907SHerbert Xu 	state = sk->sk_state;
295375c2d907SHerbert Xu 	sock_hold(sk);
295475c2d907SHerbert Xu 	sock_orphan(sk);
295575c2d907SHerbert Xu 
29561da177e4SLinus Torvalds 	local_bh_disable();
29571da177e4SLinus Torvalds 	bh_lock_sock(sk);
29588873c064SEric Dumazet 	/* remove backlog if any, without releasing ownership. */
29598873c064SEric Dumazet 	__release_sock(sk);
29601da177e4SLinus Torvalds 
296119757cebSEric Dumazet 	this_cpu_inc(tcp_orphan_count);
2962eb4dea58SHerbert Xu 
296375c2d907SHerbert Xu 	/* Have we already been destroyed by a softirq or backlog? */
296475c2d907SHerbert Xu 	if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE)
296575c2d907SHerbert Xu 		goto out;
29661da177e4SLinus Torvalds 
29671da177e4SLinus Torvalds 	/*	This is a (useful) BSD violating of the RFC. There is a
29681da177e4SLinus Torvalds 	 *	problem with TCP as specified in that the other end could
29691da177e4SLinus Torvalds 	 *	keep a socket open forever with no application left this end.
2970b10bd54cSJesper Juhl 	 *	We use a 1 minute timeout (about the same as BSD) then kill
29711da177e4SLinus Torvalds 	 *	our end. If they send after that then tough - BUT: long enough
29721da177e4SLinus Torvalds 	 *	that we won't make the old 4*rto = almost no time - whoops
29731da177e4SLinus Torvalds 	 *	reset mistake.
29741da177e4SLinus Torvalds 	 *
29751da177e4SLinus Torvalds 	 *	Nope, it was not mistake. It is really desired behaviour
29761da177e4SLinus Torvalds 	 *	f.e. on http servers, when such sockets are useless, but
29771da177e4SLinus Torvalds 	 *	consume significant resources. Let's do it with special
29781da177e4SLinus Torvalds 	 *	linger2	option.					--ANK
29791da177e4SLinus Torvalds 	 */
29801da177e4SLinus Torvalds 
29811da177e4SLinus Torvalds 	if (sk->sk_state == TCP_FIN_WAIT2) {
29821da177e4SLinus Torvalds 		struct tcp_sock *tp = tcp_sk(sk);
29831da177e4SLinus Torvalds 		if (tp->linger2 < 0) {
29841da177e4SLinus Torvalds 			tcp_set_state(sk, TCP_CLOSE);
29851da177e4SLinus Torvalds 			tcp_send_active_reset(sk, GFP_ATOMIC);
298602a1d6e7SEric Dumazet 			__NET_INC_STATS(sock_net(sk),
2987de0744afSPavel Emelyanov 					LINUX_MIB_TCPABORTONLINGER);
29881da177e4SLinus Torvalds 		} else {
2989463c84b9SArnaldo Carvalho de Melo 			const int tmo = tcp_fin_time(sk);
29901da177e4SLinus Torvalds 
29911da177e4SLinus Torvalds 			if (tmo > TCP_TIMEWAIT_LEN) {
299252499afeSDavid S. Miller 				inet_csk_reset_keepalive_timer(sk,
299352499afeSDavid S. Miller 						tmo - TCP_TIMEWAIT_LEN);
29941da177e4SLinus Torvalds 			} else {
29951da177e4SLinus Torvalds 				tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
29961da177e4SLinus Torvalds 				goto out;
29971da177e4SLinus Torvalds 			}
29981da177e4SLinus Torvalds 		}
29991da177e4SLinus Torvalds 	}
30001da177e4SLinus Torvalds 	if (sk->sk_state != TCP_CLOSE) {
3001efcdbf24SArun Sharma 		if (tcp_check_oom(sk, 0)) {
30021da177e4SLinus Torvalds 			tcp_set_state(sk, TCP_CLOSE);
30031da177e4SLinus Torvalds 			tcp_send_active_reset(sk, GFP_ATOMIC);
300402a1d6e7SEric Dumazet 			__NET_INC_STATS(sock_net(sk),
3005de0744afSPavel Emelyanov 					LINUX_MIB_TCPABORTONMEMORY);
30064ee806d5SDan Streetman 		} else if (!check_net(sock_net(sk))) {
30074ee806d5SDan Streetman 			/* Not possible to send reset; just close */
30084ee806d5SDan Streetman 			tcp_set_state(sk, TCP_CLOSE);
30091da177e4SLinus Torvalds 		}
30101da177e4SLinus Torvalds 	}
30111da177e4SLinus Torvalds 
30128336886fSJerry Chu 	if (sk->sk_state == TCP_CLOSE) {
3013d983ea6fSEric Dumazet 		struct request_sock *req;
3014d983ea6fSEric Dumazet 
3015d983ea6fSEric Dumazet 		req = rcu_dereference_protected(tcp_sk(sk)->fastopen_rsk,
3016d983ea6fSEric Dumazet 						lockdep_sock_is_held(sk));
30178336886fSJerry Chu 		/* We could get here with a non-NULL req if the socket is
30188336886fSJerry Chu 		 * aborted (e.g., closed with unread data) before 3WHS
30198336886fSJerry Chu 		 * finishes.
30208336886fSJerry Chu 		 */
302100db4124SIan Morris 		if (req)
30228336886fSJerry Chu 			reqsk_fastopen_remove(sk, req, false);
30230a5578cfSArnaldo Carvalho de Melo 		inet_csk_destroy_sock(sk);
30248336886fSJerry Chu 	}
30251da177e4SLinus Torvalds 	/* Otherwise, socket is reprieved until protocol close. */
30261da177e4SLinus Torvalds 
30271da177e4SLinus Torvalds out:
30281da177e4SLinus Torvalds 	bh_unlock_sock(sk);
30291da177e4SLinus Torvalds 	local_bh_enable();
303077c3c956SPaolo Abeni }
303177c3c956SPaolo Abeni 
303277c3c956SPaolo Abeni void tcp_close(struct sock *sk, long timeout)
303377c3c956SPaolo Abeni {
303477c3c956SPaolo Abeni 	lock_sock(sk);
303577c3c956SPaolo Abeni 	__tcp_close(sk, timeout);
30368873c064SEric Dumazet 	release_sock(sk);
30371da177e4SLinus Torvalds 	sock_put(sk);
30381da177e4SLinus Torvalds }
30394bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_close);
30401da177e4SLinus Torvalds 
30411da177e4SLinus Torvalds /* These states need RST on ABORT according to RFC793 */
30421da177e4SLinus Torvalds 
3043a2a385d6SEric Dumazet static inline bool tcp_need_reset(int state)
30441da177e4SLinus Torvalds {
30451da177e4SLinus Torvalds 	return (1 << state) &
30461da177e4SLinus Torvalds 	       (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
3047a7150e38SEric Dumazet 		TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
30481da177e4SLinus Torvalds }
30491da177e4SLinus Torvalds 
305075c119afSEric Dumazet static void tcp_rtx_queue_purge(struct sock *sk)
305175c119afSEric Dumazet {
305275c119afSEric Dumazet 	struct rb_node *p = rb_first(&sk->tcp_rtx_queue);
305375c119afSEric Dumazet 
30542bec445fSEric Dumazet 	tcp_sk(sk)->highest_sack = NULL;
305575c119afSEric Dumazet 	while (p) {
305675c119afSEric Dumazet 		struct sk_buff *skb = rb_to_skb(p);
305775c119afSEric Dumazet 
305875c119afSEric Dumazet 		p = rb_next(p);
305975c119afSEric Dumazet 		/* Since we are deleting whole queue, no need to
306075c119afSEric Dumazet 		 * list_del(&skb->tcp_tsorted_anchor)
306175c119afSEric Dumazet 		 */
306275c119afSEric Dumazet 		tcp_rtx_queue_unlink(skb, sk);
306303271f3aSTalal Ahmad 		tcp_wmem_free_skb(sk, skb);
306475c119afSEric Dumazet 	}
306575c119afSEric Dumazet }
306675c119afSEric Dumazet 
3067ac3f09baSEric Dumazet void tcp_write_queue_purge(struct sock *sk)
3068ac3f09baSEric Dumazet {
3069ac3f09baSEric Dumazet 	struct sk_buff *skb;
3070ac3f09baSEric Dumazet 
3071ac3f09baSEric Dumazet 	tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
3072ac3f09baSEric Dumazet 	while ((skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) {
3073ac3f09baSEric Dumazet 		tcp_skb_tsorted_anchor_cleanup(skb);
307403271f3aSTalal Ahmad 		tcp_wmem_free_skb(sk, skb);
3075ac3f09baSEric Dumazet 	}
307675c119afSEric Dumazet 	tcp_rtx_queue_purge(sk);
3077ac3f09baSEric Dumazet 	INIT_LIST_HEAD(&tcp_sk(sk)->tsorted_sent_queue);
3078ac3f09baSEric Dumazet 	tcp_clear_all_retrans_hints(tcp_sk(sk));
3079bffd168cSSoheil Hassas Yeganeh 	tcp_sk(sk)->packets_out = 0;
308004c03114SEric Dumazet 	inet_csk(sk)->icsk_backoff = 0;
3081ac3f09baSEric Dumazet }
3082ac3f09baSEric Dumazet 
30831da177e4SLinus Torvalds int tcp_disconnect(struct sock *sk, int flags)
30841da177e4SLinus Torvalds {
30851da177e4SLinus Torvalds 	struct inet_sock *inet = inet_sk(sk);
3086463c84b9SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
30871da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
30881da177e4SLinus Torvalds 	int old_state = sk->sk_state;
30890f317464SEric Dumazet 	u32 seq;
30901da177e4SLinus Torvalds 
30911da177e4SLinus Torvalds 	if (old_state != TCP_CLOSE)
30921da177e4SLinus Torvalds 		tcp_set_state(sk, TCP_CLOSE);
30931da177e4SLinus Torvalds 
30941da177e4SLinus Torvalds 	/* ABORT function of RFC793 */
30951da177e4SLinus Torvalds 	if (old_state == TCP_LISTEN) {
30960a5578cfSArnaldo Carvalho de Melo 		inet_csk_listen_stop(sk);
3097ee995283SPavel Emelyanov 	} else if (unlikely(tp->repair)) {
3098e13ec3daSEric Dumazet 		WRITE_ONCE(sk->sk_err, ECONNABORTED);
30991da177e4SLinus Torvalds 	} else if (tcp_need_reset(old_state) ||
31001da177e4SLinus Torvalds 		   (tp->snd_nxt != tp->write_seq &&
31011da177e4SLinus Torvalds 		    (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
3102caa20d9aSStephen Hemminger 		/* The last check adjusts for discrepancy of Linux wrt. RFC
31031da177e4SLinus Torvalds 		 * states
31041da177e4SLinus Torvalds 		 */
31051da177e4SLinus Torvalds 		tcp_send_active_reset(sk, gfp_any());
3106e13ec3daSEric Dumazet 		WRITE_ONCE(sk->sk_err, ECONNRESET);
3107a7150e38SEric Dumazet 	} else if (old_state == TCP_SYN_SENT)
3108e13ec3daSEric Dumazet 		WRITE_ONCE(sk->sk_err, ECONNRESET);
31091da177e4SLinus Torvalds 
31101da177e4SLinus Torvalds 	tcp_clear_xmit_timers(sk);
31111da177e4SLinus Torvalds 	__skb_queue_purge(&sk->sk_receive_queue);
31127db48e98SEric Dumazet 	WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
31137b6a893aSEric Dumazet 	WRITE_ONCE(tp->urg_data, 0);
3114fe067e8aSDavid S. Miller 	tcp_write_queue_purge(sk);
3115cf1ef3f0SWei Wang 	tcp_fastopen_active_disable_ofo_check(sk);
31169f5afeaeSYaogong Wang 	skb_rbtree_purge(&tp->out_of_order_queue);
31171da177e4SLinus Torvalds 
3118c720c7e8SEric Dumazet 	inet->inet_dport = 0;
31191da177e4SLinus Torvalds 
3120e0833d1fSKuniyuki Iwashima 	inet_bhash2_reset_saddr(sk);
31211da177e4SLinus Torvalds 
31221da177e4SLinus Torvalds 	sk->sk_shutdown = 0;
31231da177e4SLinus Torvalds 	sock_reset_flag(sk, SOCK_DONE);
3124740b0f18SEric Dumazet 	tp->srtt_us = 0;
3125b9e2e689SEric Dumazet 	tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT);
31263f6c65d6SWei Wang 	tp->rcv_rtt_last_tsecr = 0;
31270f317464SEric Dumazet 
31280f317464SEric Dumazet 	seq = tp->write_seq + tp->max_window + 2;
31290f317464SEric Dumazet 	if (!seq)
31300f317464SEric Dumazet 		seq = 1;
31310f317464SEric Dumazet 	WRITE_ONCE(tp->write_seq, seq);
31320f317464SEric Dumazet 
3133463c84b9SArnaldo Carvalho de Melo 	icsk->icsk_backoff = 0;
31346687e988SArnaldo Carvalho de Melo 	icsk->icsk_probes_out = 0;
31359d9b1ee0SEnke Chen 	icsk->icsk_probes_tstamp = 0;
31366a408147SEric Dumazet 	icsk->icsk_rto = TCP_TIMEOUT_INIT;
3137ca584ba0SMartin KaFai Lau 	icsk->icsk_rto_min = TCP_RTO_MIN;
31382b8ee4f0SMartin KaFai Lau 	icsk->icsk_delack_max = TCP_DELACK_MAX;
31390b6a05c1SIlpo Järvinen 	tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
314040570375SEric Dumazet 	tcp_snd_cwnd_set(tp, TCP_INIT_CWND);
31411da177e4SLinus Torvalds 	tp->snd_cwnd_cnt = 0;
3142f4ce91ceSNeal Cardwell 	tp->is_cwnd_limited = 0;
3143f4ce91ceSNeal Cardwell 	tp->max_packets_out = 0;
31441fdf475aSEric Dumazet 	tp->window_clamp = 0;
31452fbdd562SEric Dumazet 	tp->delivered = 0;
3146e21db6f6SYuchung Cheng 	tp->delivered_ce = 0;
3147ce69e563SChristoph Paasch 	if (icsk->icsk_ca_ops->release)
3148ce69e563SChristoph Paasch 		icsk->icsk_ca_ops->release(sk);
3149ce69e563SChristoph Paasch 	memset(icsk->icsk_ca_priv, 0, sizeof(icsk->icsk_ca_priv));
31508919a9b3SNeal Cardwell 	icsk->icsk_ca_initialized = 0;
31516687e988SArnaldo Carvalho de Melo 	tcp_set_ca_state(sk, TCP_CA_Open);
3152d4761754SYousuk Seung 	tp->is_sack_reneg = 0;
31531da177e4SLinus Torvalds 	tcp_clear_retrans(tp);
3154c13c48c0SEric Dumazet 	tp->total_retrans = 0;
3155463c84b9SArnaldo Carvalho de Melo 	inet_csk_delack_init(sk);
3156499350a5SWei Wang 	/* Initialize rcv_mss to TCP_MIN_MSS to avoid division by 0
3157499350a5SWei Wang 	 * issue in __tcp_select_window()
3158499350a5SWei Wang 	 */
3159499350a5SWei Wang 	icsk->icsk_ack.rcv_mss = TCP_MIN_MSS;
3160b40b4f79SSrinivas Aji 	memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
31611da177e4SLinus Torvalds 	__sk_dst_reset(sk);
31628f905c0eSEric Dumazet 	dst_release(xchg((__force struct dst_entry **)&sk->sk_rx_dst, NULL));
316317c3060bSEric Dumazet 	tcp_saved_syn_free(tp);
31645d9f4262SEric Dumazet 	tp->compressed_ack = 0;
3165784f8344SEric Dumazet 	tp->segs_in = 0;
3166784f8344SEric Dumazet 	tp->segs_out = 0;
3167ba113c3aSWei Wang 	tp->bytes_sent = 0;
3168e858faf5SChristoph Paasch 	tp->bytes_acked = 0;
3169e858faf5SChristoph Paasch 	tp->bytes_received = 0;
3170fb31c9b9SWei Wang 	tp->bytes_retrans = 0;
3171db7ffee6SEric Dumazet 	tp->data_segs_in = 0;
3172db7ffee6SEric Dumazet 	tp->data_segs_out = 0;
31737788174eSYuchung Cheng 	tp->duplicate_sack[0].start_seq = 0;
31747788174eSYuchung Cheng 	tp->duplicate_sack[0].end_seq = 0;
31757e10b655SWei Wang 	tp->dsack_dups = 0;
31767ec65372SWei Wang 	tp->reord_seen = 0;
31775c701549SEric Dumazet 	tp->retrans_out = 0;
31785c701549SEric Dumazet 	tp->sacked_out = 0;
31795c701549SEric Dumazet 	tp->tlp_high_seq = 0;
31805c701549SEric Dumazet 	tp->last_oow_ack_time = 0;
318129c1c446SMubashir Adnan Qureshi 	tp->plb_rehash = 0;
31826cda8b74SEric Dumazet 	/* There's a bubble in the pipe until at least the first ACK. */
31836cda8b74SEric Dumazet 	tp->app_limited = ~0U;
3184300b655dSDavid Morley 	tp->rate_app_limited = 1;
3185792c4354SEric Dumazet 	tp->rack.mstamp = 0;
3186792c4354SEric Dumazet 	tp->rack.advanced = 0;
3187792c4354SEric Dumazet 	tp->rack.reo_wnd_steps = 1;
3188792c4354SEric Dumazet 	tp->rack.last_delivered = 0;
3189792c4354SEric Dumazet 	tp->rack.reo_wnd_persist = 0;
3190792c4354SEric Dumazet 	tp->rack.dsack_seen = 0;
31916bcdc40dSEric Dumazet 	tp->syn_data_acked = 0;
31926bcdc40dSEric Dumazet 	tp->rx_opt.saw_tstamp = 0;
31936bcdc40dSEric Dumazet 	tp->rx_opt.dsack = 0;
31946bcdc40dSEric Dumazet 	tp->rx_opt.num_sacks = 0;
3195f9af2dbbSThomas Higdon 	tp->rcv_ooopack = 0;
31966cda8b74SEric Dumazet 
31971da177e4SLinus Torvalds 
31987db92362SWei Wang 	/* Clean up fastopen related fields */
31997db92362SWei Wang 	tcp_free_fastopen_req(tp);
32007db92362SWei Wang 	inet->defer_connect = 0;
320148027478SJason Baron 	tp->fastopen_client_fail = 0;
32027db92362SWei Wang 
3203c720c7e8SEric Dumazet 	WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
32041da177e4SLinus Torvalds 
32059b42d55aSLi RongQing 	if (sk->sk_frag.page) {
32069b42d55aSLi RongQing 		put_page(sk->sk_frag.page);
32079b42d55aSLi RongQing 		sk->sk_frag.page = NULL;
32089b42d55aSLi RongQing 		sk->sk_frag.offset = 0;
32099b42d55aSLi RongQing 	}
3210e3ae2365SAlexander Aring 	sk_error_report(sk);
3211a01512b1SYueHaibing 	return 0;
32121da177e4SLinus Torvalds }
32134bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_disconnect);
32141da177e4SLinus Torvalds 
3215a2a385d6SEric Dumazet static inline bool tcp_can_repair_sock(const struct sock *sk)
3216ee995283SPavel Emelyanov {
3217cb388e7eSMartin KaFai Lau 	return sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN) &&
3218319b0534SAndrey Vagin 		(sk->sk_state != TCP_LISTEN);
3219ee995283SPavel Emelyanov }
3220ee995283SPavel Emelyanov 
3221d38d2b00SChristoph Hellwig static int tcp_repair_set_window(struct tcp_sock *tp, sockptr_t optbuf, int len)
3222b1ed4c4fSAndrey Vagin {
3223b1ed4c4fSAndrey Vagin 	struct tcp_repair_window opt;
3224b1ed4c4fSAndrey Vagin 
3225b1ed4c4fSAndrey Vagin 	if (!tp->repair)
3226b1ed4c4fSAndrey Vagin 		return -EPERM;
3227b1ed4c4fSAndrey Vagin 
3228b1ed4c4fSAndrey Vagin 	if (len != sizeof(opt))
3229b1ed4c4fSAndrey Vagin 		return -EINVAL;
3230b1ed4c4fSAndrey Vagin 
3231d38d2b00SChristoph Hellwig 	if (copy_from_sockptr(&opt, optbuf, sizeof(opt)))
3232b1ed4c4fSAndrey Vagin 		return -EFAULT;
3233b1ed4c4fSAndrey Vagin 
3234b1ed4c4fSAndrey Vagin 	if (opt.max_window < opt.snd_wnd)
3235b1ed4c4fSAndrey Vagin 		return -EINVAL;
3236b1ed4c4fSAndrey Vagin 
3237b1ed4c4fSAndrey Vagin 	if (after(opt.snd_wl1, tp->rcv_nxt + opt.rcv_wnd))
3238b1ed4c4fSAndrey Vagin 		return -EINVAL;
3239b1ed4c4fSAndrey Vagin 
3240b1ed4c4fSAndrey Vagin 	if (after(opt.rcv_wup, tp->rcv_nxt))
3241b1ed4c4fSAndrey Vagin 		return -EINVAL;
3242b1ed4c4fSAndrey Vagin 
3243b1ed4c4fSAndrey Vagin 	tp->snd_wl1	= opt.snd_wl1;
3244b1ed4c4fSAndrey Vagin 	tp->snd_wnd	= opt.snd_wnd;
3245b1ed4c4fSAndrey Vagin 	tp->max_window	= opt.max_window;
3246b1ed4c4fSAndrey Vagin 
3247b1ed4c4fSAndrey Vagin 	tp->rcv_wnd	= opt.rcv_wnd;
3248b1ed4c4fSAndrey Vagin 	tp->rcv_wup	= opt.rcv_wup;
3249b1ed4c4fSAndrey Vagin 
3250b1ed4c4fSAndrey Vagin 	return 0;
3251b1ed4c4fSAndrey Vagin }
3252b1ed4c4fSAndrey Vagin 
3253d38d2b00SChristoph Hellwig static int tcp_repair_options_est(struct sock *sk, sockptr_t optbuf,
3254d38d2b00SChristoph Hellwig 		unsigned int len)
3255b139ba4eSPavel Emelyanov {
325615e56515SDouglas Caetano dos Santos 	struct tcp_sock *tp = tcp_sk(sk);
3257de248a75SPavel Emelyanov 	struct tcp_repair_opt opt;
3258d3c48151SChristoph Hellwig 	size_t offset = 0;
3259b139ba4eSPavel Emelyanov 
3260de248a75SPavel Emelyanov 	while (len >= sizeof(opt)) {
3261d3c48151SChristoph Hellwig 		if (copy_from_sockptr_offset(&opt, optbuf, offset, sizeof(opt)))
3262b139ba4eSPavel Emelyanov 			return -EFAULT;
3263b139ba4eSPavel Emelyanov 
3264d3c48151SChristoph Hellwig 		offset += sizeof(opt);
3265de248a75SPavel Emelyanov 		len -= sizeof(opt);
3266b139ba4eSPavel Emelyanov 
3267de248a75SPavel Emelyanov 		switch (opt.opt_code) {
3268de248a75SPavel Emelyanov 		case TCPOPT_MSS:
3269de248a75SPavel Emelyanov 			tp->rx_opt.mss_clamp = opt.opt_val;
327015e56515SDouglas Caetano dos Santos 			tcp_mtup_init(sk);
3271b139ba4eSPavel Emelyanov 			break;
3272de248a75SPavel Emelyanov 		case TCPOPT_WINDOW:
3273bc26ccd8SAndrey Vagin 			{
3274bc26ccd8SAndrey Vagin 				u16 snd_wscale = opt.opt_val & 0xFFFF;
3275bc26ccd8SAndrey Vagin 				u16 rcv_wscale = opt.opt_val >> 16;
3276bc26ccd8SAndrey Vagin 
3277589c49cbSGao Feng 				if (snd_wscale > TCP_MAX_WSCALE || rcv_wscale > TCP_MAX_WSCALE)
3278b139ba4eSPavel Emelyanov 					return -EFBIG;
3279b139ba4eSPavel Emelyanov 
3280bc26ccd8SAndrey Vagin 				tp->rx_opt.snd_wscale = snd_wscale;
3281bc26ccd8SAndrey Vagin 				tp->rx_opt.rcv_wscale = rcv_wscale;
3282bc26ccd8SAndrey Vagin 				tp->rx_opt.wscale_ok = 1;
3283bc26ccd8SAndrey Vagin 			}
3284b139ba4eSPavel Emelyanov 			break;
3285b139ba4eSPavel Emelyanov 		case TCPOPT_SACK_PERM:
3286de248a75SPavel Emelyanov 			if (opt.opt_val != 0)
3287de248a75SPavel Emelyanov 				return -EINVAL;
3288de248a75SPavel Emelyanov 
3289b139ba4eSPavel Emelyanov 			tp->rx_opt.sack_ok |= TCP_SACK_SEEN;
3290b139ba4eSPavel Emelyanov 			break;
3291b139ba4eSPavel Emelyanov 		case TCPOPT_TIMESTAMP:
3292de248a75SPavel Emelyanov 			if (opt.opt_val != 0)
3293de248a75SPavel Emelyanov 				return -EINVAL;
3294de248a75SPavel Emelyanov 
3295b139ba4eSPavel Emelyanov 			tp->rx_opt.tstamp_ok = 1;
3296b139ba4eSPavel Emelyanov 			break;
3297b139ba4eSPavel Emelyanov 		}
3298b139ba4eSPavel Emelyanov 	}
3299b139ba4eSPavel Emelyanov 
3300b139ba4eSPavel Emelyanov 	return 0;
3301b139ba4eSPavel Emelyanov }
3302b139ba4eSPavel Emelyanov 
3303a842fe14SEric Dumazet DEFINE_STATIC_KEY_FALSE(tcp_tx_delay_enabled);
3304a842fe14SEric Dumazet EXPORT_SYMBOL(tcp_tx_delay_enabled);
3305a842fe14SEric Dumazet 
3306a842fe14SEric Dumazet static void tcp_enable_tx_delay(void)
3307a842fe14SEric Dumazet {
3308a842fe14SEric Dumazet 	if (!static_branch_unlikely(&tcp_tx_delay_enabled)) {
3309a842fe14SEric Dumazet 		static int __tcp_tx_delay_enabled = 0;
3310a842fe14SEric Dumazet 
3311a842fe14SEric Dumazet 		if (cmpxchg(&__tcp_tx_delay_enabled, 0, 1) == 0) {
3312a842fe14SEric Dumazet 			static_branch_enable(&tcp_tx_delay_enabled);
3313a842fe14SEric Dumazet 			pr_info("TCP_TX_DELAY enabled\n");
3314a842fe14SEric Dumazet 		}
3315a842fe14SEric Dumazet 	}
3316a842fe14SEric Dumazet }
3317a842fe14SEric Dumazet 
3318db10538aSChristoph Hellwig /* When set indicates to always queue non-full frames.  Later the user clears
3319db10538aSChristoph Hellwig  * this option and we transmit any pending partial frames in the queue.  This is
3320db10538aSChristoph Hellwig  * meant to be used alongside sendfile() to get properly filled frames when the
3321db10538aSChristoph Hellwig  * user (for example) must write out headers with a write() call first and then
3322db10538aSChristoph Hellwig  * use sendfile to send out the data parts.
3323db10538aSChristoph Hellwig  *
3324db10538aSChristoph Hellwig  * TCP_CORK can be set together with TCP_NODELAY and it is stronger than
3325db10538aSChristoph Hellwig  * TCP_NODELAY.
3326db10538aSChristoph Hellwig  */
33276fadaa56SMaxim Galaganov void __tcp_sock_set_cork(struct sock *sk, bool on)
3328db10538aSChristoph Hellwig {
3329db10538aSChristoph Hellwig 	struct tcp_sock *tp = tcp_sk(sk);
3330db10538aSChristoph Hellwig 
3331db10538aSChristoph Hellwig 	if (on) {
3332db10538aSChristoph Hellwig 		tp->nonagle |= TCP_NAGLE_CORK;
3333db10538aSChristoph Hellwig 	} else {
3334db10538aSChristoph Hellwig 		tp->nonagle &= ~TCP_NAGLE_CORK;
3335db10538aSChristoph Hellwig 		if (tp->nonagle & TCP_NAGLE_OFF)
3336db10538aSChristoph Hellwig 			tp->nonagle |= TCP_NAGLE_PUSH;
3337db10538aSChristoph Hellwig 		tcp_push_pending_frames(sk);
3338db10538aSChristoph Hellwig 	}
3339db10538aSChristoph Hellwig }
3340db10538aSChristoph Hellwig 
3341db10538aSChristoph Hellwig void tcp_sock_set_cork(struct sock *sk, bool on)
3342db10538aSChristoph Hellwig {
3343db10538aSChristoph Hellwig 	lock_sock(sk);
3344db10538aSChristoph Hellwig 	__tcp_sock_set_cork(sk, on);
3345db10538aSChristoph Hellwig 	release_sock(sk);
3346db10538aSChristoph Hellwig }
3347db10538aSChristoph Hellwig EXPORT_SYMBOL(tcp_sock_set_cork);
3348db10538aSChristoph Hellwig 
334912abc5eeSChristoph Hellwig /* TCP_NODELAY is weaker than TCP_CORK, so that this option on corked socket is
335012abc5eeSChristoph Hellwig  * remembered, but it is not activated until cork is cleared.
335112abc5eeSChristoph Hellwig  *
335212abc5eeSChristoph Hellwig  * However, when TCP_NODELAY is set we make an explicit push, which overrides
335312abc5eeSChristoph Hellwig  * even TCP_CORK for currently queued segments.
335412abc5eeSChristoph Hellwig  */
33556fadaa56SMaxim Galaganov void __tcp_sock_set_nodelay(struct sock *sk, bool on)
335612abc5eeSChristoph Hellwig {
335712abc5eeSChristoph Hellwig 	if (on) {
335812abc5eeSChristoph Hellwig 		tcp_sk(sk)->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH;
335912abc5eeSChristoph Hellwig 		tcp_push_pending_frames(sk);
336012abc5eeSChristoph Hellwig 	} else {
336112abc5eeSChristoph Hellwig 		tcp_sk(sk)->nonagle &= ~TCP_NAGLE_OFF;
336212abc5eeSChristoph Hellwig 	}
336312abc5eeSChristoph Hellwig }
336412abc5eeSChristoph Hellwig 
336512abc5eeSChristoph Hellwig void tcp_sock_set_nodelay(struct sock *sk)
336612abc5eeSChristoph Hellwig {
336712abc5eeSChristoph Hellwig 	lock_sock(sk);
336812abc5eeSChristoph Hellwig 	__tcp_sock_set_nodelay(sk, true);
336912abc5eeSChristoph Hellwig 	release_sock(sk);
337012abc5eeSChristoph Hellwig }
337112abc5eeSChristoph Hellwig EXPORT_SYMBOL(tcp_sock_set_nodelay);
337212abc5eeSChristoph Hellwig 
3373ddd061b8SChristoph Hellwig static void __tcp_sock_set_quickack(struct sock *sk, int val)
3374ddd061b8SChristoph Hellwig {
3375ddd061b8SChristoph Hellwig 	if (!val) {
3376ddd061b8SChristoph Hellwig 		inet_csk_enter_pingpong_mode(sk);
3377ddd061b8SChristoph Hellwig 		return;
3378ddd061b8SChristoph Hellwig 	}
3379ddd061b8SChristoph Hellwig 
3380ddd061b8SChristoph Hellwig 	inet_csk_exit_pingpong_mode(sk);
3381ddd061b8SChristoph Hellwig 	if ((1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) &&
3382ddd061b8SChristoph Hellwig 	    inet_csk_ack_scheduled(sk)) {
3383ddd061b8SChristoph Hellwig 		inet_csk(sk)->icsk_ack.pending |= ICSK_ACK_PUSHED;
3384ddd061b8SChristoph Hellwig 		tcp_cleanup_rbuf(sk, 1);
3385ddd061b8SChristoph Hellwig 		if (!(val & 1))
3386ddd061b8SChristoph Hellwig 			inet_csk_enter_pingpong_mode(sk);
3387ddd061b8SChristoph Hellwig 	}
3388ddd061b8SChristoph Hellwig }
3389ddd061b8SChristoph Hellwig 
3390ddd061b8SChristoph Hellwig void tcp_sock_set_quickack(struct sock *sk, int val)
3391ddd061b8SChristoph Hellwig {
3392ddd061b8SChristoph Hellwig 	lock_sock(sk);
3393ddd061b8SChristoph Hellwig 	__tcp_sock_set_quickack(sk, val);
3394ddd061b8SChristoph Hellwig 	release_sock(sk);
3395ddd061b8SChristoph Hellwig }
3396ddd061b8SChristoph Hellwig EXPORT_SYMBOL(tcp_sock_set_quickack);
3397ddd061b8SChristoph Hellwig 
3398557eadfcSChristoph Hellwig int tcp_sock_set_syncnt(struct sock *sk, int val)
3399557eadfcSChristoph Hellwig {
3400557eadfcSChristoph Hellwig 	if (val < 1 || val > MAX_TCP_SYNCNT)
3401557eadfcSChristoph Hellwig 		return -EINVAL;
3402557eadfcSChristoph Hellwig 
3403557eadfcSChristoph Hellwig 	lock_sock(sk);
3404557eadfcSChristoph Hellwig 	inet_csk(sk)->icsk_syn_retries = val;
3405557eadfcSChristoph Hellwig 	release_sock(sk);
3406557eadfcSChristoph Hellwig 	return 0;
3407557eadfcSChristoph Hellwig }
3408557eadfcSChristoph Hellwig EXPORT_SYMBOL(tcp_sock_set_syncnt);
3409557eadfcSChristoph Hellwig 
3410c488aeadSChristoph Hellwig void tcp_sock_set_user_timeout(struct sock *sk, u32 val)
3411c488aeadSChristoph Hellwig {
3412c488aeadSChristoph Hellwig 	lock_sock(sk);
3413c488aeadSChristoph Hellwig 	inet_csk(sk)->icsk_user_timeout = val;
3414c488aeadSChristoph Hellwig 	release_sock(sk);
3415c488aeadSChristoph Hellwig }
3416c488aeadSChristoph Hellwig EXPORT_SYMBOL(tcp_sock_set_user_timeout);
3417c488aeadSChristoph Hellwig 
3418aad4a0a9SDmitry Yakunin int tcp_sock_set_keepidle_locked(struct sock *sk, int val)
341971c48eb8SChristoph Hellwig {
342071c48eb8SChristoph Hellwig 	struct tcp_sock *tp = tcp_sk(sk);
342171c48eb8SChristoph Hellwig 
342271c48eb8SChristoph Hellwig 	if (val < 1 || val > MAX_TCP_KEEPIDLE)
342371c48eb8SChristoph Hellwig 		return -EINVAL;
342471c48eb8SChristoph Hellwig 
342571c48eb8SChristoph Hellwig 	tp->keepalive_time = val * HZ;
342671c48eb8SChristoph Hellwig 	if (sock_flag(sk, SOCK_KEEPOPEN) &&
342771c48eb8SChristoph Hellwig 	    !((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) {
342871c48eb8SChristoph Hellwig 		u32 elapsed = keepalive_time_elapsed(tp);
342971c48eb8SChristoph Hellwig 
343071c48eb8SChristoph Hellwig 		if (tp->keepalive_time > elapsed)
343171c48eb8SChristoph Hellwig 			elapsed = tp->keepalive_time - elapsed;
343271c48eb8SChristoph Hellwig 		else
343371c48eb8SChristoph Hellwig 			elapsed = 0;
343471c48eb8SChristoph Hellwig 		inet_csk_reset_keepalive_timer(sk, elapsed);
343571c48eb8SChristoph Hellwig 	}
343671c48eb8SChristoph Hellwig 
343771c48eb8SChristoph Hellwig 	return 0;
343871c48eb8SChristoph Hellwig }
343971c48eb8SChristoph Hellwig 
344071c48eb8SChristoph Hellwig int tcp_sock_set_keepidle(struct sock *sk, int val)
344171c48eb8SChristoph Hellwig {
344271c48eb8SChristoph Hellwig 	int err;
344371c48eb8SChristoph Hellwig 
344471c48eb8SChristoph Hellwig 	lock_sock(sk);
3445aad4a0a9SDmitry Yakunin 	err = tcp_sock_set_keepidle_locked(sk, val);
344671c48eb8SChristoph Hellwig 	release_sock(sk);
344771c48eb8SChristoph Hellwig 	return err;
344871c48eb8SChristoph Hellwig }
344971c48eb8SChristoph Hellwig EXPORT_SYMBOL(tcp_sock_set_keepidle);
345071c48eb8SChristoph Hellwig 
3451d41ecaacSChristoph Hellwig int tcp_sock_set_keepintvl(struct sock *sk, int val)
3452d41ecaacSChristoph Hellwig {
3453d41ecaacSChristoph Hellwig 	if (val < 1 || val > MAX_TCP_KEEPINTVL)
3454d41ecaacSChristoph Hellwig 		return -EINVAL;
3455d41ecaacSChristoph Hellwig 
3456d41ecaacSChristoph Hellwig 	lock_sock(sk);
3457d41ecaacSChristoph Hellwig 	tcp_sk(sk)->keepalive_intvl = val * HZ;
3458d41ecaacSChristoph Hellwig 	release_sock(sk);
3459d41ecaacSChristoph Hellwig 	return 0;
3460d41ecaacSChristoph Hellwig }
3461d41ecaacSChristoph Hellwig EXPORT_SYMBOL(tcp_sock_set_keepintvl);
3462d41ecaacSChristoph Hellwig 
3463480aeb96SChristoph Hellwig int tcp_sock_set_keepcnt(struct sock *sk, int val)
3464480aeb96SChristoph Hellwig {
3465480aeb96SChristoph Hellwig 	if (val < 1 || val > MAX_TCP_KEEPCNT)
3466480aeb96SChristoph Hellwig 		return -EINVAL;
3467480aeb96SChristoph Hellwig 
3468480aeb96SChristoph Hellwig 	lock_sock(sk);
3469480aeb96SChristoph Hellwig 	tcp_sk(sk)->keepalive_probes = val;
3470480aeb96SChristoph Hellwig 	release_sock(sk);
3471480aeb96SChristoph Hellwig 	return 0;
3472480aeb96SChristoph Hellwig }
3473480aeb96SChristoph Hellwig EXPORT_SYMBOL(tcp_sock_set_keepcnt);
3474480aeb96SChristoph Hellwig 
3475cb811109SPrankur gupta int tcp_set_window_clamp(struct sock *sk, int val)
3476cb811109SPrankur gupta {
3477cb811109SPrankur gupta 	struct tcp_sock *tp = tcp_sk(sk);
3478cb811109SPrankur gupta 
3479cb811109SPrankur gupta 	if (!val) {
3480cb811109SPrankur gupta 		if (sk->sk_state != TCP_CLOSE)
3481cb811109SPrankur gupta 			return -EINVAL;
3482cb811109SPrankur gupta 		tp->window_clamp = 0;
3483cb811109SPrankur gupta 	} else {
3484cb811109SPrankur gupta 		tp->window_clamp = val < SOCK_MIN_RCVBUF / 2 ?
3485cb811109SPrankur gupta 			SOCK_MIN_RCVBUF / 2 : val;
34863aa7857fSNeil Spring 		tp->rcv_ssthresh = min(tp->rcv_wnd, tp->window_clamp);
3487cb811109SPrankur gupta 	}
3488cb811109SPrankur gupta 	return 0;
3489cb811109SPrankur gupta }
3490cb811109SPrankur gupta 
34911da177e4SLinus Torvalds /*
34921da177e4SLinus Torvalds  *	Socket option code for TCP.
34931da177e4SLinus Torvalds  */
34940c751f70SMartin KaFai Lau int do_tcp_setsockopt(struct sock *sk, int level, int optname,
3495d38d2b00SChristoph Hellwig 		      sockptr_t optval, unsigned int optlen)
34961da177e4SLinus Torvalds {
34971da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
3498463c84b9SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
34991e579caaSNikolay Borisov 	struct net *net = sock_net(sk);
35001da177e4SLinus Torvalds 	int val;
35011da177e4SLinus Torvalds 	int err = 0;
35021da177e4SLinus Torvalds 
3503e56fb50fSWilliam Allen Simpson 	/* These are data/string values, all the others are ints */
3504e56fb50fSWilliam Allen Simpson 	switch (optname) {
3505e56fb50fSWilliam Allen Simpson 	case TCP_CONGESTION: {
35065f8ef48dSStephen Hemminger 		char name[TCP_CA_NAME_MAX];
35075f8ef48dSStephen Hemminger 
35085f8ef48dSStephen Hemminger 		if (optlen < 1)
35095f8ef48dSStephen Hemminger 			return -EINVAL;
35105f8ef48dSStephen Hemminger 
3511d38d2b00SChristoph Hellwig 		val = strncpy_from_sockptr(name, optval,
35124fdb78d3SAndrew Morton 					min_t(long, TCP_CA_NAME_MAX-1, optlen));
35135f8ef48dSStephen Hemminger 		if (val < 0)
35145f8ef48dSStephen Hemminger 			return -EFAULT;
35155f8ef48dSStephen Hemminger 		name[val] = 0;
35165f8ef48dSStephen Hemminger 
3517cb388e7eSMartin KaFai Lau 		sockopt_lock_sock(sk);
351884e5a0f2SMartin KaFai Lau 		err = tcp_set_congestion_control(sk, name, !has_current_bpf_ctx(),
3519cb388e7eSMartin KaFai Lau 						 sockopt_ns_capable(sock_net(sk)->user_ns,
35208d650cdeSEric Dumazet 								    CAP_NET_ADMIN));
3521cb388e7eSMartin KaFai Lau 		sockopt_release_sock(sk);
35225f8ef48dSStephen Hemminger 		return err;
35235f8ef48dSStephen Hemminger 	}
3524734942ccSDave Watson 	case TCP_ULP: {
3525734942ccSDave Watson 		char name[TCP_ULP_NAME_MAX];
3526734942ccSDave Watson 
3527734942ccSDave Watson 		if (optlen < 1)
3528734942ccSDave Watson 			return -EINVAL;
3529734942ccSDave Watson 
3530d38d2b00SChristoph Hellwig 		val = strncpy_from_sockptr(name, optval,
3531734942ccSDave Watson 					min_t(long, TCP_ULP_NAME_MAX - 1,
3532734942ccSDave Watson 					      optlen));
3533734942ccSDave Watson 		if (val < 0)
3534734942ccSDave Watson 			return -EFAULT;
3535734942ccSDave Watson 		name[val] = 0;
3536734942ccSDave Watson 
3537cb388e7eSMartin KaFai Lau 		sockopt_lock_sock(sk);
3538734942ccSDave Watson 		err = tcp_set_ulp(sk, name);
3539cb388e7eSMartin KaFai Lau 		sockopt_release_sock(sk);
3540734942ccSDave Watson 		return err;
3541734942ccSDave Watson 	}
35421fba70e5SYuchung Cheng 	case TCP_FASTOPEN_KEY: {
35430f1ce023SJason Baron 		__u8 key[TCP_FASTOPEN_KEY_BUF_LENGTH];
35440f1ce023SJason Baron 		__u8 *backup_key = NULL;
35451fba70e5SYuchung Cheng 
35460f1ce023SJason Baron 		/* Allow a backup key as well to facilitate key rotation
35470f1ce023SJason Baron 		 * First key is the active one.
35480f1ce023SJason Baron 		 */
35490f1ce023SJason Baron 		if (optlen != TCP_FASTOPEN_KEY_LENGTH &&
35500f1ce023SJason Baron 		    optlen != TCP_FASTOPEN_KEY_BUF_LENGTH)
35511fba70e5SYuchung Cheng 			return -EINVAL;
35521fba70e5SYuchung Cheng 
3553d38d2b00SChristoph Hellwig 		if (copy_from_sockptr(key, optval, optlen))
35541fba70e5SYuchung Cheng 			return -EFAULT;
35551fba70e5SYuchung Cheng 
35560f1ce023SJason Baron 		if (optlen == TCP_FASTOPEN_KEY_BUF_LENGTH)
35570f1ce023SJason Baron 			backup_key = key + TCP_FASTOPEN_KEY_LENGTH;
35580f1ce023SJason Baron 
3559438ac880SArd Biesheuvel 		return tcp_fastopen_reset_cipher(net, sk, key, backup_key);
35601fba70e5SYuchung Cheng 	}
3561e56fb50fSWilliam Allen Simpson 	default:
3562e56fb50fSWilliam Allen Simpson 		/* fallthru */
3563e56fb50fSWilliam Allen Simpson 		break;
3564ccbd6a5aSJoe Perches 	}
35655f8ef48dSStephen Hemminger 
35661da177e4SLinus Torvalds 	if (optlen < sizeof(int))
35671da177e4SLinus Torvalds 		return -EINVAL;
35681da177e4SLinus Torvalds 
3569d38d2b00SChristoph Hellwig 	if (copy_from_sockptr(&val, optval, sizeof(val)))
35701da177e4SLinus Torvalds 		return -EFAULT;
35711da177e4SLinus Torvalds 
3572cb388e7eSMartin KaFai Lau 	sockopt_lock_sock(sk);
35731da177e4SLinus Torvalds 
35741da177e4SLinus Torvalds 	switch (optname) {
35751da177e4SLinus Torvalds 	case TCP_MAXSEG:
35761da177e4SLinus Torvalds 		/* Values greater than interface MTU won't take effect. However
35771da177e4SLinus Torvalds 		 * at the point when this call is done we typically don't yet
3578a777f715SRohit Chavan 		 * know which interface is going to be used
3579a777f715SRohit Chavan 		 */
3580cfc62d87SGao Feng 		if (val && (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW)) {
35811da177e4SLinus Torvalds 			err = -EINVAL;
35821da177e4SLinus Torvalds 			break;
35831da177e4SLinus Torvalds 		}
35841da177e4SLinus Torvalds 		tp->rx_opt.user_mss = val;
35851da177e4SLinus Torvalds 		break;
35861da177e4SLinus Torvalds 
35871da177e4SLinus Torvalds 	case TCP_NODELAY:
358812abc5eeSChristoph Hellwig 		__tcp_sock_set_nodelay(sk, val);
35891da177e4SLinus Torvalds 		break;
35901da177e4SLinus Torvalds 
359136e31b0aSAndreas Petlund 	case TCP_THIN_LINEAR_TIMEOUTS:
359236e31b0aSAndreas Petlund 		if (val < 0 || val > 1)
359336e31b0aSAndreas Petlund 			err = -EINVAL;
359436e31b0aSAndreas Petlund 		else
359536e31b0aSAndreas Petlund 			tp->thin_lto = val;
359636e31b0aSAndreas Petlund 		break;
359736e31b0aSAndreas Petlund 
35987e380175SAndreas Petlund 	case TCP_THIN_DUPACK:
35997e380175SAndreas Petlund 		if (val < 0 || val > 1)
36007e380175SAndreas Petlund 			err = -EINVAL;
36017e380175SAndreas Petlund 		break;
36027e380175SAndreas Petlund 
3603ee995283SPavel Emelyanov 	case TCP_REPAIR:
3604ee995283SPavel Emelyanov 		if (!tcp_can_repair_sock(sk))
3605ee995283SPavel Emelyanov 			err = -EPERM;
360631048d7aSStefan Baranoff 		else if (val == TCP_REPAIR_ON) {
3607ee995283SPavel Emelyanov 			tp->repair = 1;
3608ee995283SPavel Emelyanov 			sk->sk_reuse = SK_FORCE_REUSE;
3609ee995283SPavel Emelyanov 			tp->repair_queue = TCP_NO_QUEUE;
361031048d7aSStefan Baranoff 		} else if (val == TCP_REPAIR_OFF) {
3611ee995283SPavel Emelyanov 			tp->repair = 0;
3612ee995283SPavel Emelyanov 			sk->sk_reuse = SK_NO_REUSE;
3613ee995283SPavel Emelyanov 			tcp_send_window_probe(sk);
361431048d7aSStefan Baranoff 		} else if (val == TCP_REPAIR_OFF_NO_WP) {
361531048d7aSStefan Baranoff 			tp->repair = 0;
361631048d7aSStefan Baranoff 			sk->sk_reuse = SK_NO_REUSE;
3617ee995283SPavel Emelyanov 		} else
3618ee995283SPavel Emelyanov 			err = -EINVAL;
3619ee995283SPavel Emelyanov 
3620ee995283SPavel Emelyanov 		break;
3621ee995283SPavel Emelyanov 
3622ee995283SPavel Emelyanov 	case TCP_REPAIR_QUEUE:
3623ee995283SPavel Emelyanov 		if (!tp->repair)
3624ee995283SPavel Emelyanov 			err = -EPERM;
3625bf2acc94SEric Dumazet 		else if ((unsigned int)val < TCP_QUEUES_NR)
3626ee995283SPavel Emelyanov 			tp->repair_queue = val;
3627ee995283SPavel Emelyanov 		else
3628ee995283SPavel Emelyanov 			err = -EINVAL;
3629ee995283SPavel Emelyanov 		break;
3630ee995283SPavel Emelyanov 
3631ee995283SPavel Emelyanov 	case TCP_QUEUE_SEQ:
36328811f4a9SEric Dumazet 		if (sk->sk_state != TCP_CLOSE) {
3633ee995283SPavel Emelyanov 			err = -EPERM;
36348811f4a9SEric Dumazet 		} else if (tp->repair_queue == TCP_SEND_QUEUE) {
36358811f4a9SEric Dumazet 			if (!tcp_rtx_queue_empty(sk))
36368811f4a9SEric Dumazet 				err = -EPERM;
36378811f4a9SEric Dumazet 			else
36380f317464SEric Dumazet 				WRITE_ONCE(tp->write_seq, val);
36398811f4a9SEric Dumazet 		} else if (tp->repair_queue == TCP_RECV_QUEUE) {
36408811f4a9SEric Dumazet 			if (tp->rcv_nxt != tp->copied_seq) {
36418811f4a9SEric Dumazet 				err = -EPERM;
36428811f4a9SEric Dumazet 			} else {
3643dba7d9b8SEric Dumazet 				WRITE_ONCE(tp->rcv_nxt, val);
36446cd6cbf5SEric Dumazet 				WRITE_ONCE(tp->copied_seq, val);
36456cd6cbf5SEric Dumazet 			}
36468811f4a9SEric Dumazet 		} else {
3647ee995283SPavel Emelyanov 			err = -EINVAL;
36488811f4a9SEric Dumazet 		}
3649ee995283SPavel Emelyanov 		break;
3650ee995283SPavel Emelyanov 
3651b139ba4eSPavel Emelyanov 	case TCP_REPAIR_OPTIONS:
3652b139ba4eSPavel Emelyanov 		if (!tp->repair)
3653b139ba4eSPavel Emelyanov 			err = -EINVAL;
36540c175da7SLu Wei 		else if (sk->sk_state == TCP_ESTABLISHED && !tp->bytes_sent)
3655d38d2b00SChristoph Hellwig 			err = tcp_repair_options_est(sk, optval, optlen);
3656b139ba4eSPavel Emelyanov 		else
3657b139ba4eSPavel Emelyanov 			err = -EPERM;
3658b139ba4eSPavel Emelyanov 		break;
3659b139ba4eSPavel Emelyanov 
36601da177e4SLinus Torvalds 	case TCP_CORK:
3661db10538aSChristoph Hellwig 		__tcp_sock_set_cork(sk, val);
36621da177e4SLinus Torvalds 		break;
36631da177e4SLinus Torvalds 
36641da177e4SLinus Torvalds 	case TCP_KEEPIDLE:
3665aad4a0a9SDmitry Yakunin 		err = tcp_sock_set_keepidle_locked(sk, val);
36661da177e4SLinus Torvalds 		break;
36671da177e4SLinus Torvalds 	case TCP_KEEPINTVL:
36681da177e4SLinus Torvalds 		if (val < 1 || val > MAX_TCP_KEEPINTVL)
36691da177e4SLinus Torvalds 			err = -EINVAL;
36701da177e4SLinus Torvalds 		else
36711da177e4SLinus Torvalds 			tp->keepalive_intvl = val * HZ;
36721da177e4SLinus Torvalds 		break;
36731da177e4SLinus Torvalds 	case TCP_KEEPCNT:
36741da177e4SLinus Torvalds 		if (val < 1 || val > MAX_TCP_KEEPCNT)
36751da177e4SLinus Torvalds 			err = -EINVAL;
36761da177e4SLinus Torvalds 		else
36771da177e4SLinus Torvalds 			tp->keepalive_probes = val;
36781da177e4SLinus Torvalds 		break;
36791da177e4SLinus Torvalds 	case TCP_SYNCNT:
36801da177e4SLinus Torvalds 		if (val < 1 || val > MAX_TCP_SYNCNT)
36811da177e4SLinus Torvalds 			err = -EINVAL;
36821da177e4SLinus Torvalds 		else
3683463c84b9SArnaldo Carvalho de Melo 			icsk->icsk_syn_retries = val;
36841da177e4SLinus Torvalds 		break;
36851da177e4SLinus Torvalds 
3686cd8ae852SEric Dumazet 	case TCP_SAVE_SYN:
3687267cf9faSMartin KaFai Lau 		/* 0: disable, 1: enable, 2: start from ether_header */
3688267cf9faSMartin KaFai Lau 		if (val < 0 || val > 2)
3689cd8ae852SEric Dumazet 			err = -EINVAL;
3690cd8ae852SEric Dumazet 		else
3691cd8ae852SEric Dumazet 			tp->save_syn = val;
3692cd8ae852SEric Dumazet 		break;
3693cd8ae852SEric Dumazet 
36941da177e4SLinus Torvalds 	case TCP_LINGER2:
36951da177e4SLinus Torvalds 		if (val < 0)
36961da177e4SLinus Torvalds 			tp->linger2 = -1;
3697f0628c52SCambda Zhu 		else if (val > TCP_FIN_TIMEOUT_MAX / HZ)
3698f0628c52SCambda Zhu 			tp->linger2 = TCP_FIN_TIMEOUT_MAX;
36991da177e4SLinus Torvalds 		else
37001da177e4SLinus Torvalds 			tp->linger2 = val * HZ;
37011da177e4SLinus Torvalds 		break;
37021da177e4SLinus Torvalds 
37031da177e4SLinus Torvalds 	case TCP_DEFER_ACCEPT:
3704b103cf34SJulian Anastasov 		/* Translate value in seconds to number of retransmits */
3705b103cf34SJulian Anastasov 		icsk->icsk_accept_queue.rskq_defer_accept =
3706b103cf34SJulian Anastasov 			secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ,
3707b103cf34SJulian Anastasov 					TCP_RTO_MAX / HZ);
37081da177e4SLinus Torvalds 		break;
37091da177e4SLinus Torvalds 
37101da177e4SLinus Torvalds 	case TCP_WINDOW_CLAMP:
3711cb811109SPrankur gupta 		err = tcp_set_window_clamp(sk, val);
37121da177e4SLinus Torvalds 		break;
37131da177e4SLinus Torvalds 
37141da177e4SLinus Torvalds 	case TCP_QUICKACK:
3715ddd061b8SChristoph Hellwig 		__tcp_sock_set_quickack(sk, val);
37161da177e4SLinus Torvalds 		break;
37171da177e4SLinus Torvalds 
3718cfb6eeb4SYOSHIFUJI Hideaki #ifdef CONFIG_TCP_MD5SIG
3719cfb6eeb4SYOSHIFUJI Hideaki 	case TCP_MD5SIG:
37208917a777SIvan Delalande 	case TCP_MD5SIG_EXT:
3721d38d2b00SChristoph Hellwig 		err = tp->af_specific->md5_parse(sk, optname, optval, optlen);
3722cfb6eeb4SYOSHIFUJI Hideaki 		break;
3723cfb6eeb4SYOSHIFUJI Hideaki #endif
3724dca43c75SJerry Chu 	case TCP_USER_TIMEOUT:
3725b248230cSYuchung Cheng 		/* Cap the max time in ms TCP will retry or probe the window
3726dca43c75SJerry Chu 		 * before giving up and aborting (ETIMEDOUT) a connection.
3727dca43c75SJerry Chu 		 */
372842493570SHangbin Liu 		if (val < 0)
372942493570SHangbin Liu 			err = -EINVAL;
373042493570SHangbin Liu 		else
37319bcc66e1SJon Maxwell 			icsk->icsk_user_timeout = val;
3732dca43c75SJerry Chu 		break;
37338336886fSJerry Chu 
37348336886fSJerry Chu 	case TCP_FASTOPEN:
37358336886fSJerry Chu 		if (val >= 0 && ((1 << sk->sk_state) & (TCPF_CLOSE |
3736dfea2aa6SChristoph Paasch 		    TCPF_LISTEN))) {
373743713848SHaishuang Yan 			tcp_fastopen_init_key_once(net);
3738dfea2aa6SChristoph Paasch 
37390536fcc0SEric Dumazet 			fastopen_queue_tune(sk, val);
3740dfea2aa6SChristoph Paasch 		} else {
37418336886fSJerry Chu 			err = -EINVAL;
3742dfea2aa6SChristoph Paasch 		}
37438336886fSJerry Chu 		break;
374419f6d3f3SWei Wang 	case TCP_FASTOPEN_CONNECT:
374519f6d3f3SWei Wang 		if (val > 1 || val < 0) {
374619f6d3f3SWei Wang 			err = -EINVAL;
37475a542133SKuniyuki Iwashima 		} else if (READ_ONCE(net->ipv4.sysctl_tcp_fastopen) &
37485a542133SKuniyuki Iwashima 			   TFO_CLIENT_ENABLE) {
374919f6d3f3SWei Wang 			if (sk->sk_state == TCP_CLOSE)
375019f6d3f3SWei Wang 				tp->fastopen_connect = val;
375119f6d3f3SWei Wang 			else
375219f6d3f3SWei Wang 				err = -EINVAL;
375319f6d3f3SWei Wang 		} else {
375419f6d3f3SWei Wang 			err = -EOPNOTSUPP;
375519f6d3f3SWei Wang 		}
375619f6d3f3SWei Wang 		break;
375771c02379SChristoph Paasch 	case TCP_FASTOPEN_NO_COOKIE:
375871c02379SChristoph Paasch 		if (val > 1 || val < 0)
375971c02379SChristoph Paasch 			err = -EINVAL;
376071c02379SChristoph Paasch 		else if (!((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
376171c02379SChristoph Paasch 			err = -EINVAL;
376271c02379SChristoph Paasch 		else
376371c02379SChristoph Paasch 			tp->fastopen_no_cookie = val;
376471c02379SChristoph Paasch 		break;
376593be6ce0SAndrey Vagin 	case TCP_TIMESTAMP:
376693be6ce0SAndrey Vagin 		if (!tp->repair)
376793be6ce0SAndrey Vagin 			err = -EPERM;
376893be6ce0SAndrey Vagin 		else
37699a568de4SEric Dumazet 			tp->tsoffset = val - tcp_time_stamp_raw();
377093be6ce0SAndrey Vagin 		break;
3771b1ed4c4fSAndrey Vagin 	case TCP_REPAIR_WINDOW:
3772b1ed4c4fSAndrey Vagin 		err = tcp_repair_set_window(tp, optval, optlen);
3773b1ed4c4fSAndrey Vagin 		break;
3774c9bee3b7SEric Dumazet 	case TCP_NOTSENT_LOWAT:
3775c9bee3b7SEric Dumazet 		tp->notsent_lowat = val;
3776c9bee3b7SEric Dumazet 		sk->sk_write_space(sk);
3777c9bee3b7SEric Dumazet 		break;
3778b75eba76SSoheil Hassas Yeganeh 	case TCP_INQ:
3779b75eba76SSoheil Hassas Yeganeh 		if (val > 1 || val < 0)
3780b75eba76SSoheil Hassas Yeganeh 			err = -EINVAL;
3781b75eba76SSoheil Hassas Yeganeh 		else
3782b75eba76SSoheil Hassas Yeganeh 			tp->recvmsg_inq = val;
3783b75eba76SSoheil Hassas Yeganeh 		break;
3784a842fe14SEric Dumazet 	case TCP_TX_DELAY:
3785a842fe14SEric Dumazet 		if (val)
3786a842fe14SEric Dumazet 			tcp_enable_tx_delay();
3787a842fe14SEric Dumazet 		tp->tcp_tx_delay = val;
3788a842fe14SEric Dumazet 		break;
37891da177e4SLinus Torvalds 	default:
37901da177e4SLinus Torvalds 		err = -ENOPROTOOPT;
37911da177e4SLinus Torvalds 		break;
37923ff50b79SStephen Hemminger 	}
37933ff50b79SStephen Hemminger 
3794cb388e7eSMartin KaFai Lau 	sockopt_release_sock(sk);
37951da177e4SLinus Torvalds 	return err;
37961da177e4SLinus Torvalds }
37971da177e4SLinus Torvalds 
3798a7b75c5aSChristoph Hellwig int tcp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
3799b7058842SDavid S. Miller 		   unsigned int optlen)
38003fdadf7dSDmitry Mishin {
3801cf533ea5SEric Dumazet 	const struct inet_connection_sock *icsk = inet_csk(sk);
38023fdadf7dSDmitry Mishin 
38033fdadf7dSDmitry Mishin 	if (level != SOL_TCP)
3804f49cd2f4SKuniyuki Iwashima 		/* Paired with WRITE_ONCE() in do_ipv6_setsockopt() and tcp_v6_connect() */
3805f49cd2f4SKuniyuki Iwashima 		return READ_ONCE(icsk->icsk_af_ops)->setsockopt(sk, level, optname,
38063fdadf7dSDmitry Mishin 								optval, optlen);
3807a7b75c5aSChristoph Hellwig 	return do_tcp_setsockopt(sk, level, optname, optval, optlen);
38083fdadf7dSDmitry Mishin }
38094bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_setsockopt);
38103fdadf7dSDmitry Mishin 
3811efd90174SFrancis Yan static void tcp_get_info_chrono_stats(const struct tcp_sock *tp,
3812efd90174SFrancis Yan 				      struct tcp_info *info)
3813efd90174SFrancis Yan {
3814efd90174SFrancis Yan 	u64 stats[__TCP_CHRONO_MAX], total = 0;
3815efd90174SFrancis Yan 	enum tcp_chrono i;
3816efd90174SFrancis Yan 
3817efd90174SFrancis Yan 	for (i = TCP_CHRONO_BUSY; i < __TCP_CHRONO_MAX; ++i) {
3818efd90174SFrancis Yan 		stats[i] = tp->chrono_stat[i - 1];
3819efd90174SFrancis Yan 		if (i == tp->chrono_type)
3820628174ccSEric Dumazet 			stats[i] += tcp_jiffies32 - tp->chrono_start;
3821efd90174SFrancis Yan 		stats[i] *= USEC_PER_SEC / HZ;
3822efd90174SFrancis Yan 		total += stats[i];
3823efd90174SFrancis Yan 	}
3824efd90174SFrancis Yan 
3825efd90174SFrancis Yan 	info->tcpi_busy_time = total;
3826efd90174SFrancis Yan 	info->tcpi_rwnd_limited = stats[TCP_CHRONO_RWND_LIMITED];
3827efd90174SFrancis Yan 	info->tcpi_sndbuf_limited = stats[TCP_CHRONO_SNDBUF_LIMITED];
3828efd90174SFrancis Yan }
3829efd90174SFrancis Yan 
38301da177e4SLinus Torvalds /* Return information about state of tcp endpoint in API format. */
38310df48c26SEric Dumazet void tcp_get_info(struct sock *sk, struct tcp_info *info)
38321da177e4SLinus Torvalds {
383335ac838aSCraig Gallek 	const struct tcp_sock *tp = tcp_sk(sk); /* iff sk_type == SOCK_STREAM */
3834463c84b9SArnaldo Carvalho de Melo 	const struct inet_connection_sock *icsk = inet_csk(sk);
383576a9ebe8SEric Dumazet 	unsigned long rate;
38360263598cSWei Wang 	u32 now;
3837ff5d7497SEric Dumazet 	u64 rate64;
383867db3e4bSEric Dumazet 	bool slow;
38391da177e4SLinus Torvalds 
38401da177e4SLinus Torvalds 	memset(info, 0, sizeof(*info));
384135ac838aSCraig Gallek 	if (sk->sk_type != SOCK_STREAM)
384235ac838aSCraig Gallek 		return;
38431da177e4SLinus Torvalds 
3844986ffdfdSYafang Shao 	info->tcpi_state = inet_sk_state_load(sk);
384500fd38d9SEric Dumazet 
3846ccbf3bfaSEric Dumazet 	/* Report meaningful fields for all TCP states, including listeners */
3847ccbf3bfaSEric Dumazet 	rate = READ_ONCE(sk->sk_pacing_rate);
384876a9ebe8SEric Dumazet 	rate64 = (rate != ~0UL) ? rate : ~0ULL;
3849f522a5fcSEric Dumazet 	info->tcpi_pacing_rate = rate64;
3850ccbf3bfaSEric Dumazet 
3851ccbf3bfaSEric Dumazet 	rate = READ_ONCE(sk->sk_max_pacing_rate);
385276a9ebe8SEric Dumazet 	rate64 = (rate != ~0UL) ? rate : ~0ULL;
3853f522a5fcSEric Dumazet 	info->tcpi_max_pacing_rate = rate64;
3854ccbf3bfaSEric Dumazet 
3855ccbf3bfaSEric Dumazet 	info->tcpi_reordering = tp->reordering;
385640570375SEric Dumazet 	info->tcpi_snd_cwnd = tcp_snd_cwnd(tp);
3857ccbf3bfaSEric Dumazet 
3858ccbf3bfaSEric Dumazet 	if (info->tcpi_state == TCP_LISTEN) {
3859ccbf3bfaSEric Dumazet 		/* listeners aliased fields :
3860ccbf3bfaSEric Dumazet 		 * tcpi_unacked -> Number of children ready for accept()
3861ccbf3bfaSEric Dumazet 		 * tcpi_sacked  -> max backlog
3862ccbf3bfaSEric Dumazet 		 */
3863288efe86SEric Dumazet 		info->tcpi_unacked = READ_ONCE(sk->sk_ack_backlog);
3864099ecf59SEric Dumazet 		info->tcpi_sacked = READ_ONCE(sk->sk_max_ack_backlog);
3865ccbf3bfaSEric Dumazet 		return;
3866ccbf3bfaSEric Dumazet 	}
3867b369e7fdSEric Dumazet 
3868b369e7fdSEric Dumazet 	slow = lock_sock_fast(sk);
3869b369e7fdSEric Dumazet 
38706687e988SArnaldo Carvalho de Melo 	info->tcpi_ca_state = icsk->icsk_ca_state;
3871463c84b9SArnaldo Carvalho de Melo 	info->tcpi_retransmits = icsk->icsk_retransmits;
38726687e988SArnaldo Carvalho de Melo 	info->tcpi_probes = icsk->icsk_probes_out;
3873463c84b9SArnaldo Carvalho de Melo 	info->tcpi_backoff = icsk->icsk_backoff;
38741da177e4SLinus Torvalds 
38751da177e4SLinus Torvalds 	if (tp->rx_opt.tstamp_ok)
38761da177e4SLinus Torvalds 		info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
3877e60402d0SIlpo Järvinen 	if (tcp_is_sack(tp))
38781da177e4SLinus Torvalds 		info->tcpi_options |= TCPI_OPT_SACK;
38791da177e4SLinus Torvalds 	if (tp->rx_opt.wscale_ok) {
38801da177e4SLinus Torvalds 		info->tcpi_options |= TCPI_OPT_WSCALE;
38811da177e4SLinus Torvalds 		info->tcpi_snd_wscale = tp->rx_opt.snd_wscale;
38821da177e4SLinus Torvalds 		info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale;
38831da177e4SLinus Torvalds 	}
38841da177e4SLinus Torvalds 
38851da177e4SLinus Torvalds 	if (tp->ecn_flags & TCP_ECN_OK)
38861da177e4SLinus Torvalds 		info->tcpi_options |= TCPI_OPT_ECN;
3887b5c5693bSEric Dumazet 	if (tp->ecn_flags & TCP_ECN_SEEN)
3888b5c5693bSEric Dumazet 		info->tcpi_options |= TCPI_OPT_ECN_SEEN;
38896f73601eSYuchung Cheng 	if (tp->syn_data_acked)
38906f73601eSYuchung Cheng 		info->tcpi_options |= TCPI_OPT_SYN_DATA;
38911da177e4SLinus Torvalds 
3892463c84b9SArnaldo Carvalho de Melo 	info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto);
3893463c84b9SArnaldo Carvalho de Melo 	info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato);
3894c1b4a7e6SDavid S. Miller 	info->tcpi_snd_mss = tp->mss_cache;
3895463c84b9SArnaldo Carvalho de Melo 	info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss;
38961da177e4SLinus Torvalds 
38971da177e4SLinus Torvalds 	info->tcpi_unacked = tp->packets_out;
38981da177e4SLinus Torvalds 	info->tcpi_sacked = tp->sacked_out;
3899ccbf3bfaSEric Dumazet 
39001da177e4SLinus Torvalds 	info->tcpi_lost = tp->lost_out;
39011da177e4SLinus Torvalds 	info->tcpi_retrans = tp->retrans_out;
39021da177e4SLinus Torvalds 
3903d635fbe2SEric Dumazet 	now = tcp_jiffies32;
39041da177e4SLinus Torvalds 	info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime);
3905463c84b9SArnaldo Carvalho de Melo 	info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime);
39061da177e4SLinus Torvalds 	info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp);
39071da177e4SLinus Torvalds 
3908d83d8461SArnaldo Carvalho de Melo 	info->tcpi_pmtu = icsk->icsk_pmtu_cookie;
39091da177e4SLinus Torvalds 	info->tcpi_rcv_ssthresh = tp->rcv_ssthresh;
3910740b0f18SEric Dumazet 	info->tcpi_rtt = tp->srtt_us >> 3;
3911740b0f18SEric Dumazet 	info->tcpi_rttvar = tp->mdev_us >> 2;
39121da177e4SLinus Torvalds 	info->tcpi_snd_ssthresh = tp->snd_ssthresh;
39131da177e4SLinus Torvalds 	info->tcpi_advmss = tp->advmss;
39141da177e4SLinus Torvalds 
3915645f4c6fSEric Dumazet 	info->tcpi_rcv_rtt = tp->rcv_rtt_est.rtt_us >> 3;
39161da177e4SLinus Torvalds 	info->tcpi_rcv_space = tp->rcvq_space.space;
39171da177e4SLinus Torvalds 
39181da177e4SLinus Torvalds 	info->tcpi_total_retrans = tp->total_retrans;
3919977cb0ecSEric Dumazet 
3920f522a5fcSEric Dumazet 	info->tcpi_bytes_acked = tp->bytes_acked;
3921f522a5fcSEric Dumazet 	info->tcpi_bytes_received = tp->bytes_received;
392267db3e4bSEric Dumazet 	info->tcpi_notsent_bytes = max_t(int, 0, tp->write_seq - tp->snd_nxt);
3923efd90174SFrancis Yan 	tcp_get_info_chrono_stats(tp, info);
392467db3e4bSEric Dumazet 
39252efd055cSMarcelo Ricardo Leitner 	info->tcpi_segs_out = tp->segs_out;
39260307a0b7SEric Dumazet 
39270307a0b7SEric Dumazet 	/* segs_in and data_segs_in can be updated from tcp_segs_in() from BH */
39280307a0b7SEric Dumazet 	info->tcpi_segs_in = READ_ONCE(tp->segs_in);
39290307a0b7SEric Dumazet 	info->tcpi_data_segs_in = READ_ONCE(tp->data_segs_in);
3930cd9b2660SEric Dumazet 
3931cd9b2660SEric Dumazet 	info->tcpi_min_rtt = tcp_min_rtt(tp);
3932a44d6eacSMartin KaFai Lau 	info->tcpi_data_segs_out = tp->data_segs_out;
3933eb8329e0SYuchung Cheng 
3934eb8329e0SYuchung Cheng 	info->tcpi_delivery_rate_app_limited = tp->rate_app_limited ? 1 : 0;
39350263598cSWei Wang 	rate64 = tcp_compute_delivery_rate(tp);
39360263598cSWei Wang 	if (rate64)
3937f522a5fcSEric Dumazet 		info->tcpi_delivery_rate = rate64;
3938feb5f2ecSYuchung Cheng 	info->tcpi_delivered = tp->delivered;
3939feb5f2ecSYuchung Cheng 	info->tcpi_delivered_ce = tp->delivered_ce;
3940ba113c3aSWei Wang 	info->tcpi_bytes_sent = tp->bytes_sent;
3941fb31c9b9SWei Wang 	info->tcpi_bytes_retrans = tp->bytes_retrans;
39427e10b655SWei Wang 	info->tcpi_dsack_dups = tp->dsack_dups;
39437ec65372SWei Wang 	info->tcpi_reord_seen = tp->reord_seen;
3944f9af2dbbSThomas Higdon 	info->tcpi_rcv_ooopack = tp->rcv_ooopack;
39458f7baad7SThomas Higdon 	info->tcpi_snd_wnd = tp->snd_wnd;
394671fc7047SMubashir Adnan Qureshi 	info->tcpi_rcv_wnd = tp->rcv_wnd;
394771fc7047SMubashir Adnan Qureshi 	info->tcpi_rehash = tp->plb_rehash + tp->timeout_rehash;
394848027478SJason Baron 	info->tcpi_fastopen_client_fail = tp->fastopen_client_fail;
3949b369e7fdSEric Dumazet 	unlock_sock_fast(sk, slow);
39501da177e4SLinus Torvalds }
39511da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(tcp_get_info);
39521da177e4SLinus Torvalds 
3953984988aaSWei Wang static size_t tcp_opt_stats_get_size(void)
3954984988aaSWei Wang {
3955984988aaSWei Wang 	return
3956984988aaSWei Wang 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BUSY */
3957984988aaSWei Wang 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_RWND_LIMITED */
3958984988aaSWei Wang 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_SNDBUF_LIMITED */
3959984988aaSWei Wang 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_DATA_SEGS_OUT */
3960984988aaSWei Wang 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_TOTAL_RETRANS */
3961984988aaSWei Wang 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_PACING_RATE */
3962984988aaSWei Wang 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_DELIVERY_RATE */
3963984988aaSWei Wang 		nla_total_size(sizeof(u32)) + /* TCP_NLA_SND_CWND */
3964984988aaSWei Wang 		nla_total_size(sizeof(u32)) + /* TCP_NLA_REORDERING */
3965984988aaSWei Wang 		nla_total_size(sizeof(u32)) + /* TCP_NLA_MIN_RTT */
3966984988aaSWei Wang 		nla_total_size(sizeof(u8)) + /* TCP_NLA_RECUR_RETRANS */
3967984988aaSWei Wang 		nla_total_size(sizeof(u8)) + /* TCP_NLA_DELIVERY_RATE_APP_LMT */
3968984988aaSWei Wang 		nla_total_size(sizeof(u32)) + /* TCP_NLA_SNDQ_SIZE */
3969984988aaSWei Wang 		nla_total_size(sizeof(u8)) + /* TCP_NLA_CA_STATE */
3970984988aaSWei Wang 		nla_total_size(sizeof(u32)) + /* TCP_NLA_SND_SSTHRESH */
3971984988aaSWei Wang 		nla_total_size(sizeof(u32)) + /* TCP_NLA_DELIVERED */
3972984988aaSWei Wang 		nla_total_size(sizeof(u32)) + /* TCP_NLA_DELIVERED_CE */
3973ba113c3aSWei Wang 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BYTES_SENT */
3974fb31c9b9SWei Wang 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_BYTES_RETRANS */
39757e10b655SWei Wang 		nla_total_size(sizeof(u32)) + /* TCP_NLA_DSACK_DUPS */
39767ec65372SWei Wang 		nla_total_size(sizeof(u32)) + /* TCP_NLA_REORD_SEEN */
3977e8bd8fcaSYousuk Seung 		nla_total_size(sizeof(u32)) + /* TCP_NLA_SRTT */
397832efcc06SAbdul Kabbani 		nla_total_size(sizeof(u16)) + /* TCP_NLA_TIMEOUT_REHASH */
3979e08ab0b3SYousuk Seung 		nla_total_size(sizeof(u32)) + /* TCP_NLA_BYTES_NOTSENT */
398048040793SYousuk Seung 		nla_total_size_64bit(sizeof(u64)) + /* TCP_NLA_EDT */
3981e7ed11eeSYousuk Seung 		nla_total_size(sizeof(u8)) + /* TCP_NLA_TTL */
398229c1c446SMubashir Adnan Qureshi 		nla_total_size(sizeof(u32)) + /* TCP_NLA_REHASH */
3983984988aaSWei Wang 		0;
3984984988aaSWei Wang }
3985984988aaSWei Wang 
3986e7ed11eeSYousuk Seung /* Returns TTL or hop limit of an incoming packet from skb. */
3987e7ed11eeSYousuk Seung static u8 tcp_skb_ttl_or_hop_limit(const struct sk_buff *skb)
3988e7ed11eeSYousuk Seung {
3989e7ed11eeSYousuk Seung 	if (skb->protocol == htons(ETH_P_IP))
3990e7ed11eeSYousuk Seung 		return ip_hdr(skb)->ttl;
3991e7ed11eeSYousuk Seung 	else if (skb->protocol == htons(ETH_P_IPV6))
3992e7ed11eeSYousuk Seung 		return ipv6_hdr(skb)->hop_limit;
3993e7ed11eeSYousuk Seung 	else
3994e7ed11eeSYousuk Seung 		return 0;
3995e7ed11eeSYousuk Seung }
3996e7ed11eeSYousuk Seung 
399748040793SYousuk Seung struct sk_buff *tcp_get_timestamping_opt_stats(const struct sock *sk,
3998e7ed11eeSYousuk Seung 					       const struct sk_buff *orig_skb,
3999e7ed11eeSYousuk Seung 					       const struct sk_buff *ack_skb)
40001c885808SFrancis Yan {
40011c885808SFrancis Yan 	const struct tcp_sock *tp = tcp_sk(sk);
40021c885808SFrancis Yan 	struct sk_buff *stats;
40031c885808SFrancis Yan 	struct tcp_info info;
400476a9ebe8SEric Dumazet 	unsigned long rate;
4005bb7c19f9SWei Wang 	u64 rate64;
40061c885808SFrancis Yan 
4007984988aaSWei Wang 	stats = alloc_skb(tcp_opt_stats_get_size(), GFP_ATOMIC);
40081c885808SFrancis Yan 	if (!stats)
40091c885808SFrancis Yan 		return NULL;
40101c885808SFrancis Yan 
40111c885808SFrancis Yan 	tcp_get_info_chrono_stats(tp, &info);
40121c885808SFrancis Yan 	nla_put_u64_64bit(stats, TCP_NLA_BUSY,
40131c885808SFrancis Yan 			  info.tcpi_busy_time, TCP_NLA_PAD);
40141c885808SFrancis Yan 	nla_put_u64_64bit(stats, TCP_NLA_RWND_LIMITED,
40151c885808SFrancis Yan 			  info.tcpi_rwnd_limited, TCP_NLA_PAD);
40161c885808SFrancis Yan 	nla_put_u64_64bit(stats, TCP_NLA_SNDBUF_LIMITED,
40171c885808SFrancis Yan 			  info.tcpi_sndbuf_limited, TCP_NLA_PAD);
40187e98102fSYuchung Cheng 	nla_put_u64_64bit(stats, TCP_NLA_DATA_SEGS_OUT,
40197e98102fSYuchung Cheng 			  tp->data_segs_out, TCP_NLA_PAD);
40207e98102fSYuchung Cheng 	nla_put_u64_64bit(stats, TCP_NLA_TOTAL_RETRANS,
40217e98102fSYuchung Cheng 			  tp->total_retrans, TCP_NLA_PAD);
4022bb7c19f9SWei Wang 
4023bb7c19f9SWei Wang 	rate = READ_ONCE(sk->sk_pacing_rate);
402476a9ebe8SEric Dumazet 	rate64 = (rate != ~0UL) ? rate : ~0ULL;
4025bb7c19f9SWei Wang 	nla_put_u64_64bit(stats, TCP_NLA_PACING_RATE, rate64, TCP_NLA_PAD);
4026bb7c19f9SWei Wang 
4027bb7c19f9SWei Wang 	rate64 = tcp_compute_delivery_rate(tp);
4028bb7c19f9SWei Wang 	nla_put_u64_64bit(stats, TCP_NLA_DELIVERY_RATE, rate64, TCP_NLA_PAD);
4029bb7c19f9SWei Wang 
403040570375SEric Dumazet 	nla_put_u32(stats, TCP_NLA_SND_CWND, tcp_snd_cwnd(tp));
4031bb7c19f9SWei Wang 	nla_put_u32(stats, TCP_NLA_REORDERING, tp->reordering);
4032bb7c19f9SWei Wang 	nla_put_u32(stats, TCP_NLA_MIN_RTT, tcp_min_rtt(tp));
4033bb7c19f9SWei Wang 
4034bb7c19f9SWei Wang 	nla_put_u8(stats, TCP_NLA_RECUR_RETRANS, inet_csk(sk)->icsk_retransmits);
4035bb7c19f9SWei Wang 	nla_put_u8(stats, TCP_NLA_DELIVERY_RATE_APP_LMT, !!tp->rate_app_limited);
40367156d194SYousuk Seung 	nla_put_u32(stats, TCP_NLA_SND_SSTHRESH, tp->snd_ssthresh);
4037feb5f2ecSYuchung Cheng 	nla_put_u32(stats, TCP_NLA_DELIVERED, tp->delivered);
4038feb5f2ecSYuchung Cheng 	nla_put_u32(stats, TCP_NLA_DELIVERED_CE, tp->delivered_ce);
403987ecc95dSPriyaranjan Jha 
404087ecc95dSPriyaranjan Jha 	nla_put_u32(stats, TCP_NLA_SNDQ_SIZE, tp->write_seq - tp->snd_una);
4041be631892SPriyaranjan Jha 	nla_put_u8(stats, TCP_NLA_CA_STATE, inet_csk(sk)->icsk_ca_state);
4042feb5f2ecSYuchung Cheng 
4043ba113c3aSWei Wang 	nla_put_u64_64bit(stats, TCP_NLA_BYTES_SENT, tp->bytes_sent,
4044ba113c3aSWei Wang 			  TCP_NLA_PAD);
4045fb31c9b9SWei Wang 	nla_put_u64_64bit(stats, TCP_NLA_BYTES_RETRANS, tp->bytes_retrans,
4046fb31c9b9SWei Wang 			  TCP_NLA_PAD);
40477e10b655SWei Wang 	nla_put_u32(stats, TCP_NLA_DSACK_DUPS, tp->dsack_dups);
40487ec65372SWei Wang 	nla_put_u32(stats, TCP_NLA_REORD_SEEN, tp->reord_seen);
4049e8bd8fcaSYousuk Seung 	nla_put_u32(stats, TCP_NLA_SRTT, tp->srtt_us >> 3);
405032efcc06SAbdul Kabbani 	nla_put_u16(stats, TCP_NLA_TIMEOUT_REHASH, tp->timeout_rehash);
4051e08ab0b3SYousuk Seung 	nla_put_u32(stats, TCP_NLA_BYTES_NOTSENT,
4052e08ab0b3SYousuk Seung 		    max_t(int, 0, tp->write_seq - tp->snd_nxt));
405348040793SYousuk Seung 	nla_put_u64_64bit(stats, TCP_NLA_EDT, orig_skb->skb_mstamp_ns,
405448040793SYousuk Seung 			  TCP_NLA_PAD);
4055e7ed11eeSYousuk Seung 	if (ack_skb)
4056e7ed11eeSYousuk Seung 		nla_put_u8(stats, TCP_NLA_TTL,
4057e7ed11eeSYousuk Seung 			   tcp_skb_ttl_or_hop_limit(ack_skb));
4058ba113c3aSWei Wang 
405929c1c446SMubashir Adnan Qureshi 	nla_put_u32(stats, TCP_NLA_REHASH, tp->plb_rehash + tp->timeout_rehash);
40601c885808SFrancis Yan 	return stats;
40611c885808SFrancis Yan }
40621c885808SFrancis Yan 
4063273b7f0fSMartin KaFai Lau int do_tcp_getsockopt(struct sock *sk, int level,
406434704ef0SMartin KaFai Lau 		      int optname, sockptr_t optval, sockptr_t optlen)
40651da177e4SLinus Torvalds {
4066295f7324SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
40671da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
40686fa25166SNikolay Borisov 	struct net *net = sock_net(sk);
40691da177e4SLinus Torvalds 	int val, len;
40701da177e4SLinus Torvalds 
407134704ef0SMartin KaFai Lau 	if (copy_from_sockptr(&len, optlen, sizeof(int)))
40721da177e4SLinus Torvalds 		return -EFAULT;
40731da177e4SLinus Torvalds 
40741da177e4SLinus Torvalds 	len = min_t(unsigned int, len, sizeof(int));
40751da177e4SLinus Torvalds 
40761da177e4SLinus Torvalds 	if (len < 0)
40771da177e4SLinus Torvalds 		return -EINVAL;
40781da177e4SLinus Torvalds 
40791da177e4SLinus Torvalds 	switch (optname) {
40801da177e4SLinus Torvalds 	case TCP_MAXSEG:
4081c1b4a7e6SDavid S. Miller 		val = tp->mss_cache;
40821da177e4SLinus Torvalds 		if (!val && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
40831da177e4SLinus Torvalds 			val = tp->rx_opt.user_mss;
40845e6a3ce6SPavel Emelyanov 		if (tp->repair)
40855e6a3ce6SPavel Emelyanov 			val = tp->rx_opt.mss_clamp;
40861da177e4SLinus Torvalds 		break;
40871da177e4SLinus Torvalds 	case TCP_NODELAY:
40881da177e4SLinus Torvalds 		val = !!(tp->nonagle&TCP_NAGLE_OFF);
40891da177e4SLinus Torvalds 		break;
40901da177e4SLinus Torvalds 	case TCP_CORK:
40911da177e4SLinus Torvalds 		val = !!(tp->nonagle&TCP_NAGLE_CORK);
40921da177e4SLinus Torvalds 		break;
40931da177e4SLinus Torvalds 	case TCP_KEEPIDLE:
4094df19a626SEric Dumazet 		val = keepalive_time_when(tp) / HZ;
40951da177e4SLinus Torvalds 		break;
40961da177e4SLinus Torvalds 	case TCP_KEEPINTVL:
4097df19a626SEric Dumazet 		val = keepalive_intvl_when(tp) / HZ;
40981da177e4SLinus Torvalds 		break;
40991da177e4SLinus Torvalds 	case TCP_KEEPCNT:
4100df19a626SEric Dumazet 		val = keepalive_probes(tp);
41011da177e4SLinus Torvalds 		break;
41021da177e4SLinus Torvalds 	case TCP_SYNCNT:
410320a3b1c0SKuniyuki Iwashima 		val = icsk->icsk_syn_retries ? :
410420a3b1c0SKuniyuki Iwashima 			READ_ONCE(net->ipv4.sysctl_tcp_syn_retries);
41051da177e4SLinus Torvalds 		break;
41061da177e4SLinus Torvalds 	case TCP_LINGER2:
41071da177e4SLinus Torvalds 		val = tp->linger2;
41081da177e4SLinus Torvalds 		if (val >= 0)
410939e24435SKuniyuki Iwashima 			val = (val ? : READ_ONCE(net->ipv4.sysctl_tcp_fin_timeout)) / HZ;
41101da177e4SLinus Torvalds 		break;
41111da177e4SLinus Torvalds 	case TCP_DEFER_ACCEPT:
4112b103cf34SJulian Anastasov 		val = retrans_to_secs(icsk->icsk_accept_queue.rskq_defer_accept,
4113b103cf34SJulian Anastasov 				      TCP_TIMEOUT_INIT / HZ, TCP_RTO_MAX / HZ);
41141da177e4SLinus Torvalds 		break;
41151da177e4SLinus Torvalds 	case TCP_WINDOW_CLAMP:
41161da177e4SLinus Torvalds 		val = tp->window_clamp;
41171da177e4SLinus Torvalds 		break;
41181da177e4SLinus Torvalds 	case TCP_INFO: {
41191da177e4SLinus Torvalds 		struct tcp_info info;
41201da177e4SLinus Torvalds 
412134704ef0SMartin KaFai Lau 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
41221da177e4SLinus Torvalds 			return -EFAULT;
41231da177e4SLinus Torvalds 
41241da177e4SLinus Torvalds 		tcp_get_info(sk, &info);
41251da177e4SLinus Torvalds 
41261da177e4SLinus Torvalds 		len = min_t(unsigned int, len, sizeof(info));
412734704ef0SMartin KaFai Lau 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
41281da177e4SLinus Torvalds 			return -EFAULT;
412934704ef0SMartin KaFai Lau 		if (copy_to_sockptr(optval, &info, len))
41301da177e4SLinus Torvalds 			return -EFAULT;
41311da177e4SLinus Torvalds 		return 0;
41321da177e4SLinus Torvalds 	}
41336e9250f5SEric Dumazet 	case TCP_CC_INFO: {
41346e9250f5SEric Dumazet 		const struct tcp_congestion_ops *ca_ops;
41356e9250f5SEric Dumazet 		union tcp_cc_info info;
41366e9250f5SEric Dumazet 		size_t sz = 0;
41376e9250f5SEric Dumazet 		int attr;
41386e9250f5SEric Dumazet 
413934704ef0SMartin KaFai Lau 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
41406e9250f5SEric Dumazet 			return -EFAULT;
41416e9250f5SEric Dumazet 
41426e9250f5SEric Dumazet 		ca_ops = icsk->icsk_ca_ops;
41436e9250f5SEric Dumazet 		if (ca_ops && ca_ops->get_info)
41446e9250f5SEric Dumazet 			sz = ca_ops->get_info(sk, ~0U, &attr, &info);
41456e9250f5SEric Dumazet 
41466e9250f5SEric Dumazet 		len = min_t(unsigned int, len, sz);
414734704ef0SMartin KaFai Lau 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
41486e9250f5SEric Dumazet 			return -EFAULT;
414934704ef0SMartin KaFai Lau 		if (copy_to_sockptr(optval, &info, len))
41506e9250f5SEric Dumazet 			return -EFAULT;
41516e9250f5SEric Dumazet 		return 0;
41526e9250f5SEric Dumazet 	}
41531da177e4SLinus Torvalds 	case TCP_QUICKACK:
415431954cd8SWei Wang 		val = !inet_csk_in_pingpong_mode(sk);
41551da177e4SLinus Torvalds 		break;
41565f8ef48dSStephen Hemminger 
41575f8ef48dSStephen Hemminger 	case TCP_CONGESTION:
415834704ef0SMartin KaFai Lau 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
41595f8ef48dSStephen Hemminger 			return -EFAULT;
41605f8ef48dSStephen Hemminger 		len = min_t(unsigned int, len, TCP_CA_NAME_MAX);
416134704ef0SMartin KaFai Lau 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
41625f8ef48dSStephen Hemminger 			return -EFAULT;
416334704ef0SMartin KaFai Lau 		if (copy_to_sockptr(optval, icsk->icsk_ca_ops->name, len))
41645f8ef48dSStephen Hemminger 			return -EFAULT;
41655f8ef48dSStephen Hemminger 		return 0;
4166e56fb50fSWilliam Allen Simpson 
4167734942ccSDave Watson 	case TCP_ULP:
416834704ef0SMartin KaFai Lau 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4169734942ccSDave Watson 			return -EFAULT;
4170734942ccSDave Watson 		len = min_t(unsigned int, len, TCP_ULP_NAME_MAX);
4171d97af30fSDave Watson 		if (!icsk->icsk_ulp_ops) {
417234704ef0SMartin KaFai Lau 			len = 0;
417334704ef0SMartin KaFai Lau 			if (copy_to_sockptr(optlen, &len, sizeof(int)))
4174d97af30fSDave Watson 				return -EFAULT;
4175d97af30fSDave Watson 			return 0;
4176d97af30fSDave Watson 		}
417734704ef0SMartin KaFai Lau 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
4178734942ccSDave Watson 			return -EFAULT;
417934704ef0SMartin KaFai Lau 		if (copy_to_sockptr(optval, icsk->icsk_ulp_ops->name, len))
4180734942ccSDave Watson 			return -EFAULT;
4181734942ccSDave Watson 		return 0;
4182734942ccSDave Watson 
41831fba70e5SYuchung Cheng 	case TCP_FASTOPEN_KEY: {
4184f19008e6SJason Baron 		u64 key[TCP_FASTOPEN_KEY_BUF_LENGTH / sizeof(u64)];
4185f19008e6SJason Baron 		unsigned int key_len;
41861fba70e5SYuchung Cheng 
418734704ef0SMartin KaFai Lau 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
41881fba70e5SYuchung Cheng 			return -EFAULT;
41891fba70e5SYuchung Cheng 
4190f19008e6SJason Baron 		key_len = tcp_fastopen_get_cipher(net, icsk, key) *
41910f1ce023SJason Baron 				TCP_FASTOPEN_KEY_LENGTH;
41920f1ce023SJason Baron 		len = min_t(unsigned int, len, key_len);
419334704ef0SMartin KaFai Lau 		if (copy_to_sockptr(optlen, &len, sizeof(int)))
41941fba70e5SYuchung Cheng 			return -EFAULT;
419534704ef0SMartin KaFai Lau 		if (copy_to_sockptr(optval, key, len))
41961fba70e5SYuchung Cheng 			return -EFAULT;
41971fba70e5SYuchung Cheng 		return 0;
41981fba70e5SYuchung Cheng 	}
41993c0fef0bSJosh Hunt 	case TCP_THIN_LINEAR_TIMEOUTS:
42003c0fef0bSJosh Hunt 		val = tp->thin_lto;
42013c0fef0bSJosh Hunt 		break;
42024a7f6009SYuchung Cheng 
42033c0fef0bSJosh Hunt 	case TCP_THIN_DUPACK:
42044a7f6009SYuchung Cheng 		val = 0;
42053c0fef0bSJosh Hunt 		break;
4206dca43c75SJerry Chu 
4207ee995283SPavel Emelyanov 	case TCP_REPAIR:
4208ee995283SPavel Emelyanov 		val = tp->repair;
4209ee995283SPavel Emelyanov 		break;
4210ee995283SPavel Emelyanov 
4211ee995283SPavel Emelyanov 	case TCP_REPAIR_QUEUE:
4212ee995283SPavel Emelyanov 		if (tp->repair)
4213ee995283SPavel Emelyanov 			val = tp->repair_queue;
4214ee995283SPavel Emelyanov 		else
4215ee995283SPavel Emelyanov 			return -EINVAL;
4216ee995283SPavel Emelyanov 		break;
4217ee995283SPavel Emelyanov 
4218b1ed4c4fSAndrey Vagin 	case TCP_REPAIR_WINDOW: {
4219b1ed4c4fSAndrey Vagin 		struct tcp_repair_window opt;
4220b1ed4c4fSAndrey Vagin 
422134704ef0SMartin KaFai Lau 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4222b1ed4c4fSAndrey Vagin 			return -EFAULT;
4223b1ed4c4fSAndrey Vagin 
4224b1ed4c4fSAndrey Vagin 		if (len != sizeof(opt))
4225b1ed4c4fSAndrey Vagin 			return -EINVAL;
4226b1ed4c4fSAndrey Vagin 
4227b1ed4c4fSAndrey Vagin 		if (!tp->repair)
4228b1ed4c4fSAndrey Vagin 			return -EPERM;
4229b1ed4c4fSAndrey Vagin 
4230b1ed4c4fSAndrey Vagin 		opt.snd_wl1	= tp->snd_wl1;
4231b1ed4c4fSAndrey Vagin 		opt.snd_wnd	= tp->snd_wnd;
4232b1ed4c4fSAndrey Vagin 		opt.max_window	= tp->max_window;
4233b1ed4c4fSAndrey Vagin 		opt.rcv_wnd	= tp->rcv_wnd;
4234b1ed4c4fSAndrey Vagin 		opt.rcv_wup	= tp->rcv_wup;
4235b1ed4c4fSAndrey Vagin 
423634704ef0SMartin KaFai Lau 		if (copy_to_sockptr(optval, &opt, len))
4237b1ed4c4fSAndrey Vagin 			return -EFAULT;
4238b1ed4c4fSAndrey Vagin 		return 0;
4239b1ed4c4fSAndrey Vagin 	}
4240ee995283SPavel Emelyanov 	case TCP_QUEUE_SEQ:
4241ee995283SPavel Emelyanov 		if (tp->repair_queue == TCP_SEND_QUEUE)
4242ee995283SPavel Emelyanov 			val = tp->write_seq;
4243ee995283SPavel Emelyanov 		else if (tp->repair_queue == TCP_RECV_QUEUE)
4244ee995283SPavel Emelyanov 			val = tp->rcv_nxt;
4245ee995283SPavel Emelyanov 		else
4246ee995283SPavel Emelyanov 			return -EINVAL;
4247ee995283SPavel Emelyanov 		break;
4248ee995283SPavel Emelyanov 
4249dca43c75SJerry Chu 	case TCP_USER_TIMEOUT:
42509bcc66e1SJon Maxwell 		val = icsk->icsk_user_timeout;
4251dca43c75SJerry Chu 		break;
42521536e285SKenjiro Nakayama 
42531536e285SKenjiro Nakayama 	case TCP_FASTOPEN:
42540536fcc0SEric Dumazet 		val = icsk->icsk_accept_queue.fastopenq.max_qlen;
42551536e285SKenjiro Nakayama 		break;
42561536e285SKenjiro Nakayama 
425719f6d3f3SWei Wang 	case TCP_FASTOPEN_CONNECT:
425819f6d3f3SWei Wang 		val = tp->fastopen_connect;
425919f6d3f3SWei Wang 		break;
426019f6d3f3SWei Wang 
426171c02379SChristoph Paasch 	case TCP_FASTOPEN_NO_COOKIE:
426271c02379SChristoph Paasch 		val = tp->fastopen_no_cookie;
426371c02379SChristoph Paasch 		break;
426471c02379SChristoph Paasch 
4265a842fe14SEric Dumazet 	case TCP_TX_DELAY:
4266a842fe14SEric Dumazet 		val = tp->tcp_tx_delay;
4267a842fe14SEric Dumazet 		break;
4268a842fe14SEric Dumazet 
426993be6ce0SAndrey Vagin 	case TCP_TIMESTAMP:
42709a568de4SEric Dumazet 		val = tcp_time_stamp_raw() + tp->tsoffset;
427193be6ce0SAndrey Vagin 		break;
4272c9bee3b7SEric Dumazet 	case TCP_NOTSENT_LOWAT:
4273c9bee3b7SEric Dumazet 		val = tp->notsent_lowat;
4274c9bee3b7SEric Dumazet 		break;
4275b75eba76SSoheil Hassas Yeganeh 	case TCP_INQ:
4276b75eba76SSoheil Hassas Yeganeh 		val = tp->recvmsg_inq;
4277b75eba76SSoheil Hassas Yeganeh 		break;
4278cd8ae852SEric Dumazet 	case TCP_SAVE_SYN:
4279cd8ae852SEric Dumazet 		val = tp->save_syn;
4280cd8ae852SEric Dumazet 		break;
4281cd8ae852SEric Dumazet 	case TCP_SAVED_SYN: {
428234704ef0SMartin KaFai Lau 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
4283cd8ae852SEric Dumazet 			return -EFAULT;
4284cd8ae852SEric Dumazet 
4285d51bbff2SMartin KaFai Lau 		sockopt_lock_sock(sk);
4286cd8ae852SEric Dumazet 		if (tp->saved_syn) {
428770a217f1SMartin KaFai Lau 			if (len < tcp_saved_syn_len(tp->saved_syn)) {
428834704ef0SMartin KaFai Lau 				len = tcp_saved_syn_len(tp->saved_syn);
428934704ef0SMartin KaFai Lau 				if (copy_to_sockptr(optlen, &len, sizeof(int))) {
4290d51bbff2SMartin KaFai Lau 					sockopt_release_sock(sk);
4291aea0929eSEric B Munson 					return -EFAULT;
4292aea0929eSEric B Munson 				}
4293d51bbff2SMartin KaFai Lau 				sockopt_release_sock(sk);
4294aea0929eSEric B Munson 				return -EINVAL;
4295aea0929eSEric B Munson 			}
429670a217f1SMartin KaFai Lau 			len = tcp_saved_syn_len(tp->saved_syn);
429734704ef0SMartin KaFai Lau 			if (copy_to_sockptr(optlen, &len, sizeof(int))) {
4298d51bbff2SMartin KaFai Lau 				sockopt_release_sock(sk);
4299cd8ae852SEric Dumazet 				return -EFAULT;
4300cd8ae852SEric Dumazet 			}
430134704ef0SMartin KaFai Lau 			if (copy_to_sockptr(optval, tp->saved_syn->data, len)) {
4302d51bbff2SMartin KaFai Lau 				sockopt_release_sock(sk);
4303cd8ae852SEric Dumazet 				return -EFAULT;
4304cd8ae852SEric Dumazet 			}
4305cd8ae852SEric Dumazet 			tcp_saved_syn_free(tp);
4306d51bbff2SMartin KaFai Lau 			sockopt_release_sock(sk);
4307cd8ae852SEric Dumazet 		} else {
4308d51bbff2SMartin KaFai Lau 			sockopt_release_sock(sk);
4309cd8ae852SEric Dumazet 			len = 0;
431034704ef0SMartin KaFai Lau 			if (copy_to_sockptr(optlen, &len, sizeof(int)))
4311cd8ae852SEric Dumazet 				return -EFAULT;
4312cd8ae852SEric Dumazet 		}
4313cd8ae852SEric Dumazet 		return 0;
4314cd8ae852SEric Dumazet 	}
431505255b82SEric Dumazet #ifdef CONFIG_MMU
431605255b82SEric Dumazet 	case TCP_ZEROCOPY_RECEIVE: {
43177eeba170SArjun Roy 		struct scm_timestamping_internal tss;
4318e0fecb28SArjun Roy 		struct tcp_zerocopy_receive zc = {};
431905255b82SEric Dumazet 		int err;
432005255b82SEric Dumazet 
432134704ef0SMartin KaFai Lau 		if (copy_from_sockptr(&len, optlen, sizeof(int)))
432205255b82SEric Dumazet 			return -EFAULT;
43232107d45fSArjun Roy 		if (len < 0 ||
43242107d45fSArjun Roy 		    len < offsetofend(struct tcp_zerocopy_receive, length))
432505255b82SEric Dumazet 			return -EINVAL;
43263c5a2fd0SArjun Roy 		if (unlikely(len > sizeof(zc))) {
432734704ef0SMartin KaFai Lau 			err = check_zeroed_sockptr(optval, sizeof(zc),
43283c5a2fd0SArjun Roy 						   len - sizeof(zc));
43293c5a2fd0SArjun Roy 			if (err < 1)
43303c5a2fd0SArjun Roy 				return err == 0 ? -EINVAL : err;
4331c8856c05SArjun Roy 			len = sizeof(zc);
433234704ef0SMartin KaFai Lau 			if (copy_to_sockptr(optlen, &len, sizeof(int)))
43330b7f41f6SArjun Roy 				return -EFAULT;
43340b7f41f6SArjun Roy 		}
433534704ef0SMartin KaFai Lau 		if (copy_from_sockptr(&zc, optval, len))
433605255b82SEric Dumazet 			return -EFAULT;
43373c5a2fd0SArjun Roy 		if (zc.reserved)
43383c5a2fd0SArjun Roy 			return -EINVAL;
43393c5a2fd0SArjun Roy 		if (zc.msg_flags &  ~(TCP_VALID_ZC_MSG_FLAGS))
43403c5a2fd0SArjun Roy 			return -EINVAL;
4341d51bbff2SMartin KaFai Lau 		sockopt_lock_sock(sk);
43427eeba170SArjun Roy 		err = tcp_zerocopy_receive(sk, &zc, &tss);
43439cacf81fSStanislav Fomichev 		err = BPF_CGROUP_RUN_PROG_GETSOCKOPT_KERN(sk, level, optname,
43449cacf81fSStanislav Fomichev 							  &zc, &len, err);
4345d51bbff2SMartin KaFai Lau 		sockopt_release_sock(sk);
43467eeba170SArjun Roy 		if (len >= offsetofend(struct tcp_zerocopy_receive, msg_flags))
43477eeba170SArjun Roy 			goto zerocopy_rcv_cmsg;
4348c8856c05SArjun Roy 		switch (len) {
43497eeba170SArjun Roy 		case offsetofend(struct tcp_zerocopy_receive, msg_flags):
43507eeba170SArjun Roy 			goto zerocopy_rcv_cmsg;
43517eeba170SArjun Roy 		case offsetofend(struct tcp_zerocopy_receive, msg_controllen):
43527eeba170SArjun Roy 		case offsetofend(struct tcp_zerocopy_receive, msg_control):
43537eeba170SArjun Roy 		case offsetofend(struct tcp_zerocopy_receive, flags):
43547eeba170SArjun Roy 		case offsetofend(struct tcp_zerocopy_receive, copybuf_len):
43557eeba170SArjun Roy 		case offsetofend(struct tcp_zerocopy_receive, copybuf_address):
435633946518SArjun Roy 		case offsetofend(struct tcp_zerocopy_receive, err):
435733946518SArjun Roy 			goto zerocopy_rcv_sk_err;
4358c8856c05SArjun Roy 		case offsetofend(struct tcp_zerocopy_receive, inq):
4359c8856c05SArjun Roy 			goto zerocopy_rcv_inq;
4360c8856c05SArjun Roy 		case offsetofend(struct tcp_zerocopy_receive, length):
4361c8856c05SArjun Roy 		default:
4362c8856c05SArjun Roy 			goto zerocopy_rcv_out;
4363c8856c05SArjun Roy 		}
43647eeba170SArjun Roy zerocopy_rcv_cmsg:
43657eeba170SArjun Roy 		if (zc.msg_flags & TCP_CMSG_TS)
43667eeba170SArjun Roy 			tcp_zc_finalize_rx_tstamp(sk, &zc, &tss);
43677eeba170SArjun Roy 		else
43687eeba170SArjun Roy 			zc.msg_flags = 0;
436933946518SArjun Roy zerocopy_rcv_sk_err:
437033946518SArjun Roy 		if (!err)
437133946518SArjun Roy 			zc.err = sock_error(sk);
4372c8856c05SArjun Roy zerocopy_rcv_inq:
4373c8856c05SArjun Roy 		zc.inq = tcp_inq_hint(sk);
4374c8856c05SArjun Roy zerocopy_rcv_out:
437534704ef0SMartin KaFai Lau 		if (!err && copy_to_sockptr(optval, &zc, len))
437605255b82SEric Dumazet 			err = -EFAULT;
437705255b82SEric Dumazet 		return err;
437805255b82SEric Dumazet 	}
437905255b82SEric Dumazet #endif
43801da177e4SLinus Torvalds 	default:
43811da177e4SLinus Torvalds 		return -ENOPROTOOPT;
43823ff50b79SStephen Hemminger 	}
43831da177e4SLinus Torvalds 
438434704ef0SMartin KaFai Lau 	if (copy_to_sockptr(optlen, &len, sizeof(int)))
43851da177e4SLinus Torvalds 		return -EFAULT;
438634704ef0SMartin KaFai Lau 	if (copy_to_sockptr(optval, &val, len))
43871da177e4SLinus Torvalds 		return -EFAULT;
43881da177e4SLinus Torvalds 	return 0;
43891da177e4SLinus Torvalds }
43901da177e4SLinus Torvalds 
43919cacf81fSStanislav Fomichev bool tcp_bpf_bypass_getsockopt(int level, int optname)
43929cacf81fSStanislav Fomichev {
43939cacf81fSStanislav Fomichev 	/* TCP do_tcp_getsockopt has optimized getsockopt implementation
43949cacf81fSStanislav Fomichev 	 * to avoid extra socket lock for TCP_ZEROCOPY_RECEIVE.
43959cacf81fSStanislav Fomichev 	 */
43969cacf81fSStanislav Fomichev 	if (level == SOL_TCP && optname == TCP_ZEROCOPY_RECEIVE)
43979cacf81fSStanislav Fomichev 		return true;
43989cacf81fSStanislav Fomichev 
43999cacf81fSStanislav Fomichev 	return false;
44009cacf81fSStanislav Fomichev }
44019cacf81fSStanislav Fomichev EXPORT_SYMBOL(tcp_bpf_bypass_getsockopt);
44029cacf81fSStanislav Fomichev 
44033fdadf7dSDmitry Mishin int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
44043fdadf7dSDmitry Mishin 		   int __user *optlen)
44053fdadf7dSDmitry Mishin {
44063fdadf7dSDmitry Mishin 	struct inet_connection_sock *icsk = inet_csk(sk);
44073fdadf7dSDmitry Mishin 
44083fdadf7dSDmitry Mishin 	if (level != SOL_TCP)
4409f49cd2f4SKuniyuki Iwashima 		/* Paired with WRITE_ONCE() in do_ipv6_setsockopt() and tcp_v6_connect() */
4410f49cd2f4SKuniyuki Iwashima 		return READ_ONCE(icsk->icsk_af_ops)->getsockopt(sk, level, optname,
44113fdadf7dSDmitry Mishin 								optval, optlen);
441234704ef0SMartin KaFai Lau 	return do_tcp_getsockopt(sk, level, optname, USER_SOCKPTR(optval),
441334704ef0SMartin KaFai Lau 				 USER_SOCKPTR(optlen));
44143fdadf7dSDmitry Mishin }
44154bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_getsockopt);
44163fdadf7dSDmitry Mishin 
4417cfb6eeb4SYOSHIFUJI Hideaki #ifdef CONFIG_TCP_MD5SIG
4418349ce993SEric Dumazet static DEFINE_PER_CPU(struct tcp_md5sig_pool, tcp_md5sig_pool);
441971cea17eSEric Dumazet static DEFINE_MUTEX(tcp_md5sig_mutex);
4420349ce993SEric Dumazet static bool tcp_md5sig_pool_populated = false;
4421cfb6eeb4SYOSHIFUJI Hideaki 
442271cea17eSEric Dumazet static void __tcp_alloc_md5sig_pool(void)
4423cfb6eeb4SYOSHIFUJI Hideaki {
4424cf80e0e4SHerbert Xu 	struct crypto_ahash *hash;
4425cfb6eeb4SYOSHIFUJI Hideaki 	int cpu;
4426cfb6eeb4SYOSHIFUJI Hideaki 
4427cf80e0e4SHerbert Xu 	hash = crypto_alloc_ahash("md5", 0, CRYPTO_ALG_ASYNC);
44281eea84b7SInsu Yun 	if (IS_ERR(hash))
4429349ce993SEric Dumazet 		return;
4430cf80e0e4SHerbert Xu 
4431cf80e0e4SHerbert Xu 	for_each_possible_cpu(cpu) {
443219689e38SEric Dumazet 		void *scratch = per_cpu(tcp_md5sig_pool, cpu).scratch;
4433cf80e0e4SHerbert Xu 		struct ahash_request *req;
4434cf80e0e4SHerbert Xu 
443519689e38SEric Dumazet 		if (!scratch) {
443619689e38SEric Dumazet 			scratch = kmalloc_node(sizeof(union tcp_md5sum_block) +
443719689e38SEric Dumazet 					       sizeof(struct tcphdr),
443819689e38SEric Dumazet 					       GFP_KERNEL,
443919689e38SEric Dumazet 					       cpu_to_node(cpu));
444019689e38SEric Dumazet 			if (!scratch)
444119689e38SEric Dumazet 				return;
444219689e38SEric Dumazet 			per_cpu(tcp_md5sig_pool, cpu).scratch = scratch;
444319689e38SEric Dumazet 		}
4444cf80e0e4SHerbert Xu 		if (per_cpu(tcp_md5sig_pool, cpu).md5_req)
4445cf80e0e4SHerbert Xu 			continue;
4446cf80e0e4SHerbert Xu 
4447cf80e0e4SHerbert Xu 		req = ahash_request_alloc(hash, GFP_KERNEL);
4448cf80e0e4SHerbert Xu 		if (!req)
4449cf80e0e4SHerbert Xu 			return;
4450cf80e0e4SHerbert Xu 
4451cf80e0e4SHerbert Xu 		ahash_request_set_callback(req, 0, NULL, NULL);
4452cf80e0e4SHerbert Xu 
4453cf80e0e4SHerbert Xu 		per_cpu(tcp_md5sig_pool, cpu).md5_req = req;
4454349ce993SEric Dumazet 	}
4455349ce993SEric Dumazet 	/* before setting tcp_md5sig_pool_populated, we must commit all writes
4456349ce993SEric Dumazet 	 * to memory. See smp_rmb() in tcp_get_md5sig_pool()
445771cea17eSEric Dumazet 	 */
445871cea17eSEric Dumazet 	smp_wmb();
4459aacd467cSEric Dumazet 	/* Paired with READ_ONCE() from tcp_alloc_md5sig_pool()
4460aacd467cSEric Dumazet 	 * and tcp_get_md5sig_pool().
4461aacd467cSEric Dumazet 	*/
4462aacd467cSEric Dumazet 	WRITE_ONCE(tcp_md5sig_pool_populated, true);
4463cfb6eeb4SYOSHIFUJI Hideaki }
4464cfb6eeb4SYOSHIFUJI Hideaki 
446571cea17eSEric Dumazet bool tcp_alloc_md5sig_pool(void)
4466cfb6eeb4SYOSHIFUJI Hideaki {
4467aacd467cSEric Dumazet 	/* Paired with WRITE_ONCE() from __tcp_alloc_md5sig_pool() */
4468aacd467cSEric Dumazet 	if (unlikely(!READ_ONCE(tcp_md5sig_pool_populated))) {
446971cea17eSEric Dumazet 		mutex_lock(&tcp_md5sig_mutex);
4470cfb6eeb4SYOSHIFUJI Hideaki 
4471459837b5SDmitry Safonov 		if (!tcp_md5sig_pool_populated)
447271cea17eSEric Dumazet 			__tcp_alloc_md5sig_pool();
4473cfb6eeb4SYOSHIFUJI Hideaki 
447471cea17eSEric Dumazet 		mutex_unlock(&tcp_md5sig_mutex);
4475cfb6eeb4SYOSHIFUJI Hideaki 	}
4476aacd467cSEric Dumazet 	/* Paired with WRITE_ONCE() from __tcp_alloc_md5sig_pool() */
4477aacd467cSEric Dumazet 	return READ_ONCE(tcp_md5sig_pool_populated);
4478cfb6eeb4SYOSHIFUJI Hideaki }
4479cfb6eeb4SYOSHIFUJI Hideaki EXPORT_SYMBOL(tcp_alloc_md5sig_pool);
4480cfb6eeb4SYOSHIFUJI Hideaki 
448135790c04SEric Dumazet 
448235790c04SEric Dumazet /**
448335790c04SEric Dumazet  *	tcp_get_md5sig_pool - get md5sig_pool for this user
448435790c04SEric Dumazet  *
448535790c04SEric Dumazet  *	We use percpu structure, so if we succeed, we exit with preemption
448635790c04SEric Dumazet  *	and BH disabled, to make sure another thread or softirq handling
448735790c04SEric Dumazet  *	wont try to get same context.
448835790c04SEric Dumazet  */
448935790c04SEric Dumazet struct tcp_md5sig_pool *tcp_get_md5sig_pool(void)
4490cfb6eeb4SYOSHIFUJI Hideaki {
449135790c04SEric Dumazet 	local_bh_disable();
449235790c04SEric Dumazet 
4493aacd467cSEric Dumazet 	/* Paired with WRITE_ONCE() from __tcp_alloc_md5sig_pool() */
4494aacd467cSEric Dumazet 	if (READ_ONCE(tcp_md5sig_pool_populated)) {
4495349ce993SEric Dumazet 		/* coupled with smp_wmb() in __tcp_alloc_md5sig_pool() */
4496349ce993SEric Dumazet 		smp_rmb();
4497349ce993SEric Dumazet 		return this_cpu_ptr(&tcp_md5sig_pool);
4498349ce993SEric Dumazet 	}
449935790c04SEric Dumazet 	local_bh_enable();
450035790c04SEric Dumazet 	return NULL;
4501cfb6eeb4SYOSHIFUJI Hideaki }
450235790c04SEric Dumazet EXPORT_SYMBOL(tcp_get_md5sig_pool);
4503cfb6eeb4SYOSHIFUJI Hideaki 
450449a72dfbSAdam Langley int tcp_md5_hash_skb_data(struct tcp_md5sig_pool *hp,
4505cf533ea5SEric Dumazet 			  const struct sk_buff *skb, unsigned int header_len)
450649a72dfbSAdam Langley {
450749a72dfbSAdam Langley 	struct scatterlist sg;
450849a72dfbSAdam Langley 	const struct tcphdr *tp = tcp_hdr(skb);
4509cf80e0e4SHerbert Xu 	struct ahash_request *req = hp->md5_req;
451095c96174SEric Dumazet 	unsigned int i;
451195c96174SEric Dumazet 	const unsigned int head_data_len = skb_headlen(skb) > header_len ?
451249a72dfbSAdam Langley 					   skb_headlen(skb) - header_len : 0;
451349a72dfbSAdam Langley 	const struct skb_shared_info *shi = skb_shinfo(skb);
4514d7fd1b57SEric Dumazet 	struct sk_buff *frag_iter;
451549a72dfbSAdam Langley 
451649a72dfbSAdam Langley 	sg_init_table(&sg, 1);
451749a72dfbSAdam Langley 
451849a72dfbSAdam Langley 	sg_set_buf(&sg, ((u8 *) tp) + header_len, head_data_len);
4519cf80e0e4SHerbert Xu 	ahash_request_set_crypt(req, &sg, NULL, head_data_len);
4520cf80e0e4SHerbert Xu 	if (crypto_ahash_update(req))
452149a72dfbSAdam Langley 		return 1;
452249a72dfbSAdam Langley 
452349a72dfbSAdam Langley 	for (i = 0; i < shi->nr_frags; ++i) {
4524d8e18a51SMatthew Wilcox (Oracle) 		const skb_frag_t *f = &shi->frags[i];
4525b54c9d5bSJonathan Lemon 		unsigned int offset = skb_frag_off(f);
452654d27fcbSEric Dumazet 		struct page *page = skb_frag_page(f) + (offset >> PAGE_SHIFT);
452754d27fcbSEric Dumazet 
452854d27fcbSEric Dumazet 		sg_set_page(&sg, page, skb_frag_size(f),
452954d27fcbSEric Dumazet 			    offset_in_page(offset));
4530cf80e0e4SHerbert Xu 		ahash_request_set_crypt(req, &sg, NULL, skb_frag_size(f));
4531cf80e0e4SHerbert Xu 		if (crypto_ahash_update(req))
453249a72dfbSAdam Langley 			return 1;
453349a72dfbSAdam Langley 	}
453449a72dfbSAdam Langley 
4535d7fd1b57SEric Dumazet 	skb_walk_frags(skb, frag_iter)
4536d7fd1b57SEric Dumazet 		if (tcp_md5_hash_skb_data(hp, frag_iter, 0))
4537d7fd1b57SEric Dumazet 			return 1;
4538d7fd1b57SEric Dumazet 
453949a72dfbSAdam Langley 	return 0;
454049a72dfbSAdam Langley }
454149a72dfbSAdam Langley EXPORT_SYMBOL(tcp_md5_hash_skb_data);
454249a72dfbSAdam Langley 
4543cf533ea5SEric Dumazet int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key)
454449a72dfbSAdam Langley {
4545e6ced831SEric Dumazet 	u8 keylen = READ_ONCE(key->keylen); /* paired with WRITE_ONCE() in tcp_md5_do_add */
454649a72dfbSAdam Langley 	struct scatterlist sg;
454749a72dfbSAdam Langley 
45486a2febecSEric Dumazet 	sg_init_one(&sg, key->key, keylen);
45496a2febecSEric Dumazet 	ahash_request_set_crypt(hp->md5_req, &sg, NULL, keylen);
4550e6ced831SEric Dumazet 
4551e6ced831SEric Dumazet 	/* We use data_race() because tcp_md5_do_add() might change key->key under us */
4552e6ced831SEric Dumazet 	return data_race(crypto_ahash_update(hp->md5_req));
455349a72dfbSAdam Langley }
455449a72dfbSAdam Langley EXPORT_SYMBOL(tcp_md5_hash_key);
455549a72dfbSAdam Langley 
45567bbb765bSDmitry Safonov /* Called with rcu_read_lock() */
45571330b6efSJakub Kicinski enum skb_drop_reason
45581330b6efSJakub Kicinski tcp_inbound_md5_hash(const struct sock *sk, const struct sk_buff *skb,
45597bbb765bSDmitry Safonov 		     const void *saddr, const void *daddr,
45607bbb765bSDmitry Safonov 		     int family, int dif, int sdif)
45617bbb765bSDmitry Safonov {
45627bbb765bSDmitry Safonov 	/*
45637bbb765bSDmitry Safonov 	 * This gets called for each TCP segment that arrives
45647bbb765bSDmitry Safonov 	 * so we want to be efficient.
45657bbb765bSDmitry Safonov 	 * We have 3 drop cases:
45667bbb765bSDmitry Safonov 	 * o No MD5 hash and one expected.
45677bbb765bSDmitry Safonov 	 * o MD5 hash and we're not expecting one.
45687bbb765bSDmitry Safonov 	 * o MD5 hash and its wrong.
45697bbb765bSDmitry Safonov 	 */
45707bbb765bSDmitry Safonov 	const __u8 *hash_location = NULL;
45717bbb765bSDmitry Safonov 	struct tcp_md5sig_key *hash_expected;
45727bbb765bSDmitry Safonov 	const struct tcphdr *th = tcp_hdr(skb);
4573*e9d9da91SEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
45747bbb765bSDmitry Safonov 	int genhash, l3index;
45757bbb765bSDmitry Safonov 	u8 newhash[16];
45767bbb765bSDmitry Safonov 
45777bbb765bSDmitry Safonov 	/* sdif set, means packet ingressed via a device
45787bbb765bSDmitry Safonov 	 * in an L3 domain and dif is set to the l3mdev
45797bbb765bSDmitry Safonov 	 */
45807bbb765bSDmitry Safonov 	l3index = sdif ? dif : 0;
45817bbb765bSDmitry Safonov 
45827bbb765bSDmitry Safonov 	hash_expected = tcp_md5_do_lookup(sk, l3index, saddr, family);
45837bbb765bSDmitry Safonov 	hash_location = tcp_parse_md5sig_option(th);
45847bbb765bSDmitry Safonov 
45857bbb765bSDmitry Safonov 	/* We've parsed the options - do we have a hash? */
45867bbb765bSDmitry Safonov 	if (!hash_expected && !hash_location)
45871330b6efSJakub Kicinski 		return SKB_NOT_DROPPED_YET;
45887bbb765bSDmitry Safonov 
45897bbb765bSDmitry Safonov 	if (hash_expected && !hash_location) {
45907bbb765bSDmitry Safonov 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5NOTFOUND);
45911330b6efSJakub Kicinski 		return SKB_DROP_REASON_TCP_MD5NOTFOUND;
45927bbb765bSDmitry Safonov 	}
45937bbb765bSDmitry Safonov 
45947bbb765bSDmitry Safonov 	if (!hash_expected && hash_location) {
45957bbb765bSDmitry Safonov 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5UNEXPECTED);
45961330b6efSJakub Kicinski 		return SKB_DROP_REASON_TCP_MD5UNEXPECTED;
45977bbb765bSDmitry Safonov 	}
45987bbb765bSDmitry Safonov 
4599e62d2e11SEric Dumazet 	/* Check the signature.
4600e62d2e11SEric Dumazet 	 * To support dual stack listeners, we need to handle
4601e62d2e11SEric Dumazet 	 * IPv4-mapped case.
4602e62d2e11SEric Dumazet 	 */
4603e62d2e11SEric Dumazet 	if (family == AF_INET)
4604e62d2e11SEric Dumazet 		genhash = tcp_v4_md5_hash_skb(newhash,
4605e62d2e11SEric Dumazet 					      hash_expected,
4606e62d2e11SEric Dumazet 					      NULL, skb);
4607e62d2e11SEric Dumazet 	else
4608e62d2e11SEric Dumazet 		genhash = tp->af_specific->calc_md5_hash(newhash,
4609e62d2e11SEric Dumazet 							 hash_expected,
46107bbb765bSDmitry Safonov 							 NULL, skb);
46117bbb765bSDmitry Safonov 
46127bbb765bSDmitry Safonov 	if (genhash || memcmp(hash_location, newhash, 16) != 0) {
46137bbb765bSDmitry Safonov 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5FAILURE);
46147bbb765bSDmitry Safonov 		if (family == AF_INET) {
46157bbb765bSDmitry Safonov 			net_info_ratelimited("MD5 Hash failed for (%pI4, %d)->(%pI4, %d)%s L3 index %d\n",
46167bbb765bSDmitry Safonov 					saddr, ntohs(th->source),
46177bbb765bSDmitry Safonov 					daddr, ntohs(th->dest),
46187bbb765bSDmitry Safonov 					genhash ? " tcp_v4_calc_md5_hash failed"
46197bbb765bSDmitry Safonov 					: "", l3index);
46207bbb765bSDmitry Safonov 		} else {
46217bbb765bSDmitry Safonov 			net_info_ratelimited("MD5 Hash %s for [%pI6c]:%u->[%pI6c]:%u L3 index %d\n",
46227bbb765bSDmitry Safonov 					genhash ? "failed" : "mismatch",
46237bbb765bSDmitry Safonov 					saddr, ntohs(th->source),
46247bbb765bSDmitry Safonov 					daddr, ntohs(th->dest), l3index);
46257bbb765bSDmitry Safonov 		}
46261330b6efSJakub Kicinski 		return SKB_DROP_REASON_TCP_MD5FAILURE;
46277bbb765bSDmitry Safonov 	}
46281330b6efSJakub Kicinski 	return SKB_NOT_DROPPED_YET;
46297bbb765bSDmitry Safonov }
46307bbb765bSDmitry Safonov EXPORT_SYMBOL(tcp_inbound_md5_hash);
46317bbb765bSDmitry Safonov 
4632cfb6eeb4SYOSHIFUJI Hideaki #endif
4633cfb6eeb4SYOSHIFUJI Hideaki 
46344ac02babSAndi Kleen void tcp_done(struct sock *sk)
46354ac02babSAndi Kleen {
4636d983ea6fSEric Dumazet 	struct request_sock *req;
46378336886fSJerry Chu 
4638cab209e5SEric Dumazet 	/* We might be called with a new socket, after
4639cab209e5SEric Dumazet 	 * inet_csk_prepare_forced_close() has been called
4640cab209e5SEric Dumazet 	 * so we can not use lockdep_sock_is_held(sk)
4641cab209e5SEric Dumazet 	 */
4642cab209e5SEric Dumazet 	req = rcu_dereference_protected(tcp_sk(sk)->fastopen_rsk, 1);
46434ac02babSAndi Kleen 
46444ac02babSAndi Kleen 	if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV)
4645c10d9310SEric Dumazet 		TCP_INC_STATS(sock_net(sk), TCP_MIB_ATTEMPTFAILS);
46464ac02babSAndi Kleen 
46474ac02babSAndi Kleen 	tcp_set_state(sk, TCP_CLOSE);
46484ac02babSAndi Kleen 	tcp_clear_xmit_timers(sk);
464900db4124SIan Morris 	if (req)
46508336886fSJerry Chu 		reqsk_fastopen_remove(sk, req, false);
46514ac02babSAndi Kleen 
46524ac02babSAndi Kleen 	sk->sk_shutdown = SHUTDOWN_MASK;
46534ac02babSAndi Kleen 
46544ac02babSAndi Kleen 	if (!sock_flag(sk, SOCK_DEAD))
46554ac02babSAndi Kleen 		sk->sk_state_change(sk);
46564ac02babSAndi Kleen 	else
46574ac02babSAndi Kleen 		inet_csk_destroy_sock(sk);
46584ac02babSAndi Kleen }
46594ac02babSAndi Kleen EXPORT_SYMBOL_GPL(tcp_done);
46604ac02babSAndi Kleen 
4661c1e64e29SLorenzo Colitti int tcp_abort(struct sock *sk, int err)
4662c1e64e29SLorenzo Colitti {
4663af9784d0SEric Dumazet 	int state = inet_sk_state_load(sk);
4664af9784d0SEric Dumazet 
4665af9784d0SEric Dumazet 	if (state == TCP_NEW_SYN_RECV) {
466607f6f4a3SEric Dumazet 		struct request_sock *req = inet_reqsk(sk);
466707f6f4a3SEric Dumazet 
466807f6f4a3SEric Dumazet 		local_bh_disable();
4669acc2cf4eSLorenzo Colitti 		inet_csk_reqsk_queue_drop(req->rsk_listener, req);
467007f6f4a3SEric Dumazet 		local_bh_enable();
467107f6f4a3SEric Dumazet 		return 0;
467207f6f4a3SEric Dumazet 	}
4673af9784d0SEric Dumazet 	if (state == TCP_TIME_WAIT) {
4674af9784d0SEric Dumazet 		struct inet_timewait_sock *tw = inet_twsk(sk);
4675af9784d0SEric Dumazet 
4676af9784d0SEric Dumazet 		refcount_inc(&tw->tw_refcnt);
4677af9784d0SEric Dumazet 		local_bh_disable();
4678af9784d0SEric Dumazet 		inet_twsk_deschedule_put(tw);
4679af9784d0SEric Dumazet 		local_bh_enable();
4680af9784d0SEric Dumazet 		return 0;
4681c1e64e29SLorenzo Colitti 	}
4682c1e64e29SLorenzo Colitti 
4683c1e64e29SLorenzo Colitti 	/* Don't race with userspace socket closes such as tcp_close. */
4684c1e64e29SLorenzo Colitti 	lock_sock(sk);
4685c1e64e29SLorenzo Colitti 
46862010b93eSLorenzo Colitti 	if (sk->sk_state == TCP_LISTEN) {
46872010b93eSLorenzo Colitti 		tcp_set_state(sk, TCP_CLOSE);
46882010b93eSLorenzo Colitti 		inet_csk_listen_stop(sk);
46892010b93eSLorenzo Colitti 	}
46902010b93eSLorenzo Colitti 
4691c1e64e29SLorenzo Colitti 	/* Don't race with BH socket closes such as inet_csk_listen_stop. */
4692c1e64e29SLorenzo Colitti 	local_bh_disable();
4693c1e64e29SLorenzo Colitti 	bh_lock_sock(sk);
4694c1e64e29SLorenzo Colitti 
4695c1e64e29SLorenzo Colitti 	if (!sock_flag(sk, SOCK_DEAD)) {
4696e13ec3daSEric Dumazet 		WRITE_ONCE(sk->sk_err, err);
4697c1e64e29SLorenzo Colitti 		/* This barrier is coupled with smp_rmb() in tcp_poll() */
4698c1e64e29SLorenzo Colitti 		smp_wmb();
4699e3ae2365SAlexander Aring 		sk_error_report(sk);
4700c1e64e29SLorenzo Colitti 		if (tcp_need_reset(sk->sk_state))
4701c1e64e29SLorenzo Colitti 			tcp_send_active_reset(sk, GFP_ATOMIC);
4702c1e64e29SLorenzo Colitti 		tcp_done(sk);
4703c1e64e29SLorenzo Colitti 	}
4704c1e64e29SLorenzo Colitti 
4705c1e64e29SLorenzo Colitti 	bh_unlock_sock(sk);
4706c1e64e29SLorenzo Colitti 	local_bh_enable();
4707e05836acSSoheil Hassas Yeganeh 	tcp_write_queue_purge(sk);
4708c1e64e29SLorenzo Colitti 	release_sock(sk);
4709c1e64e29SLorenzo Colitti 	return 0;
4710c1e64e29SLorenzo Colitti }
4711c1e64e29SLorenzo Colitti EXPORT_SYMBOL_GPL(tcp_abort);
4712c1e64e29SLorenzo Colitti 
47135f8ef48dSStephen Hemminger extern struct tcp_congestion_ops tcp_reno;
47141da177e4SLinus Torvalds 
47151da177e4SLinus Torvalds static __initdata unsigned long thash_entries;
47161da177e4SLinus Torvalds static int __init set_thash_entries(char *str)
47171da177e4SLinus Torvalds {
4718413c27d8SEldad Zack 	ssize_t ret;
4719413c27d8SEldad Zack 
47201da177e4SLinus Torvalds 	if (!str)
47211da177e4SLinus Torvalds 		return 0;
4722413c27d8SEldad Zack 
4723413c27d8SEldad Zack 	ret = kstrtoul(str, 0, &thash_entries);
4724413c27d8SEldad Zack 	if (ret)
4725413c27d8SEldad Zack 		return 0;
4726413c27d8SEldad Zack 
47271da177e4SLinus Torvalds 	return 1;
47281da177e4SLinus Torvalds }
47291da177e4SLinus Torvalds __setup("thash_entries=", set_thash_entries);
47301da177e4SLinus Torvalds 
473147d7a88cSFabian Frederick static void __init tcp_init_mem(void)
47324acb4190SGlauber Costa {
4733b66e91ccSEric Dumazet 	unsigned long limit = nr_free_buffer_pages() / 16;
4734b66e91ccSEric Dumazet 
47354acb4190SGlauber Costa 	limit = max(limit, 128UL);
4736b66e91ccSEric Dumazet 	sysctl_tcp_mem[0] = limit / 4 * 3;		/* 4.68 % */
4737b66e91ccSEric Dumazet 	sysctl_tcp_mem[1] = limit;			/* 6.25 % */
4738b66e91ccSEric Dumazet 	sysctl_tcp_mem[2] = sysctl_tcp_mem[0] * 2;	/* 9.37 % */
47394acb4190SGlauber Costa }
47404acb4190SGlauber Costa 
47411da177e4SLinus Torvalds void __init tcp_init(void)
47421da177e4SLinus Torvalds {
4743b49960a0SEric Dumazet 	int max_rshare, max_wshare, cnt;
4744b2d3ea4aSEric Dumazet 	unsigned long limit;
4745074b8517SDimitri Sivanich 	unsigned int i;
47461da177e4SLinus Torvalds 
47473b4929f6SEric Dumazet 	BUILD_BUG_ON(TCP_MIN_SND_MSS <= MAX_TCP_OPTION_SPACE);
4748b2d3ea4aSEric Dumazet 	BUILD_BUG_ON(sizeof(struct tcp_skb_cb) >
4749c593642cSPankaj Bharadiya 		     sizeof_field(struct sk_buff, cb));
47501da177e4SLinus Torvalds 
4751908c7f19STejun Heo 	percpu_counter_init(&tcp_sockets_allocated, 0, GFP_KERNEL);
475219757cebSEric Dumazet 
475319757cebSEric Dumazet 	timer_setup(&tcp_orphan_timer, tcp_orphan_update, TIMER_DEFERRABLE);
475419757cebSEric Dumazet 	mod_timer(&tcp_orphan_timer, jiffies + TCP_ORPHAN_TIMER_PERIOD);
475519757cebSEric Dumazet 
475627da6d37SMartin KaFai Lau 	inet_hashinfo2_init(&tcp_hashinfo, "tcp_listen_portaddr_hash",
475727da6d37SMartin KaFai Lau 			    thash_entries, 21,  /* one slot per 2 MB*/
475827da6d37SMartin KaFai Lau 			    0, 64 * 1024);
47596e04e021SArnaldo Carvalho de Melo 	tcp_hashinfo.bind_bucket_cachep =
47606e04e021SArnaldo Carvalho de Melo 		kmem_cache_create("tcp_bind_bucket",
47616e04e021SArnaldo Carvalho de Melo 				  sizeof(struct inet_bind_bucket), 0,
4762990c74e3SVasily Averin 				  SLAB_HWCACHE_ALIGN | SLAB_PANIC |
4763990c74e3SVasily Averin 				  SLAB_ACCOUNT,
4764990c74e3SVasily Averin 				  NULL);
476528044fc1SJoanne Koong 	tcp_hashinfo.bind2_bucket_cachep =
476628044fc1SJoanne Koong 		kmem_cache_create("tcp_bind2_bucket",
476728044fc1SJoanne Koong 				  sizeof(struct inet_bind2_bucket), 0,
476828044fc1SJoanne Koong 				  SLAB_HWCACHE_ALIGN | SLAB_PANIC |
476928044fc1SJoanne Koong 				  SLAB_ACCOUNT,
477028044fc1SJoanne Koong 				  NULL);
47711da177e4SLinus Torvalds 
47721da177e4SLinus Torvalds 	/* Size and allocate the main established and bind bucket
47731da177e4SLinus Torvalds 	 * hash tables.
47741da177e4SLinus Torvalds 	 *
47751da177e4SLinus Torvalds 	 * The methodology is similar to that of the buffer cache.
47761da177e4SLinus Torvalds 	 */
47776e04e021SArnaldo Carvalho de Melo 	tcp_hashinfo.ehash =
47781da177e4SLinus Torvalds 		alloc_large_system_hash("TCP established",
47790f7ff927SArnaldo Carvalho de Melo 					sizeof(struct inet_ehash_bucket),
47801da177e4SLinus Torvalds 					thash_entries,
4781fd90b29dSEric Dumazet 					17, /* one slot per 128 KB of memory */
47829e950efaSJohn Heffner 					0,
47831da177e4SLinus Torvalds 					NULL,
4784f373b53bSEric Dumazet 					&tcp_hashinfo.ehash_mask,
478531fe62b9STim Bird 					0,
47860ccfe618SJean Delvare 					thash_entries ? 0 : 512 * 1024);
478705dbc7b5SEric Dumazet 	for (i = 0; i <= tcp_hashinfo.ehash_mask; i++)
47883ab5aee7SEric Dumazet 		INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i);
478905dbc7b5SEric Dumazet 
4790230140cfSEric Dumazet 	if (inet_ehash_locks_alloc(&tcp_hashinfo))
4791230140cfSEric Dumazet 		panic("TCP: failed to alloc ehash_locks");
47926e04e021SArnaldo Carvalho de Melo 	tcp_hashinfo.bhash =
4793593d1ebeSJoanne Koong 		alloc_large_system_hash("TCP bind",
479428044fc1SJoanne Koong 					2 * sizeof(struct inet_bind_hashbucket),
4795f373b53bSEric Dumazet 					tcp_hashinfo.ehash_mask + 1,
4796fd90b29dSEric Dumazet 					17, /* one slot per 128 KB of memory */
47979e950efaSJohn Heffner 					0,
47986e04e021SArnaldo Carvalho de Melo 					&tcp_hashinfo.bhash_size,
47991da177e4SLinus Torvalds 					NULL,
480031fe62b9STim Bird 					0,
48011da177e4SLinus Torvalds 					64 * 1024);
4802074b8517SDimitri Sivanich 	tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size;
480328044fc1SJoanne Koong 	tcp_hashinfo.bhash2 = tcp_hashinfo.bhash + tcp_hashinfo.bhash_size;
48046e04e021SArnaldo Carvalho de Melo 	for (i = 0; i < tcp_hashinfo.bhash_size; i++) {
48056e04e021SArnaldo Carvalho de Melo 		spin_lock_init(&tcp_hashinfo.bhash[i].lock);
48066e04e021SArnaldo Carvalho de Melo 		INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain);
480728044fc1SJoanne Koong 		spin_lock_init(&tcp_hashinfo.bhash2[i].lock);
480828044fc1SJoanne Koong 		INIT_HLIST_HEAD(&tcp_hashinfo.bhash2[i].chain);
48091da177e4SLinus Torvalds 	}
48101da177e4SLinus Torvalds 
4811d1e5e640SKuniyuki Iwashima 	tcp_hashinfo.pernet = false;
4812c5ed63d6SEric Dumazet 
4813c5ed63d6SEric Dumazet 	cnt = tcp_hashinfo.ehash_mask + 1;
4814c5ed63d6SEric Dumazet 	sysctl_tcp_max_orphans = cnt / 2;
48151da177e4SLinus Torvalds 
4816a4fe34bfSEric W. Biederman 	tcp_init_mem();
4817c43b874dSJason Wang 	/* Set per-socket limits to no more than 1/128 the pressure threshold */
48185fb84b14SEric Dumazet 	limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7);
4819b49960a0SEric Dumazet 	max_wshare = min(4UL*1024*1024, limit);
4820b49960a0SEric Dumazet 	max_rshare = min(6UL*1024*1024, limit);
48217b4f4b5eSJohn Heffner 
4822100fdd1fSEric Dumazet 	init_net.ipv4.sysctl_tcp_wmem[0] = PAGE_SIZE;
4823356d1833SEric Dumazet 	init_net.ipv4.sysctl_tcp_wmem[1] = 16*1024;
4824356d1833SEric Dumazet 	init_net.ipv4.sysctl_tcp_wmem[2] = max(64*1024, max_wshare);
48257b4f4b5eSJohn Heffner 
4826100fdd1fSEric Dumazet 	init_net.ipv4.sysctl_tcp_rmem[0] = PAGE_SIZE;
4827a337531bSYuchung Cheng 	init_net.ipv4.sysctl_tcp_rmem[1] = 131072;
4828a337531bSYuchung Cheng 	init_net.ipv4.sysctl_tcp_rmem[2] = max(131072, max_rshare);
48291da177e4SLinus Torvalds 
4830afd46503SJoe Perches 	pr_info("Hash tables configured (established %u bind %u)\n",
4831f373b53bSEric Dumazet 		tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size);
4832317a76f9SStephen Hemminger 
48331946e672SHaishuang Yan 	tcp_v4_init();
483451c5d0c4SDavid S. Miller 	tcp_metrics_init();
483555d8694fSFlorian Westphal 	BUG_ON(tcp_register_congestion_control(&tcp_reno) != 0);
483646d3ceabSEric Dumazet 	tcp_tasklet_init();
4837f870fa0bSMat Martineau 	mptcp_init();
48381da177e4SLinus Torvalds }
4839