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