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