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