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