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