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