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