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