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