Linux Audio

Check our new training course

Loading...
Note: File does not exist in v3.1.
   1// SPDX-License-Identifier: GPL-2.0
   2/* Multipath TCP
   3 *
   4 * Copyright (c) 2017 - 2019, Intel Corporation.
   5 */
   6
   7#define pr_fmt(fmt) "MPTCP: " fmt
   8
   9#include <linux/kernel.h>
  10#include <linux/module.h>
  11#include <linux/netdevice.h>
  12#include <linux/sched/signal.h>
  13#include <linux/atomic.h>
  14#include <net/sock.h>
  15#include <net/inet_common.h>
  16#include <net/inet_hashtables.h>
  17#include <net/protocol.h>
  18#include <net/tcp.h>
  19#include <net/tcp_states.h>
  20#if IS_ENABLED(CONFIG_MPTCP_IPV6)
  21#include <net/transp_v6.h>
  22#endif
  23#include <net/mptcp.h>
  24#include <net/xfrm.h>
  25#include <asm/ioctls.h>
  26#include "protocol.h"
  27#include "mib.h"
  28
  29#define CREATE_TRACE_POINTS
  30#include <trace/events/mptcp.h>
  31
  32#if IS_ENABLED(CONFIG_MPTCP_IPV6)
  33struct mptcp6_sock {
  34	struct mptcp_sock msk;
  35	struct ipv6_pinfo np;
  36};
  37#endif
  38
  39enum {
  40	MPTCP_CMSG_TS = BIT(0),
  41	MPTCP_CMSG_INQ = BIT(1),
  42};
  43
  44static struct percpu_counter mptcp_sockets_allocated ____cacheline_aligned_in_smp;
  45
  46static void __mptcp_destroy_sock(struct sock *sk);
  47static void __mptcp_check_send_data_fin(struct sock *sk);
  48
  49DEFINE_PER_CPU(struct mptcp_delegated_action, mptcp_delegated_actions);
  50static struct net_device mptcp_napi_dev;
  51
  52/* If msk has an initial subflow socket, and the MP_CAPABLE handshake has not
  53 * completed yet or has failed, return the subflow socket.
  54 * Otherwise return NULL.
  55 */
  56struct socket *__mptcp_nmpc_socket(const struct mptcp_sock *msk)
  57{
  58	if (!msk->subflow || READ_ONCE(msk->can_ack))
  59		return NULL;
  60
  61	return msk->subflow;
  62}
  63
  64/* Returns end sequence number of the receiver's advertised window */
  65static u64 mptcp_wnd_end(const struct mptcp_sock *msk)
  66{
  67	return READ_ONCE(msk->wnd_end);
  68}
  69
  70static bool mptcp_is_tcpsk(struct sock *sk)
  71{
  72	struct socket *sock = sk->sk_socket;
  73
  74	if (unlikely(sk->sk_prot == &tcp_prot)) {
  75		/* we are being invoked after mptcp_accept() has
  76		 * accepted a non-mp-capable flow: sk is a tcp_sk,
  77		 * not an mptcp one.
  78		 *
  79		 * Hand the socket over to tcp so all further socket ops
  80		 * bypass mptcp.
  81		 */
  82		sock->ops = &inet_stream_ops;
  83		return true;
  84#if IS_ENABLED(CONFIG_MPTCP_IPV6)
  85	} else if (unlikely(sk->sk_prot == &tcpv6_prot)) {
  86		sock->ops = &inet6_stream_ops;
  87		return true;
  88#endif
  89	}
  90
  91	return false;
  92}
  93
  94static int __mptcp_socket_create(struct mptcp_sock *msk)
  95{
  96	struct mptcp_subflow_context *subflow;
  97	struct sock *sk = (struct sock *)msk;
  98	struct socket *ssock;
  99	int err;
 100
 101	err = mptcp_subflow_create_socket(sk, sk->sk_family, &ssock);
 102	if (err)
 103		return err;
 104
 105	msk->first = ssock->sk;
 106	msk->subflow = ssock;
 107	subflow = mptcp_subflow_ctx(ssock->sk);
 108	list_add(&subflow->node, &msk->conn_list);
 109	sock_hold(ssock->sk);
 110	subflow->request_mptcp = 1;
 111
 112	/* This is the first subflow, always with id 0 */
 113	subflow->local_id_valid = 1;
 114	mptcp_sock_graft(msk->first, sk->sk_socket);
 115
 116	return 0;
 117}
 118
 119static void mptcp_drop(struct sock *sk, struct sk_buff *skb)
 120{
 121	sk_drops_add(sk, skb);
 122	__kfree_skb(skb);
 123}
 124
 125static void mptcp_rmem_charge(struct sock *sk, int size)
 126{
 127	mptcp_sk(sk)->rmem_fwd_alloc -= size;
 128}
 129
 130static bool mptcp_try_coalesce(struct sock *sk, struct sk_buff *to,
 131			       struct sk_buff *from)
 132{
 133	bool fragstolen;
 134	int delta;
 135
 136	if (MPTCP_SKB_CB(from)->offset ||
 137	    !skb_try_coalesce(to, from, &fragstolen, &delta))
 138		return false;
 139
 140	pr_debug("colesced seq %llx into %llx new len %d new end seq %llx",
 141		 MPTCP_SKB_CB(from)->map_seq, MPTCP_SKB_CB(to)->map_seq,
 142		 to->len, MPTCP_SKB_CB(from)->end_seq);
 143	MPTCP_SKB_CB(to)->end_seq = MPTCP_SKB_CB(from)->end_seq;
 144
 145	/* note the fwd memory can reach a negative value after accounting
 146	 * for the delta, but the later skb free will restore a non
 147	 * negative one
 148	 */
 149	atomic_add(delta, &sk->sk_rmem_alloc);
 150	mptcp_rmem_charge(sk, delta);
 151	kfree_skb_partial(from, fragstolen);
 152
 153	return true;
 154}
 155
 156static bool mptcp_ooo_try_coalesce(struct mptcp_sock *msk, struct sk_buff *to,
 157				   struct sk_buff *from)
 158{
 159	if (MPTCP_SKB_CB(from)->map_seq != MPTCP_SKB_CB(to)->end_seq)
 160		return false;
 161
 162	return mptcp_try_coalesce((struct sock *)msk, to, from);
 163}
 164
 165static void __mptcp_rmem_reclaim(struct sock *sk, int amount)
 166{
 167	amount >>= PAGE_SHIFT;
 168	mptcp_sk(sk)->rmem_fwd_alloc -= amount << PAGE_SHIFT;
 169	__sk_mem_reduce_allocated(sk, amount);
 170}
 171
 172static void mptcp_rmem_uncharge(struct sock *sk, int size)
 173{
 174	struct mptcp_sock *msk = mptcp_sk(sk);
 175	int reclaimable;
 176
 177	msk->rmem_fwd_alloc += size;
 178	reclaimable = msk->rmem_fwd_alloc - sk_unused_reserved_mem(sk);
 179
 180	/* see sk_mem_uncharge() for the rationale behind the following schema */
 181	if (unlikely(reclaimable >= PAGE_SIZE))
 182		__mptcp_rmem_reclaim(sk, reclaimable);
 183}
 184
 185static void mptcp_rfree(struct sk_buff *skb)
 186{
 187	unsigned int len = skb->truesize;
 188	struct sock *sk = skb->sk;
 189
 190	atomic_sub(len, &sk->sk_rmem_alloc);
 191	mptcp_rmem_uncharge(sk, len);
 192}
 193
 194void mptcp_set_owner_r(struct sk_buff *skb, struct sock *sk)
 195{
 196	skb_orphan(skb);
 197	skb->sk = sk;
 198	skb->destructor = mptcp_rfree;
 199	atomic_add(skb->truesize, &sk->sk_rmem_alloc);
 200	mptcp_rmem_charge(sk, skb->truesize);
 201}
 202
 203/* "inspired" by tcp_data_queue_ofo(), main differences:
 204 * - use mptcp seqs
 205 * - don't cope with sacks
 206 */
 207static void mptcp_data_queue_ofo(struct mptcp_sock *msk, struct sk_buff *skb)
 208{
 209	struct sock *sk = (struct sock *)msk;
 210	struct rb_node **p, *parent;
 211	u64 seq, end_seq, max_seq;
 212	struct sk_buff *skb1;
 213
 214	seq = MPTCP_SKB_CB(skb)->map_seq;
 215	end_seq = MPTCP_SKB_CB(skb)->end_seq;
 216	max_seq = atomic64_read(&msk->rcv_wnd_sent);
 217
 218	pr_debug("msk=%p seq=%llx limit=%llx empty=%d", msk, seq, max_seq,
 219		 RB_EMPTY_ROOT(&msk->out_of_order_queue));
 220	if (after64(end_seq, max_seq)) {
 221		/* out of window */
 222		mptcp_drop(sk, skb);
 223		pr_debug("oow by %lld, rcv_wnd_sent %llu\n",
 224			 (unsigned long long)end_seq - (unsigned long)max_seq,
 225			 (unsigned long long)atomic64_read(&msk->rcv_wnd_sent));
 226		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_NODSSWINDOW);
 227		return;
 228	}
 229
 230	p = &msk->out_of_order_queue.rb_node;
 231	MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOQUEUE);
 232	if (RB_EMPTY_ROOT(&msk->out_of_order_queue)) {
 233		rb_link_node(&skb->rbnode, NULL, p);
 234		rb_insert_color(&skb->rbnode, &msk->out_of_order_queue);
 235		msk->ooo_last_skb = skb;
 236		goto end;
 237	}
 238
 239	/* with 2 subflows, adding at end of ooo queue is quite likely
 240	 * Use of ooo_last_skb avoids the O(Log(N)) rbtree lookup.
 241	 */
 242	if (mptcp_ooo_try_coalesce(msk, msk->ooo_last_skb, skb)) {
 243		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOMERGE);
 244		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOQUEUETAIL);
 245		return;
 246	}
 247
 248	/* Can avoid an rbtree lookup if we are adding skb after ooo_last_skb */
 249	if (!before64(seq, MPTCP_SKB_CB(msk->ooo_last_skb)->end_seq)) {
 250		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOQUEUETAIL);
 251		parent = &msk->ooo_last_skb->rbnode;
 252		p = &parent->rb_right;
 253		goto insert;
 254	}
 255
 256	/* Find place to insert this segment. Handle overlaps on the way. */
 257	parent = NULL;
 258	while (*p) {
 259		parent = *p;
 260		skb1 = rb_to_skb(parent);
 261		if (before64(seq, MPTCP_SKB_CB(skb1)->map_seq)) {
 262			p = &parent->rb_left;
 263			continue;
 264		}
 265		if (before64(seq, MPTCP_SKB_CB(skb1)->end_seq)) {
 266			if (!after64(end_seq, MPTCP_SKB_CB(skb1)->end_seq)) {
 267				/* All the bits are present. Drop. */
 268				mptcp_drop(sk, skb);
 269				MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
 270				return;
 271			}
 272			if (after64(seq, MPTCP_SKB_CB(skb1)->map_seq)) {
 273				/* partial overlap:
 274				 *     |     skb      |
 275				 *  |     skb1    |
 276				 * continue traversing
 277				 */
 278			} else {
 279				/* skb's seq == skb1's seq and skb covers skb1.
 280				 * Replace skb1 with skb.
 281				 */
 282				rb_replace_node(&skb1->rbnode, &skb->rbnode,
 283						&msk->out_of_order_queue);
 284				mptcp_drop(sk, skb1);
 285				MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
 286				goto merge_right;
 287			}
 288		} else if (mptcp_ooo_try_coalesce(msk, skb1, skb)) {
 289			MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOMERGE);
 290			return;
 291		}
 292		p = &parent->rb_right;
 293	}
 294
 295insert:
 296	/* Insert segment into RB tree. */
 297	rb_link_node(&skb->rbnode, parent, p);
 298	rb_insert_color(&skb->rbnode, &msk->out_of_order_queue);
 299
 300merge_right:
 301	/* Remove other segments covered by skb. */
 302	while ((skb1 = skb_rb_next(skb)) != NULL) {
 303		if (before64(end_seq, MPTCP_SKB_CB(skb1)->end_seq))
 304			break;
 305		rb_erase(&skb1->rbnode, &msk->out_of_order_queue);
 306		mptcp_drop(sk, skb1);
 307		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
 308	}
 309	/* If there is no skb after us, we are the last_skb ! */
 310	if (!skb1)
 311		msk->ooo_last_skb = skb;
 312
 313end:
 314	skb_condense(skb);
 315	mptcp_set_owner_r(skb, sk);
 316}
 317
 318static bool mptcp_rmem_schedule(struct sock *sk, struct sock *ssk, int size)
 319{
 320	struct mptcp_sock *msk = mptcp_sk(sk);
 321	int amt, amount;
 322
 323	if (size <= msk->rmem_fwd_alloc)
 324		return true;
 325
 326	size -= msk->rmem_fwd_alloc;
 327	amt = sk_mem_pages(size);
 328	amount = amt << PAGE_SHIFT;
 329	if (!__sk_mem_raise_allocated(sk, size, amt, SK_MEM_RECV))
 330		return false;
 331
 332	msk->rmem_fwd_alloc += amount;
 333	return true;
 334}
 335
 336static bool __mptcp_move_skb(struct mptcp_sock *msk, struct sock *ssk,
 337			     struct sk_buff *skb, unsigned int offset,
 338			     size_t copy_len)
 339{
 340	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
 341	struct sock *sk = (struct sock *)msk;
 342	struct sk_buff *tail;
 343	bool has_rxtstamp;
 344
 345	__skb_unlink(skb, &ssk->sk_receive_queue);
 346
 347	skb_ext_reset(skb);
 348	skb_orphan(skb);
 349
 350	/* try to fetch required memory from subflow */
 351	if (!mptcp_rmem_schedule(sk, ssk, skb->truesize))
 352		goto drop;
 353
 354	has_rxtstamp = TCP_SKB_CB(skb)->has_rxtstamp;
 355
 356	/* the skb map_seq accounts for the skb offset:
 357	 * mptcp_subflow_get_mapped_dsn() is based on the current tp->copied_seq
 358	 * value
 359	 */
 360	MPTCP_SKB_CB(skb)->map_seq = mptcp_subflow_get_mapped_dsn(subflow);
 361	MPTCP_SKB_CB(skb)->end_seq = MPTCP_SKB_CB(skb)->map_seq + copy_len;
 362	MPTCP_SKB_CB(skb)->offset = offset;
 363	MPTCP_SKB_CB(skb)->has_rxtstamp = has_rxtstamp;
 364
 365	if (MPTCP_SKB_CB(skb)->map_seq == msk->ack_seq) {
 366		/* in sequence */
 367		WRITE_ONCE(msk->ack_seq, msk->ack_seq + copy_len);
 368		tail = skb_peek_tail(&sk->sk_receive_queue);
 369		if (tail && mptcp_try_coalesce(sk, tail, skb))
 370			return true;
 371
 372		mptcp_set_owner_r(skb, sk);
 373		__skb_queue_tail(&sk->sk_receive_queue, skb);
 374		return true;
 375	} else if (after64(MPTCP_SKB_CB(skb)->map_seq, msk->ack_seq)) {
 376		mptcp_data_queue_ofo(msk, skb);
 377		return false;
 378	}
 379
 380	/* old data, keep it simple and drop the whole pkt, sender
 381	 * will retransmit as needed, if needed.
 382	 */
 383	MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
 384drop:
 385	mptcp_drop(sk, skb);
 386	return false;
 387}
 388
 389static void mptcp_stop_timer(struct sock *sk)
 390{
 391	struct inet_connection_sock *icsk = inet_csk(sk);
 392
 393	sk_stop_timer(sk, &icsk->icsk_retransmit_timer);
 394	mptcp_sk(sk)->timer_ival = 0;
 395}
 396
 397static void mptcp_close_wake_up(struct sock *sk)
 398{
 399	if (sock_flag(sk, SOCK_DEAD))
 400		return;
 401
 402	sk->sk_state_change(sk);
 403	if (sk->sk_shutdown == SHUTDOWN_MASK ||
 404	    sk->sk_state == TCP_CLOSE)
 405		sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
 406	else
 407		sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
 408}
 409
 410static bool mptcp_pending_data_fin_ack(struct sock *sk)
 411{
 412	struct mptcp_sock *msk = mptcp_sk(sk);
 413
 414	return !__mptcp_check_fallback(msk) &&
 415	       ((1 << sk->sk_state) &
 416		(TCPF_FIN_WAIT1 | TCPF_CLOSING | TCPF_LAST_ACK)) &&
 417	       msk->write_seq == READ_ONCE(msk->snd_una);
 418}
 419
 420static void mptcp_check_data_fin_ack(struct sock *sk)
 421{
 422	struct mptcp_sock *msk = mptcp_sk(sk);
 423
 424	/* Look for an acknowledged DATA_FIN */
 425	if (mptcp_pending_data_fin_ack(sk)) {
 426		WRITE_ONCE(msk->snd_data_fin_enable, 0);
 427
 428		switch (sk->sk_state) {
 429		case TCP_FIN_WAIT1:
 430			inet_sk_state_store(sk, TCP_FIN_WAIT2);
 431			break;
 432		case TCP_CLOSING:
 433		case TCP_LAST_ACK:
 434			inet_sk_state_store(sk, TCP_CLOSE);
 435			break;
 436		}
 437
 438		mptcp_close_wake_up(sk);
 439	}
 440}
 441
 442static bool mptcp_pending_data_fin(struct sock *sk, u64 *seq)
 443{
 444	struct mptcp_sock *msk = mptcp_sk(sk);
 445
 446	if (READ_ONCE(msk->rcv_data_fin) &&
 447	    ((1 << sk->sk_state) &
 448	     (TCPF_ESTABLISHED | TCPF_FIN_WAIT1 | TCPF_FIN_WAIT2))) {
 449		u64 rcv_data_fin_seq = READ_ONCE(msk->rcv_data_fin_seq);
 450
 451		if (msk->ack_seq == rcv_data_fin_seq) {
 452			if (seq)
 453				*seq = rcv_data_fin_seq;
 454
 455			return true;
 456		}
 457	}
 458
 459	return false;
 460}
 461
 462static void mptcp_set_datafin_timeout(const struct sock *sk)
 463{
 464	struct inet_connection_sock *icsk = inet_csk(sk);
 465	u32 retransmits;
 466
 467	retransmits = min_t(u32, icsk->icsk_retransmits,
 468			    ilog2(TCP_RTO_MAX / TCP_RTO_MIN));
 469
 470	mptcp_sk(sk)->timer_ival = TCP_RTO_MIN << retransmits;
 471}
 472
 473static void __mptcp_set_timeout(struct sock *sk, long tout)
 474{
 475	mptcp_sk(sk)->timer_ival = tout > 0 ? tout : TCP_RTO_MIN;
 476}
 477
 478static long mptcp_timeout_from_subflow(const struct mptcp_subflow_context *subflow)
 479{
 480	const struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
 481
 482	return inet_csk(ssk)->icsk_pending && !subflow->stale_count ?
 483	       inet_csk(ssk)->icsk_timeout - jiffies : 0;
 484}
 485
 486static void mptcp_set_timeout(struct sock *sk)
 487{
 488	struct mptcp_subflow_context *subflow;
 489	long tout = 0;
 490
 491	mptcp_for_each_subflow(mptcp_sk(sk), subflow)
 492		tout = max(tout, mptcp_timeout_from_subflow(subflow));
 493	__mptcp_set_timeout(sk, tout);
 494}
 495
 496static inline bool tcp_can_send_ack(const struct sock *ssk)
 497{
 498	return !((1 << inet_sk_state_load(ssk)) &
 499	       (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_TIME_WAIT | TCPF_CLOSE | TCPF_LISTEN));
 500}
 501
 502void __mptcp_subflow_send_ack(struct sock *ssk)
 503{
 504	if (tcp_can_send_ack(ssk))
 505		tcp_send_ack(ssk);
 506}
 507
 508static void mptcp_subflow_send_ack(struct sock *ssk)
 509{
 510	bool slow;
 511
 512	slow = lock_sock_fast(ssk);
 513	__mptcp_subflow_send_ack(ssk);
 514	unlock_sock_fast(ssk, slow);
 515}
 516
 517static void mptcp_send_ack(struct mptcp_sock *msk)
 518{
 519	struct mptcp_subflow_context *subflow;
 520
 521	mptcp_for_each_subflow(msk, subflow)
 522		mptcp_subflow_send_ack(mptcp_subflow_tcp_sock(subflow));
 523}
 524
 525static void mptcp_subflow_cleanup_rbuf(struct sock *ssk)
 526{
 527	bool slow;
 528
 529	slow = lock_sock_fast(ssk);
 530	if (tcp_can_send_ack(ssk))
 531		tcp_cleanup_rbuf(ssk, 1);
 532	unlock_sock_fast(ssk, slow);
 533}
 534
 535static bool mptcp_subflow_could_cleanup(const struct sock *ssk, bool rx_empty)
 536{
 537	const struct inet_connection_sock *icsk = inet_csk(ssk);
 538	u8 ack_pending = READ_ONCE(icsk->icsk_ack.pending);
 539	const struct tcp_sock *tp = tcp_sk(ssk);
 540
 541	return (ack_pending & ICSK_ACK_SCHED) &&
 542		((READ_ONCE(tp->rcv_nxt) - READ_ONCE(tp->rcv_wup) >
 543		  READ_ONCE(icsk->icsk_ack.rcv_mss)) ||
 544		 (rx_empty && ack_pending &
 545			      (ICSK_ACK_PUSHED2 | ICSK_ACK_PUSHED)));
 546}
 547
 548static void mptcp_cleanup_rbuf(struct mptcp_sock *msk)
 549{
 550	int old_space = READ_ONCE(msk->old_wspace);
 551	struct mptcp_subflow_context *subflow;
 552	struct sock *sk = (struct sock *)msk;
 553	int space =  __mptcp_space(sk);
 554	bool cleanup, rx_empty;
 555
 556	cleanup = (space > 0) && (space >= (old_space << 1));
 557	rx_empty = !__mptcp_rmem(sk);
 558
 559	mptcp_for_each_subflow(msk, subflow) {
 560		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
 561
 562		if (cleanup || mptcp_subflow_could_cleanup(ssk, rx_empty))
 563			mptcp_subflow_cleanup_rbuf(ssk);
 564	}
 565}
 566
 567static bool mptcp_check_data_fin(struct sock *sk)
 568{
 569	struct mptcp_sock *msk = mptcp_sk(sk);
 570	u64 rcv_data_fin_seq;
 571	bool ret = false;
 572
 573	if (__mptcp_check_fallback(msk))
 574		return ret;
 575
 576	/* Need to ack a DATA_FIN received from a peer while this side
 577	 * of the connection is in ESTABLISHED, FIN_WAIT1, or FIN_WAIT2.
 578	 * msk->rcv_data_fin was set when parsing the incoming options
 579	 * at the subflow level and the msk lock was not held, so this
 580	 * is the first opportunity to act on the DATA_FIN and change
 581	 * the msk state.
 582	 *
 583	 * If we are caught up to the sequence number of the incoming
 584	 * DATA_FIN, send the DATA_ACK now and do state transition.  If
 585	 * not caught up, do nothing and let the recv code send DATA_ACK
 586	 * when catching up.
 587	 */
 588
 589	if (mptcp_pending_data_fin(sk, &rcv_data_fin_seq)) {
 590		WRITE_ONCE(msk->ack_seq, msk->ack_seq + 1);
 591		WRITE_ONCE(msk->rcv_data_fin, 0);
 592
 593		sk->sk_shutdown |= RCV_SHUTDOWN;
 594		smp_mb__before_atomic(); /* SHUTDOWN must be visible first */
 595
 596		switch (sk->sk_state) {
 597		case TCP_ESTABLISHED:
 598			inet_sk_state_store(sk, TCP_CLOSE_WAIT);
 599			break;
 600		case TCP_FIN_WAIT1:
 601			inet_sk_state_store(sk, TCP_CLOSING);
 602			break;
 603		case TCP_FIN_WAIT2:
 604			inet_sk_state_store(sk, TCP_CLOSE);
 605			break;
 606		default:
 607			/* Other states not expected */
 608			WARN_ON_ONCE(1);
 609			break;
 610		}
 611
 612		ret = true;
 613		mptcp_send_ack(msk);
 614		mptcp_close_wake_up(sk);
 615	}
 616	return ret;
 617}
 618
 619static bool __mptcp_move_skbs_from_subflow(struct mptcp_sock *msk,
 620					   struct sock *ssk,
 621					   unsigned int *bytes)
 622{
 623	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
 624	struct sock *sk = (struct sock *)msk;
 625	unsigned int moved = 0;
 626	bool more_data_avail;
 627	struct tcp_sock *tp;
 628	bool done = false;
 629	int sk_rbuf;
 630
 631	sk_rbuf = READ_ONCE(sk->sk_rcvbuf);
 632
 633	if (!(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
 634		int ssk_rbuf = READ_ONCE(ssk->sk_rcvbuf);
 635
 636		if (unlikely(ssk_rbuf > sk_rbuf)) {
 637			WRITE_ONCE(sk->sk_rcvbuf, ssk_rbuf);
 638			sk_rbuf = ssk_rbuf;
 639		}
 640	}
 641
 642	pr_debug("msk=%p ssk=%p", msk, ssk);
 643	tp = tcp_sk(ssk);
 644	do {
 645		u32 map_remaining, offset;
 646		u32 seq = tp->copied_seq;
 647		struct sk_buff *skb;
 648		bool fin;
 649
 650		/* try to move as much data as available */
 651		map_remaining = subflow->map_data_len -
 652				mptcp_subflow_get_map_offset(subflow);
 653
 654		skb = skb_peek(&ssk->sk_receive_queue);
 655		if (!skb) {
 656			/* With racing move_skbs_to_msk() and __mptcp_move_skbs(),
 657			 * a different CPU can have already processed the pending
 658			 * data, stop here or we can enter an infinite loop
 659			 */
 660			if (!moved)
 661				done = true;
 662			break;
 663		}
 664
 665		if (__mptcp_check_fallback(msk)) {
 666			/* Under fallback skbs have no MPTCP extension and TCP could
 667			 * collapse them between the dummy map creation and the
 668			 * current dequeue. Be sure to adjust the map size.
 669			 */
 670			map_remaining = skb->len;
 671			subflow->map_data_len = skb->len;
 672		}
 673
 674		offset = seq - TCP_SKB_CB(skb)->seq;
 675		fin = TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN;
 676		if (fin) {
 677			done = true;
 678			seq++;
 679		}
 680
 681		if (offset < skb->len) {
 682			size_t len = skb->len - offset;
 683
 684			if (tp->urg_data)
 685				done = true;
 686
 687			if (__mptcp_move_skb(msk, ssk, skb, offset, len))
 688				moved += len;
 689			seq += len;
 690
 691			if (WARN_ON_ONCE(map_remaining < len))
 692				break;
 693		} else {
 694			WARN_ON_ONCE(!fin);
 695			sk_eat_skb(ssk, skb);
 696			done = true;
 697		}
 698
 699		WRITE_ONCE(tp->copied_seq, seq);
 700		more_data_avail = mptcp_subflow_data_available(ssk);
 701
 702		if (atomic_read(&sk->sk_rmem_alloc) > sk_rbuf) {
 703			done = true;
 704			break;
 705		}
 706	} while (more_data_avail);
 707
 708	*bytes += moved;
 709	return done;
 710}
 711
 712static bool __mptcp_ofo_queue(struct mptcp_sock *msk)
 713{
 714	struct sock *sk = (struct sock *)msk;
 715	struct sk_buff *skb, *tail;
 716	bool moved = false;
 717	struct rb_node *p;
 718	u64 end_seq;
 719
 720	p = rb_first(&msk->out_of_order_queue);
 721	pr_debug("msk=%p empty=%d", msk, RB_EMPTY_ROOT(&msk->out_of_order_queue));
 722	while (p) {
 723		skb = rb_to_skb(p);
 724		if (after64(MPTCP_SKB_CB(skb)->map_seq, msk->ack_seq))
 725			break;
 726
 727		p = rb_next(p);
 728		rb_erase(&skb->rbnode, &msk->out_of_order_queue);
 729
 730		if (unlikely(!after64(MPTCP_SKB_CB(skb)->end_seq,
 731				      msk->ack_seq))) {
 732			mptcp_drop(sk, skb);
 733			MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
 734			continue;
 735		}
 736
 737		end_seq = MPTCP_SKB_CB(skb)->end_seq;
 738		tail = skb_peek_tail(&sk->sk_receive_queue);
 739		if (!tail || !mptcp_ooo_try_coalesce(msk, tail, skb)) {
 740			int delta = msk->ack_seq - MPTCP_SKB_CB(skb)->map_seq;
 741
 742			/* skip overlapping data, if any */
 743			pr_debug("uncoalesced seq=%llx ack seq=%llx delta=%d",
 744				 MPTCP_SKB_CB(skb)->map_seq, msk->ack_seq,
 745				 delta);
 746			MPTCP_SKB_CB(skb)->offset += delta;
 747			MPTCP_SKB_CB(skb)->map_seq += delta;
 748			__skb_queue_tail(&sk->sk_receive_queue, skb);
 749		}
 750		msk->ack_seq = end_seq;
 751		moved = true;
 752	}
 753	return moved;
 754}
 755
 756/* In most cases we will be able to lock the mptcp socket.  If its already
 757 * owned, we need to defer to the work queue to avoid ABBA deadlock.
 758 */
 759static bool move_skbs_to_msk(struct mptcp_sock *msk, struct sock *ssk)
 760{
 761	struct sock *sk = (struct sock *)msk;
 762	unsigned int moved = 0;
 763
 764	__mptcp_move_skbs_from_subflow(msk, ssk, &moved);
 765	__mptcp_ofo_queue(msk);
 766	if (unlikely(ssk->sk_err)) {
 767		if (!sock_owned_by_user(sk))
 768			__mptcp_error_report(sk);
 769		else
 770			__set_bit(MPTCP_ERROR_REPORT,  &msk->cb_flags);
 771	}
 772
 773	/* If the moves have caught up with the DATA_FIN sequence number
 774	 * it's time to ack the DATA_FIN and change socket state, but
 775	 * this is not a good place to change state. Let the workqueue
 776	 * do it.
 777	 */
 778	if (mptcp_pending_data_fin(sk, NULL))
 779		mptcp_schedule_work(sk);
 780	return moved > 0;
 781}
 782
 783void mptcp_data_ready(struct sock *sk, struct sock *ssk)
 784{
 785	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
 786	struct mptcp_sock *msk = mptcp_sk(sk);
 787	int sk_rbuf, ssk_rbuf;
 788
 789	/* The peer can send data while we are shutting down this
 790	 * subflow at msk destruction time, but we must avoid enqueuing
 791	 * more data to the msk receive queue
 792	 */
 793	if (unlikely(subflow->disposable))
 794		return;
 795
 796	ssk_rbuf = READ_ONCE(ssk->sk_rcvbuf);
 797	sk_rbuf = READ_ONCE(sk->sk_rcvbuf);
 798	if (unlikely(ssk_rbuf > sk_rbuf))
 799		sk_rbuf = ssk_rbuf;
 800
 801	/* over limit? can't append more skbs to msk, Also, no need to wake-up*/
 802	if (__mptcp_rmem(sk) > sk_rbuf) {
 803		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_RCVPRUNED);
 804		return;
 805	}
 806
 807	/* Wake-up the reader only for in-sequence data */
 808	mptcp_data_lock(sk);
 809	if (move_skbs_to_msk(msk, ssk))
 810		sk->sk_data_ready(sk);
 811
 812	mptcp_data_unlock(sk);
 813}
 814
 815static bool __mptcp_finish_join(struct mptcp_sock *msk, struct sock *ssk)
 816{
 817	struct sock *sk = (struct sock *)msk;
 818
 819	if (sk->sk_state != TCP_ESTABLISHED)
 820		return false;
 821
 822	/* attach to msk socket only after we are sure we will deal with it
 823	 * at close time
 824	 */
 825	if (sk->sk_socket && !ssk->sk_socket)
 826		mptcp_sock_graft(ssk, sk->sk_socket);
 827
 828	mptcp_propagate_sndbuf((struct sock *)msk, ssk);
 829	mptcp_sockopt_sync_locked(msk, ssk);
 830	return true;
 831}
 832
 833static void __mptcp_flush_join_list(struct sock *sk)
 834{
 835	struct mptcp_subflow_context *tmp, *subflow;
 836	struct mptcp_sock *msk = mptcp_sk(sk);
 837
 838	list_for_each_entry_safe(subflow, tmp, &msk->join_list, node) {
 839		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
 840		bool slow = lock_sock_fast(ssk);
 841
 842		list_move_tail(&subflow->node, &msk->conn_list);
 843		if (!__mptcp_finish_join(msk, ssk))
 844			mptcp_subflow_reset(ssk);
 845		unlock_sock_fast(ssk, slow);
 846	}
 847}
 848
 849static bool mptcp_timer_pending(struct sock *sk)
 850{
 851	return timer_pending(&inet_csk(sk)->icsk_retransmit_timer);
 852}
 853
 854static void mptcp_reset_timer(struct sock *sk)
 855{
 856	struct inet_connection_sock *icsk = inet_csk(sk);
 857	unsigned long tout;
 858
 859	/* prevent rescheduling on close */
 860	if (unlikely(inet_sk_state_load(sk) == TCP_CLOSE))
 861		return;
 862
 863	tout = mptcp_sk(sk)->timer_ival;
 864	sk_reset_timer(sk, &icsk->icsk_retransmit_timer, jiffies + tout);
 865}
 866
 867bool mptcp_schedule_work(struct sock *sk)
 868{
 869	if (inet_sk_state_load(sk) != TCP_CLOSE &&
 870	    schedule_work(&mptcp_sk(sk)->work)) {
 871		/* each subflow already holds a reference to the sk, and the
 872		 * workqueue is invoked by a subflow, so sk can't go away here.
 873		 */
 874		sock_hold(sk);
 875		return true;
 876	}
 877	return false;
 878}
 879
 880void mptcp_subflow_eof(struct sock *sk)
 881{
 882	if (!test_and_set_bit(MPTCP_WORK_EOF, &mptcp_sk(sk)->flags))
 883		mptcp_schedule_work(sk);
 884}
 885
 886static void mptcp_check_for_eof(struct mptcp_sock *msk)
 887{
 888	struct mptcp_subflow_context *subflow;
 889	struct sock *sk = (struct sock *)msk;
 890	int receivers = 0;
 891
 892	mptcp_for_each_subflow(msk, subflow)
 893		receivers += !subflow->rx_eof;
 894	if (receivers)
 895		return;
 896
 897	if (!(sk->sk_shutdown & RCV_SHUTDOWN)) {
 898		/* hopefully temporary hack: propagate shutdown status
 899		 * to msk, when all subflows agree on it
 900		 */
 901		sk->sk_shutdown |= RCV_SHUTDOWN;
 902
 903		smp_mb__before_atomic(); /* SHUTDOWN must be visible first */
 904		sk->sk_data_ready(sk);
 905	}
 906
 907	switch (sk->sk_state) {
 908	case TCP_ESTABLISHED:
 909		inet_sk_state_store(sk, TCP_CLOSE_WAIT);
 910		break;
 911	case TCP_FIN_WAIT1:
 912		inet_sk_state_store(sk, TCP_CLOSING);
 913		break;
 914	case TCP_FIN_WAIT2:
 915		inet_sk_state_store(sk, TCP_CLOSE);
 916		break;
 917	default:
 918		return;
 919	}
 920	mptcp_close_wake_up(sk);
 921}
 922
 923static struct sock *mptcp_subflow_recv_lookup(const struct mptcp_sock *msk)
 924{
 925	struct mptcp_subflow_context *subflow;
 926	struct sock *sk = (struct sock *)msk;
 927
 928	sock_owned_by_me(sk);
 929
 930	mptcp_for_each_subflow(msk, subflow) {
 931		if (READ_ONCE(subflow->data_avail))
 932			return mptcp_subflow_tcp_sock(subflow);
 933	}
 934
 935	return NULL;
 936}
 937
 938static bool mptcp_skb_can_collapse_to(u64 write_seq,
 939				      const struct sk_buff *skb,
 940				      const struct mptcp_ext *mpext)
 941{
 942	if (!tcp_skb_can_collapse_to(skb))
 943		return false;
 944
 945	/* can collapse only if MPTCP level sequence is in order and this
 946	 * mapping has not been xmitted yet
 947	 */
 948	return mpext && mpext->data_seq + mpext->data_len == write_seq &&
 949	       !mpext->frozen;
 950}
 951
 952/* we can append data to the given data frag if:
 953 * - there is space available in the backing page_frag
 954 * - the data frag tail matches the current page_frag free offset
 955 * - the data frag end sequence number matches the current write seq
 956 */
 957static bool mptcp_frag_can_collapse_to(const struct mptcp_sock *msk,
 958				       const struct page_frag *pfrag,
 959				       const struct mptcp_data_frag *df)
 960{
 961	return df && pfrag->page == df->page &&
 962		pfrag->size - pfrag->offset > 0 &&
 963		pfrag->offset == (df->offset + df->data_len) &&
 964		df->data_seq + df->data_len == msk->write_seq;
 965}
 966
 967static void dfrag_uncharge(struct sock *sk, int len)
 968{
 969	sk_mem_uncharge(sk, len);
 970	sk_wmem_queued_add(sk, -len);
 971}
 972
 973static void dfrag_clear(struct sock *sk, struct mptcp_data_frag *dfrag)
 974{
 975	int len = dfrag->data_len + dfrag->overhead;
 976
 977	list_del(&dfrag->list);
 978	dfrag_uncharge(sk, len);
 979	put_page(dfrag->page);
 980}
 981
 982static void __mptcp_clean_una(struct sock *sk)
 983{
 984	struct mptcp_sock *msk = mptcp_sk(sk);
 985	struct mptcp_data_frag *dtmp, *dfrag;
 986	u64 snd_una;
 987
 988	/* on fallback we just need to ignore snd_una, as this is really
 989	 * plain TCP
 990	 */
 991	if (__mptcp_check_fallback(msk))
 992		msk->snd_una = READ_ONCE(msk->snd_nxt);
 993
 994	snd_una = msk->snd_una;
 995	list_for_each_entry_safe(dfrag, dtmp, &msk->rtx_queue, list) {
 996		if (after64(dfrag->data_seq + dfrag->data_len, snd_una))
 997			break;
 998
 999		if (unlikely(dfrag == msk->first_pending)) {
1000			/* in recovery mode can see ack after the current snd head */
1001			if (WARN_ON_ONCE(!msk->recovery))
1002				break;
1003
1004			WRITE_ONCE(msk->first_pending, mptcp_send_next(sk));
1005		}
1006
1007		dfrag_clear(sk, dfrag);
1008	}
1009
1010	dfrag = mptcp_rtx_head(sk);
1011	if (dfrag && after64(snd_una, dfrag->data_seq)) {
1012		u64 delta = snd_una - dfrag->data_seq;
1013
1014		/* prevent wrap around in recovery mode */
1015		if (unlikely(delta > dfrag->already_sent)) {
1016			if (WARN_ON_ONCE(!msk->recovery))
1017				goto out;
1018			if (WARN_ON_ONCE(delta > dfrag->data_len))
1019				goto out;
1020			dfrag->already_sent += delta - dfrag->already_sent;
1021		}
1022
1023		dfrag->data_seq += delta;
1024		dfrag->offset += delta;
1025		dfrag->data_len -= delta;
1026		dfrag->already_sent -= delta;
1027
1028		dfrag_uncharge(sk, delta);
1029	}
1030
1031	/* all retransmitted data acked, recovery completed */
1032	if (unlikely(msk->recovery) && after64(msk->snd_una, msk->recovery_snd_nxt))
1033		msk->recovery = false;
1034
1035out:
1036	if (snd_una == READ_ONCE(msk->snd_nxt) &&
1037	    snd_una == READ_ONCE(msk->write_seq)) {
1038		if (mptcp_timer_pending(sk) && !mptcp_data_fin_enabled(msk))
1039			mptcp_stop_timer(sk);
1040	} else {
1041		mptcp_reset_timer(sk);
1042	}
1043}
1044
1045static void __mptcp_clean_una_wakeup(struct sock *sk)
1046{
1047	lockdep_assert_held_once(&sk->sk_lock.slock);
1048
1049	__mptcp_clean_una(sk);
1050	mptcp_write_space(sk);
1051}
1052
1053static void mptcp_clean_una_wakeup(struct sock *sk)
1054{
1055	mptcp_data_lock(sk);
1056	__mptcp_clean_una_wakeup(sk);
1057	mptcp_data_unlock(sk);
1058}
1059
1060static void mptcp_enter_memory_pressure(struct sock *sk)
1061{
1062	struct mptcp_subflow_context *subflow;
1063	struct mptcp_sock *msk = mptcp_sk(sk);
1064	bool first = true;
1065
1066	sk_stream_moderate_sndbuf(sk);
1067	mptcp_for_each_subflow(msk, subflow) {
1068		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
1069
1070		if (first)
1071			tcp_enter_memory_pressure(ssk);
1072		sk_stream_moderate_sndbuf(ssk);
1073		first = false;
1074	}
1075}
1076
1077/* ensure we get enough memory for the frag hdr, beyond some minimal amount of
1078 * data
1079 */
1080static bool mptcp_page_frag_refill(struct sock *sk, struct page_frag *pfrag)
1081{
1082	if (likely(skb_page_frag_refill(32U + sizeof(struct mptcp_data_frag),
1083					pfrag, sk->sk_allocation)))
1084		return true;
1085
1086	mptcp_enter_memory_pressure(sk);
1087	return false;
1088}
1089
1090static struct mptcp_data_frag *
1091mptcp_carve_data_frag(const struct mptcp_sock *msk, struct page_frag *pfrag,
1092		      int orig_offset)
1093{
1094	int offset = ALIGN(orig_offset, sizeof(long));
1095	struct mptcp_data_frag *dfrag;
1096
1097	dfrag = (struct mptcp_data_frag *)(page_to_virt(pfrag->page) + offset);
1098	dfrag->data_len = 0;
1099	dfrag->data_seq = msk->write_seq;
1100	dfrag->overhead = offset - orig_offset + sizeof(struct mptcp_data_frag);
1101	dfrag->offset = offset + sizeof(struct mptcp_data_frag);
1102	dfrag->already_sent = 0;
1103	dfrag->page = pfrag->page;
1104
1105	return dfrag;
1106}
1107
1108struct mptcp_sendmsg_info {
1109	int mss_now;
1110	int size_goal;
1111	u16 limit;
1112	u16 sent;
1113	unsigned int flags;
1114	bool data_lock_held;
1115};
1116
1117static int mptcp_check_allowed_size(const struct mptcp_sock *msk, struct sock *ssk,
1118				    u64 data_seq, int avail_size)
1119{
1120	u64 window_end = mptcp_wnd_end(msk);
1121	u64 mptcp_snd_wnd;
1122
1123	if (__mptcp_check_fallback(msk))
1124		return avail_size;
1125
1126	mptcp_snd_wnd = window_end - data_seq;
1127	avail_size = min_t(unsigned int, mptcp_snd_wnd, avail_size);
1128
1129	if (unlikely(tcp_sk(ssk)->snd_wnd < mptcp_snd_wnd)) {
1130		tcp_sk(ssk)->snd_wnd = min_t(u64, U32_MAX, mptcp_snd_wnd);
1131		MPTCP_INC_STATS(sock_net(ssk), MPTCP_MIB_SNDWNDSHARED);
1132	}
1133
1134	return avail_size;
1135}
1136
1137static bool __mptcp_add_ext(struct sk_buff *skb, gfp_t gfp)
1138{
1139	struct skb_ext *mpext = __skb_ext_alloc(gfp);
1140
1141	if (!mpext)
1142		return false;
1143	__skb_ext_set(skb, SKB_EXT_MPTCP, mpext);
1144	return true;
1145}
1146
1147static struct sk_buff *__mptcp_do_alloc_tx_skb(struct sock *sk, gfp_t gfp)
1148{
1149	struct sk_buff *skb;
1150
1151	skb = alloc_skb_fclone(MAX_TCP_HEADER, gfp);
1152	if (likely(skb)) {
1153		if (likely(__mptcp_add_ext(skb, gfp))) {
1154			skb_reserve(skb, MAX_TCP_HEADER);
1155			skb->ip_summed = CHECKSUM_PARTIAL;
1156			INIT_LIST_HEAD(&skb->tcp_tsorted_anchor);
1157			return skb;
1158		}
1159		__kfree_skb(skb);
1160	} else {
1161		mptcp_enter_memory_pressure(sk);
1162	}
1163	return NULL;
1164}
1165
1166static struct sk_buff *__mptcp_alloc_tx_skb(struct sock *sk, struct sock *ssk, gfp_t gfp)
1167{
1168	struct sk_buff *skb;
1169
1170	skb = __mptcp_do_alloc_tx_skb(sk, gfp);
1171	if (!skb)
1172		return NULL;
1173
1174	if (likely(sk_wmem_schedule(ssk, skb->truesize))) {
1175		tcp_skb_entail(ssk, skb);
1176		return skb;
1177	}
1178	tcp_skb_tsorted_anchor_cleanup(skb);
1179	kfree_skb(skb);
1180	return NULL;
1181}
1182
1183static struct sk_buff *mptcp_alloc_tx_skb(struct sock *sk, struct sock *ssk, bool data_lock_held)
1184{
1185	gfp_t gfp = data_lock_held ? GFP_ATOMIC : sk->sk_allocation;
1186
1187	return __mptcp_alloc_tx_skb(sk, ssk, gfp);
1188}
1189
1190/* note: this always recompute the csum on the whole skb, even
1191 * if we just appended a single frag. More status info needed
1192 */
1193static void mptcp_update_data_checksum(struct sk_buff *skb, int added)
1194{
1195	struct mptcp_ext *mpext = mptcp_get_ext(skb);
1196	__wsum csum = ~csum_unfold(mpext->csum);
1197	int offset = skb->len - added;
1198
1199	mpext->csum = csum_fold(csum_block_add(csum, skb_checksum(skb, offset, added, 0), offset));
1200}
1201
1202static void mptcp_update_infinite_map(struct mptcp_sock *msk,
1203				      struct sock *ssk,
1204				      struct mptcp_ext *mpext)
1205{
1206	if (!mpext)
1207		return;
1208
1209	mpext->infinite_map = 1;
1210	mpext->data_len = 0;
1211
1212	MPTCP_INC_STATS(sock_net(ssk), MPTCP_MIB_INFINITEMAPTX);
1213	mptcp_subflow_ctx(ssk)->send_infinite_map = 0;
1214	pr_fallback(msk);
1215	mptcp_do_fallback(ssk);
1216}
1217
1218static int mptcp_sendmsg_frag(struct sock *sk, struct sock *ssk,
1219			      struct mptcp_data_frag *dfrag,
1220			      struct mptcp_sendmsg_info *info)
1221{
1222	u64 data_seq = dfrag->data_seq + info->sent;
1223	int offset = dfrag->offset + info->sent;
1224	struct mptcp_sock *msk = mptcp_sk(sk);
1225	bool zero_window_probe = false;
1226	struct mptcp_ext *mpext = NULL;
1227	bool can_coalesce = false;
1228	bool reuse_skb = true;
1229	struct sk_buff *skb;
1230	size_t copy;
1231	int i;
1232
1233	pr_debug("msk=%p ssk=%p sending dfrag at seq=%llu len=%u already sent=%u",
1234		 msk, ssk, dfrag->data_seq, dfrag->data_len, info->sent);
1235
1236	if (WARN_ON_ONCE(info->sent > info->limit ||
1237			 info->limit > dfrag->data_len))
1238		return 0;
1239
1240	if (unlikely(!__tcp_can_send(ssk)))
1241		return -EAGAIN;
1242
1243	/* compute send limit */
1244	info->mss_now = tcp_send_mss(ssk, &info->size_goal, info->flags);
1245	copy = info->size_goal;
1246
1247	skb = tcp_write_queue_tail(ssk);
1248	if (skb && copy > skb->len) {
1249		/* Limit the write to the size available in the
1250		 * current skb, if any, so that we create at most a new skb.
1251		 * Explicitly tells TCP internals to avoid collapsing on later
1252		 * queue management operation, to avoid breaking the ext <->
1253		 * SSN association set here
1254		 */
1255		mpext = skb_ext_find(skb, SKB_EXT_MPTCP);
1256		if (!mptcp_skb_can_collapse_to(data_seq, skb, mpext)) {
1257			TCP_SKB_CB(skb)->eor = 1;
1258			goto alloc_skb;
1259		}
1260
1261		i = skb_shinfo(skb)->nr_frags;
1262		can_coalesce = skb_can_coalesce(skb, i, dfrag->page, offset);
1263		if (!can_coalesce && i >= READ_ONCE(sysctl_max_skb_frags)) {
1264			tcp_mark_push(tcp_sk(ssk), skb);
1265			goto alloc_skb;
1266		}
1267
1268		copy -= skb->len;
1269	} else {
1270alloc_skb:
1271		skb = mptcp_alloc_tx_skb(sk, ssk, info->data_lock_held);
1272		if (!skb)
1273			return -ENOMEM;
1274
1275		i = skb_shinfo(skb)->nr_frags;
1276		reuse_skb = false;
1277		mpext = skb_ext_find(skb, SKB_EXT_MPTCP);
1278	}
1279
1280	/* Zero window and all data acked? Probe. */
1281	copy = mptcp_check_allowed_size(msk, ssk, data_seq, copy);
1282	if (copy == 0) {
1283		u64 snd_una = READ_ONCE(msk->snd_una);
1284
1285		if (snd_una != msk->snd_nxt) {
1286			tcp_remove_empty_skb(ssk);
1287			return 0;
1288		}
1289
1290		zero_window_probe = true;
1291		data_seq = snd_una - 1;
1292		copy = 1;
1293
1294		/* all mptcp-level data is acked, no skbs should be present into the
1295		 * ssk write queue
1296		 */
1297		WARN_ON_ONCE(reuse_skb);
1298	}
1299
1300	copy = min_t(size_t, copy, info->limit - info->sent);
1301	if (!sk_wmem_schedule(ssk, copy)) {
1302		tcp_remove_empty_skb(ssk);
1303		return -ENOMEM;
1304	}
1305
1306	if (can_coalesce) {
1307		skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
1308	} else {
1309		get_page(dfrag->page);
1310		skb_fill_page_desc(skb, i, dfrag->page, offset, copy);
1311	}
1312
1313	skb->len += copy;
1314	skb->data_len += copy;
1315	skb->truesize += copy;
1316	sk_wmem_queued_add(ssk, copy);
1317	sk_mem_charge(ssk, copy);
1318	WRITE_ONCE(tcp_sk(ssk)->write_seq, tcp_sk(ssk)->write_seq + copy);
1319	TCP_SKB_CB(skb)->end_seq += copy;
1320	tcp_skb_pcount_set(skb, 0);
1321
1322	/* on skb reuse we just need to update the DSS len */
1323	if (reuse_skb) {
1324		TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
1325		mpext->data_len += copy;
1326		WARN_ON_ONCE(zero_window_probe);
1327		goto out;
1328	}
1329
1330	memset(mpext, 0, sizeof(*mpext));
1331	mpext->data_seq = data_seq;
1332	mpext->subflow_seq = mptcp_subflow_ctx(ssk)->rel_write_seq;
1333	mpext->data_len = copy;
1334	mpext->use_map = 1;
1335	mpext->dsn64 = 1;
1336
1337	pr_debug("data_seq=%llu subflow_seq=%u data_len=%u dsn64=%d",
1338		 mpext->data_seq, mpext->subflow_seq, mpext->data_len,
1339		 mpext->dsn64);
1340
1341	if (zero_window_probe) {
1342		mptcp_subflow_ctx(ssk)->rel_write_seq += copy;
1343		mpext->frozen = 1;
1344		if (READ_ONCE(msk->csum_enabled))
1345			mptcp_update_data_checksum(skb, copy);
1346		tcp_push_pending_frames(ssk);
1347		return 0;
1348	}
1349out:
1350	if (READ_ONCE(msk->csum_enabled))
1351		mptcp_update_data_checksum(skb, copy);
1352	if (mptcp_subflow_ctx(ssk)->send_infinite_map)
1353		mptcp_update_infinite_map(msk, ssk, mpext);
1354	trace_mptcp_sendmsg_frag(mpext);
1355	mptcp_subflow_ctx(ssk)->rel_write_seq += copy;
1356	return copy;
1357}
1358
1359#define MPTCP_SEND_BURST_SIZE		((1 << 16) - \
1360					 sizeof(struct tcphdr) - \
1361					 MAX_TCP_OPTION_SPACE - \
1362					 sizeof(struct ipv6hdr) - \
1363					 sizeof(struct frag_hdr))
1364
1365struct subflow_send_info {
1366	struct sock *ssk;
1367	u64 linger_time;
1368};
1369
1370void mptcp_subflow_set_active(struct mptcp_subflow_context *subflow)
1371{
1372	if (!subflow->stale)
1373		return;
1374
1375	subflow->stale = 0;
1376	MPTCP_INC_STATS(sock_net(mptcp_subflow_tcp_sock(subflow)), MPTCP_MIB_SUBFLOWRECOVER);
1377}
1378
1379bool mptcp_subflow_active(struct mptcp_subflow_context *subflow)
1380{
1381	if (unlikely(subflow->stale)) {
1382		u32 rcv_tstamp = READ_ONCE(tcp_sk(mptcp_subflow_tcp_sock(subflow))->rcv_tstamp);
1383
1384		if (subflow->stale_rcv_tstamp == rcv_tstamp)
1385			return false;
1386
1387		mptcp_subflow_set_active(subflow);
1388	}
1389	return __mptcp_subflow_active(subflow);
1390}
1391
1392#define SSK_MODE_ACTIVE	0
1393#define SSK_MODE_BACKUP	1
1394#define SSK_MODE_MAX	2
1395
1396/* implement the mptcp packet scheduler;
1397 * returns the subflow that will transmit the next DSS
1398 * additionally updates the rtx timeout
1399 */
1400static struct sock *mptcp_subflow_get_send(struct mptcp_sock *msk)
1401{
1402	struct subflow_send_info send_info[SSK_MODE_MAX];
1403	struct mptcp_subflow_context *subflow;
1404	struct sock *sk = (struct sock *)msk;
1405	u32 pace, burst, wmem;
1406	int i, nr_active = 0;
1407	struct sock *ssk;
1408	u64 linger_time;
1409	long tout = 0;
1410
1411	sock_owned_by_me(sk);
1412
1413	if (__mptcp_check_fallback(msk)) {
1414		if (!msk->first)
1415			return NULL;
1416		return __tcp_can_send(msk->first) &&
1417		       sk_stream_memory_free(msk->first) ? msk->first : NULL;
1418	}
1419
1420	/* re-use last subflow, if the burst allow that */
1421	if (msk->last_snd && msk->snd_burst > 0 &&
1422	    sk_stream_memory_free(msk->last_snd) &&
1423	    mptcp_subflow_active(mptcp_subflow_ctx(msk->last_snd))) {
1424		mptcp_set_timeout(sk);
1425		return msk->last_snd;
1426	}
1427
1428	/* pick the subflow with the lower wmem/wspace ratio */
1429	for (i = 0; i < SSK_MODE_MAX; ++i) {
1430		send_info[i].ssk = NULL;
1431		send_info[i].linger_time = -1;
1432	}
1433
1434	mptcp_for_each_subflow(msk, subflow) {
1435		trace_mptcp_subflow_get_send(subflow);
1436		ssk =  mptcp_subflow_tcp_sock(subflow);
1437		if (!mptcp_subflow_active(subflow))
1438			continue;
1439
1440		tout = max(tout, mptcp_timeout_from_subflow(subflow));
1441		nr_active += !subflow->backup;
1442		pace = subflow->avg_pacing_rate;
1443		if (unlikely(!pace)) {
1444			/* init pacing rate from socket */
1445			subflow->avg_pacing_rate = READ_ONCE(ssk->sk_pacing_rate);
1446			pace = subflow->avg_pacing_rate;
1447			if (!pace)
1448				continue;
1449		}
1450
1451		linger_time = div_u64((u64)READ_ONCE(ssk->sk_wmem_queued) << 32, pace);
1452		if (linger_time < send_info[subflow->backup].linger_time) {
1453			send_info[subflow->backup].ssk = ssk;
1454			send_info[subflow->backup].linger_time = linger_time;
1455		}
1456	}
1457	__mptcp_set_timeout(sk, tout);
1458
1459	/* pick the best backup if no other subflow is active */
1460	if (!nr_active)
1461		send_info[SSK_MODE_ACTIVE].ssk = send_info[SSK_MODE_BACKUP].ssk;
1462
1463	/* According to the blest algorithm, to avoid HoL blocking for the
1464	 * faster flow, we need to:
1465	 * - estimate the faster flow linger time
1466	 * - use the above to estimate the amount of byte transferred
1467	 *   by the faster flow
1468	 * - check that the amount of queued data is greter than the above,
1469	 *   otherwise do not use the picked, slower, subflow
1470	 * We select the subflow with the shorter estimated time to flush
1471	 * the queued mem, which basically ensure the above. We just need
1472	 * to check that subflow has a non empty cwin.
1473	 */
1474	ssk = send_info[SSK_MODE_ACTIVE].ssk;
1475	if (!ssk || !sk_stream_memory_free(ssk))
1476		return NULL;
1477
1478	burst = min_t(int, MPTCP_SEND_BURST_SIZE, mptcp_wnd_end(msk) - msk->snd_nxt);
1479	wmem = READ_ONCE(ssk->sk_wmem_queued);
1480	if (!burst) {
1481		msk->last_snd = NULL;
1482		return ssk;
1483	}
1484
1485	subflow = mptcp_subflow_ctx(ssk);
1486	subflow->avg_pacing_rate = div_u64((u64)subflow->avg_pacing_rate * wmem +
1487					   READ_ONCE(ssk->sk_pacing_rate) * burst,
1488					   burst + wmem);
1489	msk->last_snd = ssk;
1490	msk->snd_burst = burst;
1491	return ssk;
1492}
1493
1494static void mptcp_push_release(struct sock *ssk, struct mptcp_sendmsg_info *info)
1495{
1496	tcp_push(ssk, 0, info->mss_now, tcp_sk(ssk)->nonagle, info->size_goal);
1497	release_sock(ssk);
1498}
1499
1500static void mptcp_update_post_push(struct mptcp_sock *msk,
1501				   struct mptcp_data_frag *dfrag,
1502				   u32 sent)
1503{
1504	u64 snd_nxt_new = dfrag->data_seq;
1505
1506	dfrag->already_sent += sent;
1507
1508	msk->snd_burst -= sent;
1509
1510	snd_nxt_new += dfrag->already_sent;
1511
1512	/* snd_nxt_new can be smaller than snd_nxt in case mptcp
1513	 * is recovering after a failover. In that event, this re-sends
1514	 * old segments.
1515	 *
1516	 * Thus compute snd_nxt_new candidate based on
1517	 * the dfrag->data_seq that was sent and the data
1518	 * that has been handed to the subflow for transmission
1519	 * and skip update in case it was old dfrag.
1520	 */
1521	if (likely(after64(snd_nxt_new, msk->snd_nxt)))
1522		msk->snd_nxt = snd_nxt_new;
1523}
1524
1525void mptcp_check_and_set_pending(struct sock *sk)
1526{
1527	if (mptcp_send_head(sk))
1528		mptcp_sk(sk)->push_pending |= BIT(MPTCP_PUSH_PENDING);
1529}
1530
1531void __mptcp_push_pending(struct sock *sk, unsigned int flags)
1532{
1533	struct sock *prev_ssk = NULL, *ssk = NULL;
1534	struct mptcp_sock *msk = mptcp_sk(sk);
1535	struct mptcp_sendmsg_info info = {
1536				.flags = flags,
1537	};
1538	bool do_check_data_fin = false;
1539	struct mptcp_data_frag *dfrag;
1540	int len;
1541
1542	while ((dfrag = mptcp_send_head(sk))) {
1543		info.sent = dfrag->already_sent;
1544		info.limit = dfrag->data_len;
1545		len = dfrag->data_len - dfrag->already_sent;
1546		while (len > 0) {
1547			int ret = 0;
1548
1549			prev_ssk = ssk;
1550			ssk = mptcp_subflow_get_send(msk);
1551
1552			/* First check. If the ssk has changed since
1553			 * the last round, release prev_ssk
1554			 */
1555			if (ssk != prev_ssk && prev_ssk)
1556				mptcp_push_release(prev_ssk, &info);
1557			if (!ssk)
1558				goto out;
1559
1560			/* Need to lock the new subflow only if different
1561			 * from the previous one, otherwise we are still
1562			 * helding the relevant lock
1563			 */
1564			if (ssk != prev_ssk)
1565				lock_sock(ssk);
1566
1567			ret = mptcp_sendmsg_frag(sk, ssk, dfrag, &info);
1568			if (ret <= 0) {
1569				if (ret == -EAGAIN)
1570					continue;
1571				mptcp_push_release(ssk, &info);
1572				goto out;
1573			}
1574
1575			do_check_data_fin = true;
1576			info.sent += ret;
1577			len -= ret;
1578
1579			mptcp_update_post_push(msk, dfrag, ret);
1580		}
1581		WRITE_ONCE(msk->first_pending, mptcp_send_next(sk));
1582	}
1583
1584	/* at this point we held the socket lock for the last subflow we used */
1585	if (ssk)
1586		mptcp_push_release(ssk, &info);
1587
1588out:
1589	/* ensure the rtx timer is running */
1590	if (!mptcp_timer_pending(sk))
1591		mptcp_reset_timer(sk);
1592	if (do_check_data_fin)
1593		__mptcp_check_send_data_fin(sk);
1594}
1595
1596static void __mptcp_subflow_push_pending(struct sock *sk, struct sock *ssk, bool first)
1597{
1598	struct mptcp_sock *msk = mptcp_sk(sk);
1599	struct mptcp_sendmsg_info info = {
1600		.data_lock_held = true,
1601	};
1602	struct mptcp_data_frag *dfrag;
1603	struct sock *xmit_ssk;
1604	int len, copied = 0;
1605
1606	info.flags = 0;
1607	while ((dfrag = mptcp_send_head(sk))) {
1608		info.sent = dfrag->already_sent;
1609		info.limit = dfrag->data_len;
1610		len = dfrag->data_len - dfrag->already_sent;
1611		while (len > 0) {
1612			int ret = 0;
1613
1614			/* check for a different subflow usage only after
1615			 * spooling the first chunk of data
1616			 */
1617			xmit_ssk = first ? ssk : mptcp_subflow_get_send(msk);
1618			if (!xmit_ssk)
1619				goto out;
1620			if (xmit_ssk != ssk) {
1621				mptcp_subflow_delegate(mptcp_subflow_ctx(xmit_ssk),
1622						       MPTCP_DELEGATE_SEND);
1623				goto out;
1624			}
1625
1626			ret = mptcp_sendmsg_frag(sk, ssk, dfrag, &info);
1627			if (ret <= 0)
1628				goto out;
1629
1630			info.sent += ret;
1631			copied += ret;
1632			len -= ret;
1633			first = false;
1634
1635			mptcp_update_post_push(msk, dfrag, ret);
1636		}
1637		WRITE_ONCE(msk->first_pending, mptcp_send_next(sk));
1638	}
1639
1640out:
1641	/* __mptcp_alloc_tx_skb could have released some wmem and we are
1642	 * not going to flush it via release_sock()
1643	 */
1644	if (copied) {
1645		tcp_push(ssk, 0, info.mss_now, tcp_sk(ssk)->nonagle,
1646			 info.size_goal);
1647		if (!mptcp_timer_pending(sk))
1648			mptcp_reset_timer(sk);
1649
1650		if (msk->snd_data_fin_enable &&
1651		    msk->snd_nxt + 1 == msk->write_seq)
1652			mptcp_schedule_work(sk);
1653	}
1654}
1655
1656static void mptcp_set_nospace(struct sock *sk)
1657{
1658	/* enable autotune */
1659	set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1660
1661	/* will be cleared on avail space */
1662	set_bit(MPTCP_NOSPACE, &mptcp_sk(sk)->flags);
1663}
1664
1665static int mptcp_disconnect(struct sock *sk, int flags);
1666
1667static int mptcp_sendmsg_fastopen(struct sock *sk, struct sock *ssk, struct msghdr *msg,
1668				  size_t len, int *copied_syn)
1669{
1670	unsigned int saved_flags = msg->msg_flags;
1671	struct mptcp_sock *msk = mptcp_sk(sk);
1672	int ret;
1673
1674	lock_sock(ssk);
1675	msg->msg_flags |= MSG_DONTWAIT;
1676	msk->connect_flags = O_NONBLOCK;
1677	msk->fastopening = 1;
1678	ret = tcp_sendmsg_fastopen(ssk, msg, copied_syn, len, NULL);
1679	msk->fastopening = 0;
1680	msg->msg_flags = saved_flags;
1681	release_sock(ssk);
1682
1683	/* do the blocking bits of inet_stream_connect outside the ssk socket lock */
1684	if (ret == -EINPROGRESS && !(msg->msg_flags & MSG_DONTWAIT)) {
1685		ret = __inet_stream_connect(sk->sk_socket, msg->msg_name,
1686					    msg->msg_namelen, msg->msg_flags, 1);
1687
1688		/* Keep the same behaviour of plain TCP: zero the copied bytes in
1689		 * case of any error, except timeout or signal
1690		 */
1691		if (ret && ret != -EINPROGRESS && ret != -ERESTARTSYS && ret != -EINTR)
1692			*copied_syn = 0;
1693	} else if (ret && ret != -EINPROGRESS) {
1694		mptcp_disconnect(sk, 0);
1695	}
1696
1697	return ret;
1698}
1699
1700static int mptcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1701{
1702	struct mptcp_sock *msk = mptcp_sk(sk);
1703	struct page_frag *pfrag;
1704	struct socket *ssock;
1705	size_t copied = 0;
1706	int ret = 0;
1707	long timeo;
1708
1709	/* silently ignore everything else */
1710	msg->msg_flags &= MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL | MSG_FASTOPEN;
1711
1712	lock_sock(sk);
1713
1714	ssock = __mptcp_nmpc_socket(msk);
1715	if (unlikely(ssock && (inet_sk(ssock->sk)->defer_connect ||
1716			       msg->msg_flags & MSG_FASTOPEN))) {
1717		int copied_syn = 0;
1718
1719		ret = mptcp_sendmsg_fastopen(sk, ssock->sk, msg, len, &copied_syn);
1720		copied += copied_syn;
1721		if (ret == -EINPROGRESS && copied_syn > 0)
1722			goto out;
1723		else if (ret)
1724			goto do_error;
1725	}
1726
1727	timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1728
1729	if ((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) {
1730		ret = sk_stream_wait_connect(sk, &timeo);
1731		if (ret)
1732			goto do_error;
1733	}
1734
1735	ret = -EPIPE;
1736	if (unlikely(sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN)))
1737		goto do_error;
1738
1739	pfrag = sk_page_frag(sk);
1740
1741	while (msg_data_left(msg)) {
1742		int total_ts, frag_truesize = 0;
1743		struct mptcp_data_frag *dfrag;
1744		bool dfrag_collapsed;
1745		size_t psize, offset;
1746
1747		/* reuse tail pfrag, if possible, or carve a new one from the
1748		 * page allocator
1749		 */
1750		dfrag = mptcp_pending_tail(sk);
1751		dfrag_collapsed = mptcp_frag_can_collapse_to(msk, pfrag, dfrag);
1752		if (!dfrag_collapsed) {
1753			if (!sk_stream_memory_free(sk))
1754				goto wait_for_memory;
1755
1756			if (!mptcp_page_frag_refill(sk, pfrag))
1757				goto wait_for_memory;
1758
1759			dfrag = mptcp_carve_data_frag(msk, pfrag, pfrag->offset);
1760			frag_truesize = dfrag->overhead;
1761		}
1762
1763		/* we do not bound vs wspace, to allow a single packet.
1764		 * memory accounting will prevent execessive memory usage
1765		 * anyway
1766		 */
1767		offset = dfrag->offset + dfrag->data_len;
1768		psize = pfrag->size - offset;
1769		psize = min_t(size_t, psize, msg_data_left(msg));
1770		total_ts = psize + frag_truesize;
1771
1772		if (!sk_wmem_schedule(sk, total_ts))
1773			goto wait_for_memory;
1774
1775		if (copy_page_from_iter(dfrag->page, offset, psize,
1776					&msg->msg_iter) != psize) {
1777			ret = -EFAULT;
1778			goto do_error;
1779		}
1780
1781		/* data successfully copied into the write queue */
1782		sk->sk_forward_alloc -= total_ts;
1783		copied += psize;
1784		dfrag->data_len += psize;
1785		frag_truesize += psize;
1786		pfrag->offset += frag_truesize;
1787		WRITE_ONCE(msk->write_seq, msk->write_seq + psize);
1788
1789		/* charge data on mptcp pending queue to the msk socket
1790		 * Note: we charge such data both to sk and ssk
1791		 */
1792		sk_wmem_queued_add(sk, frag_truesize);
1793		if (!dfrag_collapsed) {
1794			get_page(dfrag->page);
1795			list_add_tail(&dfrag->list, &msk->rtx_queue);
1796			if (!msk->first_pending)
1797				WRITE_ONCE(msk->first_pending, dfrag);
1798		}
1799		pr_debug("msk=%p dfrag at seq=%llu len=%u sent=%u new=%d", msk,
1800			 dfrag->data_seq, dfrag->data_len, dfrag->already_sent,
1801			 !dfrag_collapsed);
1802
1803		continue;
1804
1805wait_for_memory:
1806		mptcp_set_nospace(sk);
1807		__mptcp_push_pending(sk, msg->msg_flags);
1808		ret = sk_stream_wait_memory(sk, &timeo);
1809		if (ret)
1810			goto do_error;
1811	}
1812
1813	if (copied)
1814		__mptcp_push_pending(sk, msg->msg_flags);
1815
1816out:
1817	release_sock(sk);
1818	return copied;
1819
1820do_error:
1821	if (copied)
1822		goto out;
1823
1824	copied = sk_stream_error(sk, msg->msg_flags, ret);
1825	goto out;
1826}
1827
1828static int __mptcp_recvmsg_mskq(struct mptcp_sock *msk,
1829				struct msghdr *msg,
1830				size_t len, int flags,
1831				struct scm_timestamping_internal *tss,
1832				int *cmsg_flags)
1833{
1834	struct sk_buff *skb, *tmp;
1835	int copied = 0;
1836
1837	skb_queue_walk_safe(&msk->receive_queue, skb, tmp) {
1838		u32 offset = MPTCP_SKB_CB(skb)->offset;
1839		u32 data_len = skb->len - offset;
1840		u32 count = min_t(size_t, len - copied, data_len);
1841		int err;
1842
1843		if (!(flags & MSG_TRUNC)) {
1844			err = skb_copy_datagram_msg(skb, offset, msg, count);
1845			if (unlikely(err < 0)) {
1846				if (!copied)
1847					return err;
1848				break;
1849			}
1850		}
1851
1852		if (MPTCP_SKB_CB(skb)->has_rxtstamp) {
1853			tcp_update_recv_tstamps(skb, tss);
1854			*cmsg_flags |= MPTCP_CMSG_TS;
1855		}
1856
1857		copied += count;
1858
1859		if (count < data_len) {
1860			if (!(flags & MSG_PEEK)) {
1861				MPTCP_SKB_CB(skb)->offset += count;
1862				MPTCP_SKB_CB(skb)->map_seq += count;
1863			}
1864			break;
1865		}
1866
1867		if (!(flags & MSG_PEEK)) {
1868			/* we will bulk release the skb memory later */
1869			skb->destructor = NULL;
1870			WRITE_ONCE(msk->rmem_released, msk->rmem_released + skb->truesize);
1871			__skb_unlink(skb, &msk->receive_queue);
1872			__kfree_skb(skb);
1873		}
1874
1875		if (copied >= len)
1876			break;
1877	}
1878
1879	return copied;
1880}
1881
1882/* receive buffer autotuning.  See tcp_rcv_space_adjust for more information.
1883 *
1884 * Only difference: Use highest rtt estimate of the subflows in use.
1885 */
1886static void mptcp_rcv_space_adjust(struct mptcp_sock *msk, int copied)
1887{
1888	struct mptcp_subflow_context *subflow;
1889	struct sock *sk = (struct sock *)msk;
1890	u32 time, advmss = 1;
1891	u64 rtt_us, mstamp;
1892
1893	sock_owned_by_me(sk);
1894
1895	if (copied <= 0)
1896		return;
1897
1898	msk->rcvq_space.copied += copied;
1899
1900	mstamp = div_u64(tcp_clock_ns(), NSEC_PER_USEC);
1901	time = tcp_stamp_us_delta(mstamp, msk->rcvq_space.time);
1902
1903	rtt_us = msk->rcvq_space.rtt_us;
1904	if (rtt_us && time < (rtt_us >> 3))
1905		return;
1906
1907	rtt_us = 0;
1908	mptcp_for_each_subflow(msk, subflow) {
1909		const struct tcp_sock *tp;
1910		u64 sf_rtt_us;
1911		u32 sf_advmss;
1912
1913		tp = tcp_sk(mptcp_subflow_tcp_sock(subflow));
1914
1915		sf_rtt_us = READ_ONCE(tp->rcv_rtt_est.rtt_us);
1916		sf_advmss = READ_ONCE(tp->advmss);
1917
1918		rtt_us = max(sf_rtt_us, rtt_us);
1919		advmss = max(sf_advmss, advmss);
1920	}
1921
1922	msk->rcvq_space.rtt_us = rtt_us;
1923	if (time < (rtt_us >> 3) || rtt_us == 0)
1924		return;
1925
1926	if (msk->rcvq_space.copied <= msk->rcvq_space.space)
1927		goto new_measure;
1928
1929	if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_moderate_rcvbuf) &&
1930	    !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
1931		int rcvmem, rcvbuf;
1932		u64 rcvwin, grow;
1933
1934		rcvwin = ((u64)msk->rcvq_space.copied << 1) + 16 * advmss;
1935
1936		grow = rcvwin * (msk->rcvq_space.copied - msk->rcvq_space.space);
1937
1938		do_div(grow, msk->rcvq_space.space);
1939		rcvwin += (grow << 1);
1940
1941		rcvmem = SKB_TRUESIZE(advmss + MAX_TCP_HEADER);
1942		while (tcp_win_from_space(sk, rcvmem) < advmss)
1943			rcvmem += 128;
1944
1945		do_div(rcvwin, advmss);
1946		rcvbuf = min_t(u64, rcvwin * rcvmem,
1947			       READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2]));
1948
1949		if (rcvbuf > sk->sk_rcvbuf) {
1950			u32 window_clamp;
1951
1952			window_clamp = tcp_win_from_space(sk, rcvbuf);
1953			WRITE_ONCE(sk->sk_rcvbuf, rcvbuf);
1954
1955			/* Make subflows follow along.  If we do not do this, we
1956			 * get drops at subflow level if skbs can't be moved to
1957			 * the mptcp rx queue fast enough (announced rcv_win can
1958			 * exceed ssk->sk_rcvbuf).
1959			 */
1960			mptcp_for_each_subflow(msk, subflow) {
1961				struct sock *ssk;
1962				bool slow;
1963
1964				ssk = mptcp_subflow_tcp_sock(subflow);
1965				slow = lock_sock_fast(ssk);
1966				WRITE_ONCE(ssk->sk_rcvbuf, rcvbuf);
1967				tcp_sk(ssk)->window_clamp = window_clamp;
1968				tcp_cleanup_rbuf(ssk, 1);
1969				unlock_sock_fast(ssk, slow);
1970			}
1971		}
1972	}
1973
1974	msk->rcvq_space.space = msk->rcvq_space.copied;
1975new_measure:
1976	msk->rcvq_space.copied = 0;
1977	msk->rcvq_space.time = mstamp;
1978}
1979
1980static void __mptcp_update_rmem(struct sock *sk)
1981{
1982	struct mptcp_sock *msk = mptcp_sk(sk);
1983
1984	if (!msk->rmem_released)
1985		return;
1986
1987	atomic_sub(msk->rmem_released, &sk->sk_rmem_alloc);
1988	mptcp_rmem_uncharge(sk, msk->rmem_released);
1989	WRITE_ONCE(msk->rmem_released, 0);
1990}
1991
1992static void __mptcp_splice_receive_queue(struct sock *sk)
1993{
1994	struct mptcp_sock *msk = mptcp_sk(sk);
1995
1996	skb_queue_splice_tail_init(&sk->sk_receive_queue, &msk->receive_queue);
1997}
1998
1999static bool __mptcp_move_skbs(struct mptcp_sock *msk)
2000{
2001	struct sock *sk = (struct sock *)msk;
2002	unsigned int moved = 0;
2003	bool ret, done;
2004
2005	do {
2006		struct sock *ssk = mptcp_subflow_recv_lookup(msk);
2007		bool slowpath;
2008
2009		/* we can have data pending in the subflows only if the msk
2010		 * receive buffer was full at subflow_data_ready() time,
2011		 * that is an unlikely slow path.
2012		 */
2013		if (likely(!ssk))
2014			break;
2015
2016		slowpath = lock_sock_fast(ssk);
2017		mptcp_data_lock(sk);
2018		__mptcp_update_rmem(sk);
2019		done = __mptcp_move_skbs_from_subflow(msk, ssk, &moved);
2020		mptcp_data_unlock(sk);
2021
2022		if (unlikely(ssk->sk_err))
2023			__mptcp_error_report(sk);
2024		unlock_sock_fast(ssk, slowpath);
2025	} while (!done);
2026
2027	/* acquire the data lock only if some input data is pending */
2028	ret = moved > 0;
2029	if (!RB_EMPTY_ROOT(&msk->out_of_order_queue) ||
2030	    !skb_queue_empty_lockless(&sk->sk_receive_queue)) {
2031		mptcp_data_lock(sk);
2032		__mptcp_update_rmem(sk);
2033		ret |= __mptcp_ofo_queue(msk);
2034		__mptcp_splice_receive_queue(sk);
2035		mptcp_data_unlock(sk);
2036	}
2037	if (ret)
2038		mptcp_check_data_fin((struct sock *)msk);
2039	return !skb_queue_empty(&msk->receive_queue);
2040}
2041
2042static unsigned int mptcp_inq_hint(const struct sock *sk)
2043{
2044	const struct mptcp_sock *msk = mptcp_sk(sk);
2045	const struct sk_buff *skb;
2046
2047	skb = skb_peek(&msk->receive_queue);
2048	if (skb) {
2049		u64 hint_val = msk->ack_seq - MPTCP_SKB_CB(skb)->map_seq;
2050
2051		if (hint_val >= INT_MAX)
2052			return INT_MAX;
2053
2054		return (unsigned int)hint_val;
2055	}
2056
2057	if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
2058		return 1;
2059
2060	return 0;
2061}
2062
2063static int mptcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
2064			 int flags, int *addr_len)
2065{
2066	struct mptcp_sock *msk = mptcp_sk(sk);
2067	struct scm_timestamping_internal tss;
2068	int copied = 0, cmsg_flags = 0;
2069	int target;
2070	long timeo;
2071
2072	/* MSG_ERRQUEUE is really a no-op till we support IP_RECVERR */
2073	if (unlikely(flags & MSG_ERRQUEUE))
2074		return inet_recv_error(sk, msg, len, addr_len);
2075
2076	lock_sock(sk);
2077	if (unlikely(sk->sk_state == TCP_LISTEN)) {
2078		copied = -ENOTCONN;
2079		goto out_err;
2080	}
2081
2082	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2083
2084	len = min_t(size_t, len, INT_MAX);
2085	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
2086
2087	if (unlikely(msk->recvmsg_inq))
2088		cmsg_flags = MPTCP_CMSG_INQ;
2089
2090	while (copied < len) {
2091		int bytes_read;
2092
2093		bytes_read = __mptcp_recvmsg_mskq(msk, msg, len - copied, flags, &tss, &cmsg_flags);
2094		if (unlikely(bytes_read < 0)) {
2095			if (!copied)
2096				copied = bytes_read;
2097			goto out_err;
2098		}
2099
2100		copied += bytes_read;
2101
2102		/* be sure to advertise window change */
2103		mptcp_cleanup_rbuf(msk);
2104
2105		if (skb_queue_empty(&msk->receive_queue) && __mptcp_move_skbs(msk))
2106			continue;
2107
2108		/* only the master socket status is relevant here. The exit
2109		 * conditions mirror closely tcp_recvmsg()
2110		 */
2111		if (copied >= target)
2112			break;
2113
2114		if (copied) {
2115			if (sk->sk_err ||
2116			    sk->sk_state == TCP_CLOSE ||
2117			    (sk->sk_shutdown & RCV_SHUTDOWN) ||
2118			    !timeo ||
2119			    signal_pending(current))
2120				break;
2121		} else {
2122			if (sk->sk_err) {
2123				copied = sock_error(sk);
2124				break;
2125			}
2126
2127			if (test_and_clear_bit(MPTCP_WORK_EOF, &msk->flags))
2128				mptcp_check_for_eof(msk);
2129
2130			if (sk->sk_shutdown & RCV_SHUTDOWN) {
2131				/* race breaker: the shutdown could be after the
2132				 * previous receive queue check
2133				 */
2134				if (__mptcp_move_skbs(msk))
2135					continue;
2136				break;
2137			}
2138
2139			if (sk->sk_state == TCP_CLOSE) {
2140				copied = -ENOTCONN;
2141				break;
2142			}
2143
2144			if (!timeo) {
2145				copied = -EAGAIN;
2146				break;
2147			}
2148
2149			if (signal_pending(current)) {
2150				copied = sock_intr_errno(timeo);
2151				break;
2152			}
2153		}
2154
2155		pr_debug("block timeout %ld", timeo);
2156		sk_wait_data(sk, &timeo, NULL);
2157	}
2158
2159out_err:
2160	if (cmsg_flags && copied >= 0) {
2161		if (cmsg_flags & MPTCP_CMSG_TS)
2162			tcp_recv_timestamp(msg, sk, &tss);
2163
2164		if (cmsg_flags & MPTCP_CMSG_INQ) {
2165			unsigned int inq = mptcp_inq_hint(sk);
2166
2167			put_cmsg(msg, SOL_TCP, TCP_CM_INQ, sizeof(inq), &inq);
2168		}
2169	}
2170
2171	pr_debug("msk=%p rx queue empty=%d:%d copied=%d",
2172		 msk, skb_queue_empty_lockless(&sk->sk_receive_queue),
2173		 skb_queue_empty(&msk->receive_queue), copied);
2174	if (!(flags & MSG_PEEK))
2175		mptcp_rcv_space_adjust(msk, copied);
2176
2177	release_sock(sk);
2178	return copied;
2179}
2180
2181static void mptcp_retransmit_timer(struct timer_list *t)
2182{
2183	struct inet_connection_sock *icsk = from_timer(icsk, t,
2184						       icsk_retransmit_timer);
2185	struct sock *sk = &icsk->icsk_inet.sk;
2186	struct mptcp_sock *msk = mptcp_sk(sk);
2187
2188	bh_lock_sock(sk);
2189	if (!sock_owned_by_user(sk)) {
2190		/* we need a process context to retransmit */
2191		if (!test_and_set_bit(MPTCP_WORK_RTX, &msk->flags))
2192			mptcp_schedule_work(sk);
2193	} else {
2194		/* delegate our work to tcp_release_cb() */
2195		__set_bit(MPTCP_RETRANSMIT, &msk->cb_flags);
2196	}
2197	bh_unlock_sock(sk);
2198	sock_put(sk);
2199}
2200
2201static void mptcp_timeout_timer(struct timer_list *t)
2202{
2203	struct sock *sk = from_timer(sk, t, sk_timer);
2204
2205	mptcp_schedule_work(sk);
2206	sock_put(sk);
2207}
2208
2209/* Find an idle subflow.  Return NULL if there is unacked data at tcp
2210 * level.
2211 *
2212 * A backup subflow is returned only if that is the only kind available.
2213 */
2214static struct sock *mptcp_subflow_get_retrans(struct mptcp_sock *msk)
2215{
2216	struct sock *backup = NULL, *pick = NULL;
2217	struct mptcp_subflow_context *subflow;
2218	int min_stale_count = INT_MAX;
2219
2220	sock_owned_by_me((const struct sock *)msk);
2221
2222	if (__mptcp_check_fallback(msk))
2223		return NULL;
2224
2225	mptcp_for_each_subflow(msk, subflow) {
2226		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
2227
2228		if (!__mptcp_subflow_active(subflow))
2229			continue;
2230
2231		/* still data outstanding at TCP level? skip this */
2232		if (!tcp_rtx_and_write_queues_empty(ssk)) {
2233			mptcp_pm_subflow_chk_stale(msk, ssk);
2234			min_stale_count = min_t(int, min_stale_count, subflow->stale_count);
2235			continue;
2236		}
2237
2238		if (subflow->backup) {
2239			if (!backup)
2240				backup = ssk;
2241			continue;
2242		}
2243
2244		if (!pick)
2245			pick = ssk;
2246	}
2247
2248	if (pick)
2249		return pick;
2250
2251	/* use backup only if there are no progresses anywhere */
2252	return min_stale_count > 1 ? backup : NULL;
2253}
2254
2255static void mptcp_dispose_initial_subflow(struct mptcp_sock *msk)
2256{
2257	if (msk->subflow) {
2258		iput(SOCK_INODE(msk->subflow));
2259		msk->subflow = NULL;
2260	}
2261}
2262
2263bool __mptcp_retransmit_pending_data(struct sock *sk)
2264{
2265	struct mptcp_data_frag *cur, *rtx_head;
2266	struct mptcp_sock *msk = mptcp_sk(sk);
2267
2268	if (__mptcp_check_fallback(msk))
2269		return false;
2270
2271	if (tcp_rtx_and_write_queues_empty(sk))
2272		return false;
2273
2274	/* the closing socket has some data untransmitted and/or unacked:
2275	 * some data in the mptcp rtx queue has not really xmitted yet.
2276	 * keep it simple and re-inject the whole mptcp level rtx queue
2277	 */
2278	mptcp_data_lock(sk);
2279	__mptcp_clean_una_wakeup(sk);
2280	rtx_head = mptcp_rtx_head(sk);
2281	if (!rtx_head) {
2282		mptcp_data_unlock(sk);
2283		return false;
2284	}
2285
2286	msk->recovery_snd_nxt = msk->snd_nxt;
2287	msk->recovery = true;
2288	mptcp_data_unlock(sk);
2289
2290	msk->first_pending = rtx_head;
2291	msk->snd_burst = 0;
2292
2293	/* be sure to clear the "sent status" on all re-injected fragments */
2294	list_for_each_entry(cur, &msk->rtx_queue, list) {
2295		if (!cur->already_sent)
2296			break;
2297		cur->already_sent = 0;
2298	}
2299
2300	return true;
2301}
2302
2303/* flags for __mptcp_close_ssk() */
2304#define MPTCP_CF_PUSH		BIT(1)
2305#define MPTCP_CF_FASTCLOSE	BIT(2)
2306
2307/* subflow sockets can be either outgoing (connect) or incoming
2308 * (accept).
2309 *
2310 * Outgoing subflows use in-kernel sockets.
2311 * Incoming subflows do not have their own 'struct socket' allocated,
2312 * so we need to use tcp_close() after detaching them from the mptcp
2313 * parent socket.
2314 */
2315static void __mptcp_close_ssk(struct sock *sk, struct sock *ssk,
2316			      struct mptcp_subflow_context *subflow,
2317			      unsigned int flags)
2318{
2319	struct mptcp_sock *msk = mptcp_sk(sk);
2320	bool need_push, dispose_it;
2321
2322	dispose_it = !msk->subflow || ssk != msk->subflow->sk;
2323	if (dispose_it)
2324		list_del(&subflow->node);
2325
2326	lock_sock_nested(ssk, SINGLE_DEPTH_NESTING);
2327
2328	if (flags & MPTCP_CF_FASTCLOSE) {
2329		/* be sure to force the tcp_disconnect() path,
2330		 * to generate the egress reset
2331		 */
2332		ssk->sk_lingertime = 0;
2333		sock_set_flag(ssk, SOCK_LINGER);
2334		subflow->send_fastclose = 1;
2335	}
2336
2337	need_push = (flags & MPTCP_CF_PUSH) && __mptcp_retransmit_pending_data(sk);
2338	if (!dispose_it) {
2339		tcp_disconnect(ssk, 0);
2340		msk->subflow->state = SS_UNCONNECTED;
2341		mptcp_subflow_ctx_reset(subflow);
2342		release_sock(ssk);
2343
2344		goto out;
2345	}
2346
2347	sock_orphan(ssk);
2348	subflow->disposable = 1;
2349
2350	/* if ssk hit tcp_done(), tcp_cleanup_ulp() cleared the related ops
2351	 * the ssk has been already destroyed, we just need to release the
2352	 * reference owned by msk;
2353	 */
2354	if (!inet_csk(ssk)->icsk_ulp_ops) {
2355		kfree_rcu(subflow, rcu);
2356	} else {
2357		/* otherwise tcp will dispose of the ssk and subflow ctx */
2358		if (ssk->sk_state == TCP_LISTEN) {
2359			tcp_set_state(ssk, TCP_CLOSE);
2360			mptcp_subflow_queue_clean(sk, ssk);
2361			inet_csk_listen_stop(ssk);
2362			mptcp_event_pm_listener(ssk, MPTCP_EVENT_LISTENER_CLOSED);
2363		}
2364		__tcp_close(ssk, 0);
2365
2366		/* close acquired an extra ref */
2367		__sock_put(ssk);
2368	}
2369	release_sock(ssk);
2370
2371	sock_put(ssk);
2372
2373	if (ssk == msk->first)
2374		msk->first = NULL;
2375
2376out:
2377	if (ssk == msk->last_snd)
2378		msk->last_snd = NULL;
2379
2380	if (need_push)
2381		__mptcp_push_pending(sk, 0);
2382}
2383
2384void mptcp_close_ssk(struct sock *sk, struct sock *ssk,
2385		     struct mptcp_subflow_context *subflow)
2386{
2387	if (sk->sk_state == TCP_ESTABLISHED)
2388		mptcp_event(MPTCP_EVENT_SUB_CLOSED, mptcp_sk(sk), ssk, GFP_KERNEL);
2389
2390	/* subflow aborted before reaching the fully_established status
2391	 * attempt the creation of the next subflow
2392	 */
2393	mptcp_pm_subflow_check_next(mptcp_sk(sk), ssk, subflow);
2394
2395	__mptcp_close_ssk(sk, ssk, subflow, MPTCP_CF_PUSH);
2396}
2397
2398static unsigned int mptcp_sync_mss(struct sock *sk, u32 pmtu)
2399{
2400	return 0;
2401}
2402
2403static void __mptcp_close_subflow(struct mptcp_sock *msk)
2404{
2405	struct mptcp_subflow_context *subflow, *tmp;
2406
2407	might_sleep();
2408
2409	mptcp_for_each_subflow_safe(msk, subflow, tmp) {
2410		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
2411
2412		if (inet_sk_state_load(ssk) != TCP_CLOSE)
2413			continue;
2414
2415		/* 'subflow_data_ready' will re-sched once rx queue is empty */
2416		if (!skb_queue_empty_lockless(&ssk->sk_receive_queue))
2417			continue;
2418
2419		mptcp_close_ssk((struct sock *)msk, ssk, subflow);
2420	}
2421}
2422
2423static bool mptcp_check_close_timeout(const struct sock *sk)
2424{
2425	s32 delta = tcp_jiffies32 - inet_csk(sk)->icsk_mtup.probe_timestamp;
2426	struct mptcp_subflow_context *subflow;
2427
2428	if (delta >= TCP_TIMEWAIT_LEN)
2429		return true;
2430
2431	/* if all subflows are in closed status don't bother with additional
2432	 * timeout
2433	 */
2434	mptcp_for_each_subflow(mptcp_sk(sk), subflow) {
2435		if (inet_sk_state_load(mptcp_subflow_tcp_sock(subflow)) !=
2436		    TCP_CLOSE)
2437			return false;
2438	}
2439	return true;
2440}
2441
2442static void mptcp_check_fastclose(struct mptcp_sock *msk)
2443{
2444	struct mptcp_subflow_context *subflow, *tmp;
2445	struct sock *sk = (struct sock *)msk;
2446
2447	if (likely(!READ_ONCE(msk->rcv_fastclose)))
2448		return;
2449
2450	mptcp_token_destroy(msk);
2451
2452	mptcp_for_each_subflow_safe(msk, subflow, tmp) {
2453		struct sock *tcp_sk = mptcp_subflow_tcp_sock(subflow);
2454		bool slow;
2455
2456		slow = lock_sock_fast(tcp_sk);
2457		if (tcp_sk->sk_state != TCP_CLOSE) {
2458			tcp_send_active_reset(tcp_sk, GFP_ATOMIC);
2459			tcp_set_state(tcp_sk, TCP_CLOSE);
2460		}
2461		unlock_sock_fast(tcp_sk, slow);
2462	}
2463
2464	/* Mirror the tcp_reset() error propagation */
2465	switch (sk->sk_state) {
2466	case TCP_SYN_SENT:
2467		sk->sk_err = ECONNREFUSED;
2468		break;
2469	case TCP_CLOSE_WAIT:
2470		sk->sk_err = EPIPE;
2471		break;
2472	case TCP_CLOSE:
2473		return;
2474	default:
2475		sk->sk_err = ECONNRESET;
2476	}
2477
2478	inet_sk_state_store(sk, TCP_CLOSE);
2479	sk->sk_shutdown = SHUTDOWN_MASK;
2480	smp_mb__before_atomic(); /* SHUTDOWN must be visible first */
2481	set_bit(MPTCP_WORK_CLOSE_SUBFLOW, &msk->flags);
2482
2483	/* the calling mptcp_worker will properly destroy the socket */
2484	if (sock_flag(sk, SOCK_DEAD))
2485		return;
2486
2487	sk->sk_state_change(sk);
2488	sk_error_report(sk);
2489}
2490
2491static void __mptcp_retrans(struct sock *sk)
2492{
2493	struct mptcp_sock *msk = mptcp_sk(sk);
2494	struct mptcp_sendmsg_info info = {};
2495	struct mptcp_data_frag *dfrag;
2496	size_t copied = 0;
2497	struct sock *ssk;
2498	int ret;
2499
2500	mptcp_clean_una_wakeup(sk);
2501
2502	/* first check ssk: need to kick "stale" logic */
2503	ssk = mptcp_subflow_get_retrans(msk);
2504	dfrag = mptcp_rtx_head(sk);
2505	if (!dfrag) {
2506		if (mptcp_data_fin_enabled(msk)) {
2507			struct inet_connection_sock *icsk = inet_csk(sk);
2508
2509			icsk->icsk_retransmits++;
2510			mptcp_set_datafin_timeout(sk);
2511			mptcp_send_ack(msk);
2512
2513			goto reset_timer;
2514		}
2515
2516		if (!mptcp_send_head(sk))
2517			return;
2518
2519		goto reset_timer;
2520	}
2521
2522	if (!ssk)
2523		goto reset_timer;
2524
2525	lock_sock(ssk);
2526
2527	/* limit retransmission to the bytes already sent on some subflows */
2528	info.sent = 0;
2529	info.limit = READ_ONCE(msk->csum_enabled) ? dfrag->data_len : dfrag->already_sent;
2530	while (info.sent < info.limit) {
2531		ret = mptcp_sendmsg_frag(sk, ssk, dfrag, &info);
2532		if (ret <= 0)
2533			break;
2534
2535		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_RETRANSSEGS);
2536		copied += ret;
2537		info.sent += ret;
2538	}
2539	if (copied) {
2540		dfrag->already_sent = max(dfrag->already_sent, info.sent);
2541		tcp_push(ssk, 0, info.mss_now, tcp_sk(ssk)->nonagle,
2542			 info.size_goal);
2543		WRITE_ONCE(msk->allow_infinite_fallback, false);
2544	}
2545
2546	release_sock(ssk);
2547
2548reset_timer:
2549	mptcp_check_and_set_pending(sk);
2550
2551	if (!mptcp_timer_pending(sk))
2552		mptcp_reset_timer(sk);
2553}
2554
2555/* schedule the timeout timer for the relevant event: either close timeout
2556 * or mp_fail timeout. The close timeout takes precedence on the mp_fail one
2557 */
2558void mptcp_reset_timeout(struct mptcp_sock *msk, unsigned long fail_tout)
2559{
2560	struct sock *sk = (struct sock *)msk;
2561	unsigned long timeout, close_timeout;
2562
2563	if (!fail_tout && !sock_flag(sk, SOCK_DEAD))
2564		return;
2565
2566	close_timeout = inet_csk(sk)->icsk_mtup.probe_timestamp - tcp_jiffies32 + jiffies + TCP_TIMEWAIT_LEN;
2567
2568	/* the close timeout takes precedence on the fail one, and here at least one of
2569	 * them is active
2570	 */
2571	timeout = sock_flag(sk, SOCK_DEAD) ? close_timeout : fail_tout;
2572
2573	sk_reset_timer(sk, &sk->sk_timer, timeout);
2574}
2575
2576static void mptcp_mp_fail_no_response(struct mptcp_sock *msk)
2577{
2578	struct sock *ssk = msk->first;
2579	bool slow;
2580
2581	if (!ssk)
2582		return;
2583
2584	pr_debug("MP_FAIL doesn't respond, reset the subflow");
2585
2586	slow = lock_sock_fast(ssk);
2587	mptcp_subflow_reset(ssk);
2588	WRITE_ONCE(mptcp_subflow_ctx(ssk)->fail_tout, 0);
2589	unlock_sock_fast(ssk, slow);
2590
2591	mptcp_reset_timeout(msk, 0);
2592}
2593
2594static void mptcp_do_fastclose(struct sock *sk)
2595{
2596	struct mptcp_subflow_context *subflow, *tmp;
2597	struct mptcp_sock *msk = mptcp_sk(sk);
2598
2599	mptcp_for_each_subflow_safe(msk, subflow, tmp)
2600		__mptcp_close_ssk(sk, mptcp_subflow_tcp_sock(subflow),
2601				  subflow, MPTCP_CF_FASTCLOSE);
2602}
2603
2604static void mptcp_worker(struct work_struct *work)
2605{
2606	struct mptcp_sock *msk = container_of(work, struct mptcp_sock, work);
2607	struct sock *sk = (struct sock *)msk;
2608	unsigned long fail_tout;
2609	int state;
2610
2611	lock_sock(sk);
2612	state = sk->sk_state;
2613	if (unlikely(state == TCP_CLOSE))
2614		goto unlock;
2615
2616	mptcp_check_data_fin_ack(sk);
2617
2618	mptcp_check_fastclose(msk);
2619
2620	mptcp_pm_nl_work(msk);
2621
2622	if (test_and_clear_bit(MPTCP_WORK_EOF, &msk->flags))
2623		mptcp_check_for_eof(msk);
2624
2625	__mptcp_check_send_data_fin(sk);
2626	mptcp_check_data_fin(sk);
2627
2628	/* There is no point in keeping around an orphaned sk timedout or
2629	 * closed, but we need the msk around to reply to incoming DATA_FIN,
2630	 * even if it is orphaned and in FIN_WAIT2 state
2631	 */
2632	if (sock_flag(sk, SOCK_DEAD)) {
2633		if (mptcp_check_close_timeout(sk)) {
2634			inet_sk_state_store(sk, TCP_CLOSE);
2635			mptcp_do_fastclose(sk);
2636		}
2637		if (sk->sk_state == TCP_CLOSE) {
2638			__mptcp_destroy_sock(sk);
2639			goto unlock;
2640		}
2641	}
2642
2643	if (test_and_clear_bit(MPTCP_WORK_CLOSE_SUBFLOW, &msk->flags))
2644		__mptcp_close_subflow(msk);
2645
2646	if (test_and_clear_bit(MPTCP_WORK_RTX, &msk->flags))
2647		__mptcp_retrans(sk);
2648
2649	fail_tout = msk->first ? READ_ONCE(mptcp_subflow_ctx(msk->first)->fail_tout) : 0;
2650	if (fail_tout && time_after(jiffies, fail_tout))
2651		mptcp_mp_fail_no_response(msk);
2652
2653unlock:
2654	release_sock(sk);
2655	sock_put(sk);
2656}
2657
2658static int __mptcp_init_sock(struct sock *sk)
2659{
2660	struct mptcp_sock *msk = mptcp_sk(sk);
2661
2662	INIT_LIST_HEAD(&msk->conn_list);
2663	INIT_LIST_HEAD(&msk->join_list);
2664	INIT_LIST_HEAD(&msk->rtx_queue);
2665	INIT_WORK(&msk->work, mptcp_worker);
2666	__skb_queue_head_init(&msk->receive_queue);
2667	msk->out_of_order_queue = RB_ROOT;
2668	msk->first_pending = NULL;
2669	msk->rmem_fwd_alloc = 0;
2670	WRITE_ONCE(msk->rmem_released, 0);
2671	msk->timer_ival = TCP_RTO_MIN;
2672
2673	msk->first = NULL;
2674	inet_csk(sk)->icsk_sync_mss = mptcp_sync_mss;
2675	WRITE_ONCE(msk->csum_enabled, mptcp_is_checksum_enabled(sock_net(sk)));
2676	WRITE_ONCE(msk->allow_infinite_fallback, true);
2677	msk->recovery = false;
2678
2679	mptcp_pm_data_init(msk);
2680
2681	/* re-use the csk retrans timer for MPTCP-level retrans */
2682	timer_setup(&msk->sk.icsk_retransmit_timer, mptcp_retransmit_timer, 0);
2683	timer_setup(&sk->sk_timer, mptcp_timeout_timer, 0);
2684
2685	return 0;
2686}
2687
2688static void mptcp_ca_reset(struct sock *sk)
2689{
2690	struct inet_connection_sock *icsk = inet_csk(sk);
2691
2692	tcp_assign_congestion_control(sk);
2693	strcpy(mptcp_sk(sk)->ca_name, icsk->icsk_ca_ops->name);
2694
2695	/* no need to keep a reference to the ops, the name will suffice */
2696	tcp_cleanup_congestion_control(sk);
2697	icsk->icsk_ca_ops = NULL;
2698}
2699
2700static int mptcp_init_sock(struct sock *sk)
2701{
2702	struct net *net = sock_net(sk);
2703	int ret;
2704
2705	ret = __mptcp_init_sock(sk);
2706	if (ret)
2707		return ret;
2708
2709	if (!mptcp_is_enabled(net))
2710		return -ENOPROTOOPT;
2711
2712	if (unlikely(!net->mib.mptcp_statistics) && !mptcp_mib_alloc(net))
2713		return -ENOMEM;
2714
2715	ret = __mptcp_socket_create(mptcp_sk(sk));
2716	if (ret)
2717		return ret;
2718
2719	set_bit(SOCK_CUSTOM_SOCKOPT, &sk->sk_socket->flags);
2720
2721	/* fetch the ca name; do it outside __mptcp_init_sock(), so that clone will
2722	 * propagate the correct value
2723	 */
2724	mptcp_ca_reset(sk);
2725
2726	sk_sockets_allocated_inc(sk);
2727	sk->sk_rcvbuf = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[1]);
2728	sk->sk_sndbuf = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_wmem[1]);
2729
2730	return 0;
2731}
2732
2733static void __mptcp_clear_xmit(struct sock *sk)
2734{
2735	struct mptcp_sock *msk = mptcp_sk(sk);
2736	struct mptcp_data_frag *dtmp, *dfrag;
2737
2738	WRITE_ONCE(msk->first_pending, NULL);
2739	list_for_each_entry_safe(dfrag, dtmp, &msk->rtx_queue, list)
2740		dfrag_clear(sk, dfrag);
2741}
2742
2743void mptcp_cancel_work(struct sock *sk)
2744{
2745	struct mptcp_sock *msk = mptcp_sk(sk);
2746
2747	if (cancel_work_sync(&msk->work))
2748		__sock_put(sk);
2749}
2750
2751void mptcp_subflow_shutdown(struct sock *sk, struct sock *ssk, int how)
2752{
2753	lock_sock(ssk);
2754
2755	switch (ssk->sk_state) {
2756	case TCP_LISTEN:
2757		if (!(how & RCV_SHUTDOWN))
2758			break;
2759		fallthrough;
2760	case TCP_SYN_SENT:
2761		tcp_disconnect(ssk, O_NONBLOCK);
2762		break;
2763	default:
2764		if (__mptcp_check_fallback(mptcp_sk(sk))) {
2765			pr_debug("Fallback");
2766			ssk->sk_shutdown |= how;
2767			tcp_shutdown(ssk, how);
2768		} else {
2769			pr_debug("Sending DATA_FIN on subflow %p", ssk);
2770			tcp_send_ack(ssk);
2771			if (!mptcp_timer_pending(sk))
2772				mptcp_reset_timer(sk);
2773		}
2774		break;
2775	}
2776
2777	release_sock(ssk);
2778}
2779
2780static const unsigned char new_state[16] = {
2781	/* current state:     new state:      action:	*/
2782	[0 /* (Invalid) */] = TCP_CLOSE,
2783	[TCP_ESTABLISHED]   = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
2784	[TCP_SYN_SENT]      = TCP_CLOSE,
2785	[TCP_SYN_RECV]      = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
2786	[TCP_FIN_WAIT1]     = TCP_FIN_WAIT1,
2787	[TCP_FIN_WAIT2]     = TCP_FIN_WAIT2,
2788	[TCP_TIME_WAIT]     = TCP_CLOSE,	/* should not happen ! */
2789	[TCP_CLOSE]         = TCP_CLOSE,
2790	[TCP_CLOSE_WAIT]    = TCP_LAST_ACK  | TCP_ACTION_FIN,
2791	[TCP_LAST_ACK]      = TCP_LAST_ACK,
2792	[TCP_LISTEN]        = TCP_CLOSE,
2793	[TCP_CLOSING]       = TCP_CLOSING,
2794	[TCP_NEW_SYN_RECV]  = TCP_CLOSE,	/* should not happen ! */
2795};
2796
2797static int mptcp_close_state(struct sock *sk)
2798{
2799	int next = (int)new_state[sk->sk_state];
2800	int ns = next & TCP_STATE_MASK;
2801
2802	inet_sk_state_store(sk, ns);
2803
2804	return next & TCP_ACTION_FIN;
2805}
2806
2807static void __mptcp_check_send_data_fin(struct sock *sk)
2808{
2809	struct mptcp_subflow_context *subflow;
2810	struct mptcp_sock *msk = mptcp_sk(sk);
2811
2812	pr_debug("msk=%p snd_data_fin_enable=%d pending=%d snd_nxt=%llu write_seq=%llu",
2813		 msk, msk->snd_data_fin_enable, !!mptcp_send_head(sk),
2814		 msk->snd_nxt, msk->write_seq);
2815
2816	/* we still need to enqueue subflows or not really shutting down,
2817	 * skip this
2818	 */
2819	if (!msk->snd_data_fin_enable || msk->snd_nxt + 1 != msk->write_seq ||
2820	    mptcp_send_head(sk))
2821		return;
2822
2823	WRITE_ONCE(msk->snd_nxt, msk->write_seq);
2824
2825	/* fallback socket will not get data_fin/ack, can move to the next
2826	 * state now
2827	 */
2828	if (__mptcp_check_fallback(msk)) {
2829		WRITE_ONCE(msk->snd_una, msk->write_seq);
2830		if ((1 << sk->sk_state) & (TCPF_CLOSING | TCPF_LAST_ACK)) {
2831			inet_sk_state_store(sk, TCP_CLOSE);
2832			mptcp_close_wake_up(sk);
2833		} else if (sk->sk_state == TCP_FIN_WAIT1) {
2834			inet_sk_state_store(sk, TCP_FIN_WAIT2);
2835		}
2836	}
2837
2838	mptcp_for_each_subflow(msk, subflow) {
2839		struct sock *tcp_sk = mptcp_subflow_tcp_sock(subflow);
2840
2841		mptcp_subflow_shutdown(sk, tcp_sk, SEND_SHUTDOWN);
2842	}
2843}
2844
2845static void __mptcp_wr_shutdown(struct sock *sk)
2846{
2847	struct mptcp_sock *msk = mptcp_sk(sk);
2848
2849	pr_debug("msk=%p snd_data_fin_enable=%d shutdown=%x state=%d pending=%d",
2850		 msk, msk->snd_data_fin_enable, sk->sk_shutdown, sk->sk_state,
2851		 !!mptcp_send_head(sk));
2852
2853	/* will be ignored by fallback sockets */
2854	WRITE_ONCE(msk->write_seq, msk->write_seq + 1);
2855	WRITE_ONCE(msk->snd_data_fin_enable, 1);
2856
2857	__mptcp_check_send_data_fin(sk);
2858}
2859
2860static void __mptcp_destroy_sock(struct sock *sk)
2861{
2862	struct mptcp_sock *msk = mptcp_sk(sk);
2863
2864	pr_debug("msk=%p", msk);
2865
2866	might_sleep();
2867
2868	mptcp_stop_timer(sk);
2869	sk_stop_timer(sk, &sk->sk_timer);
2870	msk->pm.status = 0;
2871
2872	sk->sk_prot->destroy(sk);
2873
2874	WARN_ON_ONCE(msk->rmem_fwd_alloc);
2875	WARN_ON_ONCE(msk->rmem_released);
2876	sk_stream_kill_queues(sk);
2877	xfrm_sk_free_policy(sk);
2878
2879	sk_refcnt_debug_release(sk);
2880	sock_put(sk);
2881}
2882
2883static __poll_t mptcp_check_readable(struct mptcp_sock *msk)
2884{
2885	/* Concurrent splices from sk_receive_queue into receive_queue will
2886	 * always show at least one non-empty queue when checked in this order.
2887	 */
2888	if (skb_queue_empty_lockless(&((struct sock *)msk)->sk_receive_queue) &&
2889	    skb_queue_empty_lockless(&msk->receive_queue))
2890		return 0;
2891
2892	return EPOLLIN | EPOLLRDNORM;
2893}
2894
2895bool __mptcp_close(struct sock *sk, long timeout)
2896{
2897	struct mptcp_subflow_context *subflow;
2898	struct mptcp_sock *msk = mptcp_sk(sk);
2899	bool do_cancel_work = false;
2900	int subflows_alive = 0;
2901
2902	sk->sk_shutdown = SHUTDOWN_MASK;
2903
2904	if ((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) {
2905		inet_sk_state_store(sk, TCP_CLOSE);
2906		goto cleanup;
2907	}
2908
2909	if (mptcp_check_readable(msk)) {
2910		/* the msk has read data, do the MPTCP equivalent of TCP reset */
2911		inet_sk_state_store(sk, TCP_CLOSE);
2912		mptcp_do_fastclose(sk);
2913	} else if (mptcp_close_state(sk)) {
2914		__mptcp_wr_shutdown(sk);
2915	}
2916
2917	sk_stream_wait_close(sk, timeout);
2918
2919cleanup:
2920	/* orphan all the subflows */
2921	inet_csk(sk)->icsk_mtup.probe_timestamp = tcp_jiffies32;
2922	mptcp_for_each_subflow(msk, subflow) {
2923		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
2924		bool slow = lock_sock_fast_nested(ssk);
2925
2926		subflows_alive += ssk->sk_state != TCP_CLOSE;
2927
2928		/* since the close timeout takes precedence on the fail one,
2929		 * cancel the latter
2930		 */
2931		if (ssk == msk->first)
2932			subflow->fail_tout = 0;
2933
2934		/* detach from the parent socket, but allow data_ready to
2935		 * push incoming data into the mptcp stack, to properly ack it
2936		 */
2937		ssk->sk_socket = NULL;
2938		ssk->sk_wq = NULL;
2939		unlock_sock_fast(ssk, slow);
2940	}
2941	sock_orphan(sk);
2942
2943	/* all the subflows are closed, only timeout can change the msk
2944	 * state, let's not keep resources busy for no reasons
2945	 */
2946	if (subflows_alive == 0)
2947		inet_sk_state_store(sk, TCP_CLOSE);
2948
2949	sock_hold(sk);
2950	pr_debug("msk=%p state=%d", sk, sk->sk_state);
2951	if (msk->token)
2952		mptcp_event(MPTCP_EVENT_CLOSED, msk, NULL, GFP_KERNEL);
2953
2954	if (sk->sk_state == TCP_CLOSE) {
2955		__mptcp_destroy_sock(sk);
2956		do_cancel_work = true;
2957	} else {
2958		mptcp_reset_timeout(msk, 0);
2959	}
2960
2961	return do_cancel_work;
2962}
2963
2964static void mptcp_close(struct sock *sk, long timeout)
2965{
2966	bool do_cancel_work;
2967
2968	lock_sock(sk);
2969
2970	do_cancel_work = __mptcp_close(sk, timeout);
2971	release_sock(sk);
2972	if (do_cancel_work)
2973		mptcp_cancel_work(sk);
2974
2975	sock_put(sk);
2976}
2977
2978void mptcp_copy_inaddrs(struct sock *msk, const struct sock *ssk)
2979{
2980#if IS_ENABLED(CONFIG_MPTCP_IPV6)
2981	const struct ipv6_pinfo *ssk6 = inet6_sk(ssk);
2982	struct ipv6_pinfo *msk6 = inet6_sk(msk);
2983
2984	msk->sk_v6_daddr = ssk->sk_v6_daddr;
2985	msk->sk_v6_rcv_saddr = ssk->sk_v6_rcv_saddr;
2986
2987	if (msk6 && ssk6) {
2988		msk6->saddr = ssk6->saddr;
2989		msk6->flow_label = ssk6->flow_label;
2990	}
2991#endif
2992
2993	inet_sk(msk)->inet_num = inet_sk(ssk)->inet_num;
2994	inet_sk(msk)->inet_dport = inet_sk(ssk)->inet_dport;
2995	inet_sk(msk)->inet_sport = inet_sk(ssk)->inet_sport;
2996	inet_sk(msk)->inet_daddr = inet_sk(ssk)->inet_daddr;
2997	inet_sk(msk)->inet_saddr = inet_sk(ssk)->inet_saddr;
2998	inet_sk(msk)->inet_rcv_saddr = inet_sk(ssk)->inet_rcv_saddr;
2999}
3000
3001static int mptcp_disconnect(struct sock *sk, int flags)
3002{
3003	struct mptcp_sock *msk = mptcp_sk(sk);
3004
3005	/* We are on the fastopen error path. We can't call straight into the
3006	 * subflows cleanup code due to lock nesting (we are already under
3007	 * msk->firstsocket lock). Do nothing and leave the cleanup to the
3008	 * caller.
3009	 */
3010	if (msk->fastopening)
3011		return 0;
3012
3013	inet_sk_state_store(sk, TCP_CLOSE);
3014
3015	mptcp_stop_timer(sk);
3016	sk_stop_timer(sk, &sk->sk_timer);
3017
3018	if (msk->token)
3019		mptcp_event(MPTCP_EVENT_CLOSED, msk, NULL, GFP_KERNEL);
3020
3021	/* msk->subflow is still intact, the following will not free the first
3022	 * subflow
3023	 */
3024	mptcp_destroy_common(msk, MPTCP_CF_FASTCLOSE);
3025	msk->last_snd = NULL;
3026	WRITE_ONCE(msk->flags, 0);
3027	msk->cb_flags = 0;
3028	msk->push_pending = 0;
3029	msk->recovery = false;
3030	msk->can_ack = false;
3031	msk->fully_established = false;
3032	msk->rcv_data_fin = false;
3033	msk->snd_data_fin_enable = false;
3034	msk->rcv_fastclose = false;
3035	msk->use_64bit_ack = false;
3036	WRITE_ONCE(msk->csum_enabled, mptcp_is_checksum_enabled(sock_net(sk)));
3037	mptcp_pm_data_reset(msk);
3038	mptcp_ca_reset(sk);
3039
3040	sk->sk_shutdown = 0;
3041	sk_error_report(sk);
3042	return 0;
3043}
3044
3045#if IS_ENABLED(CONFIG_MPTCP_IPV6)
3046static struct ipv6_pinfo *mptcp_inet6_sk(const struct sock *sk)
3047{
3048	unsigned int offset = sizeof(struct mptcp6_sock) - sizeof(struct ipv6_pinfo);
3049
3050	return (struct ipv6_pinfo *)(((u8 *)sk) + offset);
3051}
3052#endif
3053
3054struct sock *mptcp_sk_clone(const struct sock *sk,
3055			    const struct mptcp_options_received *mp_opt,
3056			    struct request_sock *req)
3057{
3058	struct mptcp_subflow_request_sock *subflow_req = mptcp_subflow_rsk(req);
3059	struct sock *nsk = sk_clone_lock(sk, GFP_ATOMIC);
3060	struct mptcp_sock *msk;
3061
3062	if (!nsk)
3063		return NULL;
3064
3065#if IS_ENABLED(CONFIG_MPTCP_IPV6)
3066	if (nsk->sk_family == AF_INET6)
3067		inet_sk(nsk)->pinet6 = mptcp_inet6_sk(nsk);
3068#endif
3069
3070	__mptcp_init_sock(nsk);
3071
3072	msk = mptcp_sk(nsk);
3073	msk->local_key = subflow_req->local_key;
3074	msk->token = subflow_req->token;
3075	msk->subflow = NULL;
3076	WRITE_ONCE(msk->fully_established, false);
3077	if (mp_opt->suboptions & OPTION_MPTCP_CSUMREQD)
3078		WRITE_ONCE(msk->csum_enabled, true);
3079
3080	msk->write_seq = subflow_req->idsn + 1;
3081	msk->snd_nxt = msk->write_seq;
3082	msk->snd_una = msk->write_seq;
3083	msk->wnd_end = msk->snd_nxt + req->rsk_rcv_wnd;
3084	msk->setsockopt_seq = mptcp_sk(sk)->setsockopt_seq;
3085
3086	sock_reset_flag(nsk, SOCK_RCU_FREE);
3087	/* will be fully established after successful MPC subflow creation */
3088	inet_sk_state_store(nsk, TCP_SYN_RECV);
3089
3090	security_inet_csk_clone(nsk, req);
3091	bh_unlock_sock(nsk);
3092
3093	/* keep a single reference */
3094	__sock_put(nsk);
3095	return nsk;
3096}
3097
3098void mptcp_rcv_space_init(struct mptcp_sock *msk, const struct sock *ssk)
3099{
3100	const struct tcp_sock *tp = tcp_sk(ssk);
3101
3102	msk->rcvq_space.copied = 0;
3103	msk->rcvq_space.rtt_us = 0;
3104
3105	msk->rcvq_space.time = tp->tcp_mstamp;
3106
3107	/* initial rcv_space offering made to peer */
3108	msk->rcvq_space.space = min_t(u32, tp->rcv_wnd,
3109				      TCP_INIT_CWND * tp->advmss);
3110	if (msk->rcvq_space.space == 0)
3111		msk->rcvq_space.space = TCP_INIT_CWND * TCP_MSS_DEFAULT;
3112
3113	WRITE_ONCE(msk->wnd_end, msk->snd_nxt + tcp_sk(ssk)->snd_wnd);
3114}
3115
3116static struct sock *mptcp_accept(struct sock *sk, int flags, int *err,
3117				 bool kern)
3118{
3119	struct mptcp_sock *msk = mptcp_sk(sk);
3120	struct socket *listener;
3121	struct sock *newsk;
3122
3123	listener = __mptcp_nmpc_socket(msk);
3124	if (WARN_ON_ONCE(!listener)) {
3125		*err = -EINVAL;
3126		return NULL;
3127	}
3128
3129	pr_debug("msk=%p, listener=%p", msk, mptcp_subflow_ctx(listener->sk));
3130	newsk = inet_csk_accept(listener->sk, flags, err, kern);
3131	if (!newsk)
3132		return NULL;
3133
3134	pr_debug("msk=%p, subflow is mptcp=%d", msk, sk_is_mptcp(newsk));
3135	if (sk_is_mptcp(newsk)) {
3136		struct mptcp_subflow_context *subflow;
3137		struct sock *new_mptcp_sock;
3138
3139		subflow = mptcp_subflow_ctx(newsk);
3140		new_mptcp_sock = subflow->conn;
3141
3142		/* is_mptcp should be false if subflow->conn is missing, see
3143		 * subflow_syn_recv_sock()
3144		 */
3145		if (WARN_ON_ONCE(!new_mptcp_sock)) {
3146			tcp_sk(newsk)->is_mptcp = 0;
3147			goto out;
3148		}
3149
3150		/* acquire the 2nd reference for the owning socket */
3151		sock_hold(new_mptcp_sock);
3152		newsk = new_mptcp_sock;
3153		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_MPCAPABLEPASSIVEACK);
3154	} else {
3155		MPTCP_INC_STATS(sock_net(sk),
3156				MPTCP_MIB_MPCAPABLEPASSIVEFALLBACK);
3157	}
3158
3159out:
3160	newsk->sk_kern_sock = kern;
3161	return newsk;
3162}
3163
3164void mptcp_destroy_common(struct mptcp_sock *msk, unsigned int flags)
3165{
3166	struct mptcp_subflow_context *subflow, *tmp;
3167	struct sock *sk = (struct sock *)msk;
3168
3169	__mptcp_clear_xmit(sk);
3170
3171	/* join list will be eventually flushed (with rst) at sock lock release time */
3172	mptcp_for_each_subflow_safe(msk, subflow, tmp)
3173		__mptcp_close_ssk(sk, mptcp_subflow_tcp_sock(subflow), subflow, flags);
3174
3175	/* move to sk_receive_queue, sk_stream_kill_queues will purge it */
3176	mptcp_data_lock(sk);
3177	skb_queue_splice_tail_init(&msk->receive_queue, &sk->sk_receive_queue);
3178	__skb_queue_purge(&sk->sk_receive_queue);
3179	skb_rbtree_purge(&msk->out_of_order_queue);
3180	mptcp_data_unlock(sk);
3181
3182	/* move all the rx fwd alloc into the sk_mem_reclaim_final in
3183	 * inet_sock_destruct() will dispose it
3184	 */
3185	sk->sk_forward_alloc += msk->rmem_fwd_alloc;
3186	msk->rmem_fwd_alloc = 0;
3187	mptcp_token_destroy(msk);
3188	mptcp_pm_free_anno_list(msk);
3189	mptcp_free_local_addr_list(msk);
3190}
3191
3192static void mptcp_destroy(struct sock *sk)
3193{
3194	struct mptcp_sock *msk = mptcp_sk(sk);
3195
3196	/* clears msk->subflow, allowing the following to close
3197	 * even the initial subflow
3198	 */
3199	mptcp_dispose_initial_subflow(msk);
3200	mptcp_destroy_common(msk, 0);
3201	sk_sockets_allocated_dec(sk);
3202}
3203
3204void __mptcp_data_acked(struct sock *sk)
3205{
3206	if (!sock_owned_by_user(sk))
3207		__mptcp_clean_una(sk);
3208	else
3209		__set_bit(MPTCP_CLEAN_UNA, &mptcp_sk(sk)->cb_flags);
3210
3211	if (mptcp_pending_data_fin_ack(sk))
3212		mptcp_schedule_work(sk);
3213}
3214
3215void __mptcp_check_push(struct sock *sk, struct sock *ssk)
3216{
3217	if (!mptcp_send_head(sk))
3218		return;
3219
3220	if (!sock_owned_by_user(sk))
3221		__mptcp_subflow_push_pending(sk, ssk, false);
3222	else
3223		__set_bit(MPTCP_PUSH_PENDING, &mptcp_sk(sk)->cb_flags);
3224}
3225
3226#define MPTCP_FLAGS_PROCESS_CTX_NEED (BIT(MPTCP_PUSH_PENDING) | \
3227				      BIT(MPTCP_RETRANSMIT) | \
3228				      BIT(MPTCP_FLUSH_JOIN_LIST))
3229
3230/* processes deferred events and flush wmem */
3231static void mptcp_release_cb(struct sock *sk)
3232	__must_hold(&sk->sk_lock.slock)
3233{
3234	struct mptcp_sock *msk = mptcp_sk(sk);
3235
3236	for (;;) {
3237		unsigned long flags = (msk->cb_flags & MPTCP_FLAGS_PROCESS_CTX_NEED) |
3238				      msk->push_pending;
3239		if (!flags)
3240			break;
3241
3242		/* the following actions acquire the subflow socket lock
3243		 *
3244		 * 1) can't be invoked in atomic scope
3245		 * 2) must avoid ABBA deadlock with msk socket spinlock: the RX
3246		 *    datapath acquires the msk socket spinlock while helding
3247		 *    the subflow socket lock
3248		 */
3249		msk->push_pending = 0;
3250		msk->cb_flags &= ~flags;
3251		spin_unlock_bh(&sk->sk_lock.slock);
3252		if (flags & BIT(MPTCP_FLUSH_JOIN_LIST))
3253			__mptcp_flush_join_list(sk);
3254		if (flags & BIT(MPTCP_PUSH_PENDING))
3255			__mptcp_push_pending(sk, 0);
3256		if (flags & BIT(MPTCP_RETRANSMIT))
3257			__mptcp_retrans(sk);
3258
3259		cond_resched();
3260		spin_lock_bh(&sk->sk_lock.slock);
3261	}
3262
3263	if (__test_and_clear_bit(MPTCP_CLEAN_UNA, &msk->cb_flags))
3264		__mptcp_clean_una_wakeup(sk);
3265	if (unlikely(&msk->cb_flags)) {
3266		/* be sure to set the current sk state before tacking actions
3267		 * depending on sk_state, that is processing MPTCP_ERROR_REPORT
3268		 */
3269		if (__test_and_clear_bit(MPTCP_CONNECTED, &msk->cb_flags))
3270			__mptcp_set_connected(sk);
3271		if (__test_and_clear_bit(MPTCP_ERROR_REPORT, &msk->cb_flags))
3272			__mptcp_error_report(sk);
3273		if (__test_and_clear_bit(MPTCP_RESET_SCHEDULER, &msk->cb_flags))
3274			msk->last_snd = NULL;
3275	}
3276
3277	__mptcp_update_rmem(sk);
3278}
3279
3280/* MP_JOIN client subflow must wait for 4th ack before sending any data:
3281 * TCP can't schedule delack timer before the subflow is fully established.
3282 * MPTCP uses the delack timer to do 3rd ack retransmissions
3283 */
3284static void schedule_3rdack_retransmission(struct sock *ssk)
3285{
3286	struct inet_connection_sock *icsk = inet_csk(ssk);
3287	struct tcp_sock *tp = tcp_sk(ssk);
3288	unsigned long timeout;
3289
3290	if (mptcp_subflow_ctx(ssk)->fully_established)
3291		return;
3292
3293	/* reschedule with a timeout above RTT, as we must look only for drop */
3294	if (tp->srtt_us)
3295		timeout = usecs_to_jiffies(tp->srtt_us >> (3 - 1));
3296	else
3297		timeout = TCP_TIMEOUT_INIT;
3298	timeout += jiffies;
3299
3300	WARN_ON_ONCE(icsk->icsk_ack.pending & ICSK_ACK_TIMER);
3301	icsk->icsk_ack.pending |= ICSK_ACK_SCHED | ICSK_ACK_TIMER;
3302	icsk->icsk_ack.timeout = timeout;
3303	sk_reset_timer(ssk, &icsk->icsk_delack_timer, timeout);
3304}
3305
3306void mptcp_subflow_process_delegated(struct sock *ssk)
3307{
3308	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
3309	struct sock *sk = subflow->conn;
3310
3311	if (test_bit(MPTCP_DELEGATE_SEND, &subflow->delegated_status)) {
3312		mptcp_data_lock(sk);
3313		if (!sock_owned_by_user(sk))
3314			__mptcp_subflow_push_pending(sk, ssk, true);
3315		else
3316			__set_bit(MPTCP_PUSH_PENDING, &mptcp_sk(sk)->cb_flags);
3317		mptcp_data_unlock(sk);
3318		mptcp_subflow_delegated_done(subflow, MPTCP_DELEGATE_SEND);
3319	}
3320	if (test_bit(MPTCP_DELEGATE_ACK, &subflow->delegated_status)) {
3321		schedule_3rdack_retransmission(ssk);
3322		mptcp_subflow_delegated_done(subflow, MPTCP_DELEGATE_ACK);
3323	}
3324}
3325
3326static int mptcp_hash(struct sock *sk)
3327{
3328	/* should never be called,
3329	 * we hash the TCP subflows not the master socket
3330	 */
3331	WARN_ON_ONCE(1);
3332	return 0;
3333}
3334
3335static void mptcp_unhash(struct sock *sk)
3336{
3337	/* called from sk_common_release(), but nothing to do here */
3338}
3339
3340static int mptcp_get_port(struct sock *sk, unsigned short snum)
3341{
3342	struct mptcp_sock *msk = mptcp_sk(sk);
3343	struct socket *ssock;
3344
3345	ssock = __mptcp_nmpc_socket(msk);
3346	pr_debug("msk=%p, subflow=%p", msk, ssock);
3347	if (WARN_ON_ONCE(!ssock))
3348		return -EINVAL;
3349
3350	return inet_csk_get_port(ssock->sk, snum);
3351}
3352
3353void mptcp_finish_connect(struct sock *ssk)
3354{
3355	struct mptcp_subflow_context *subflow;
3356	struct mptcp_sock *msk;
3357	struct sock *sk;
3358
3359	subflow = mptcp_subflow_ctx(ssk);
3360	sk = subflow->conn;
3361	msk = mptcp_sk(sk);
3362
3363	pr_debug("msk=%p, token=%u", sk, subflow->token);
3364
3365	subflow->map_seq = subflow->iasn;
3366	subflow->map_subflow_seq = 1;
3367
3368	/* the socket is not connected yet, no msk/subflow ops can access/race
3369	 * accessing the field below
3370	 */
3371	WRITE_ONCE(msk->local_key, subflow->local_key);
3372	WRITE_ONCE(msk->write_seq, subflow->idsn + 1);
3373	WRITE_ONCE(msk->snd_nxt, msk->write_seq);
3374	WRITE_ONCE(msk->snd_una, msk->write_seq);
3375
3376	mptcp_pm_new_connection(msk, ssk, 0);
3377
3378	mptcp_rcv_space_init(msk, ssk);
3379}
3380
3381void mptcp_sock_graft(struct sock *sk, struct socket *parent)
3382{
3383	write_lock_bh(&sk->sk_callback_lock);
3384	rcu_assign_pointer(sk->sk_wq, &parent->wq);
3385	sk_set_socket(sk, parent);
3386	sk->sk_uid = SOCK_INODE(parent)->i_uid;
3387	write_unlock_bh(&sk->sk_callback_lock);
3388}
3389
3390bool mptcp_finish_join(struct sock *ssk)
3391{
3392	struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
3393	struct mptcp_sock *msk = mptcp_sk(subflow->conn);
3394	struct sock *parent = (void *)msk;
3395	bool ret = true;
3396
3397	pr_debug("msk=%p, subflow=%p", msk, subflow);
3398
3399	/* mptcp socket already closing? */
3400	if (!mptcp_is_fully_established(parent)) {
3401		subflow->reset_reason = MPTCP_RST_EMPTCP;
3402		return false;
3403	}
3404
3405	if (!list_empty(&subflow->node))
3406		goto out;
3407
3408	if (!mptcp_pm_allow_new_subflow(msk))
3409		goto err_prohibited;
3410
3411	/* active connections are already on conn_list.
3412	 * If we can't acquire msk socket lock here, let the release callback
3413	 * handle it
3414	 */
3415	mptcp_data_lock(parent);
3416	if (!sock_owned_by_user(parent)) {
3417		ret = __mptcp_finish_join(msk, ssk);
3418		if (ret) {
3419			sock_hold(ssk);
3420			list_add_tail(&subflow->node, &msk->conn_list);
3421		}
3422	} else {
3423		sock_hold(ssk);
3424		list_add_tail(&subflow->node, &msk->join_list);
3425		__set_bit(MPTCP_FLUSH_JOIN_LIST, &msk->cb_flags);
3426	}
3427	mptcp_data_unlock(parent);
3428
3429	if (!ret) {
3430err_prohibited:
3431		subflow->reset_reason = MPTCP_RST_EPROHIBIT;
3432		return false;
3433	}
3434
3435	subflow->map_seq = READ_ONCE(msk->ack_seq);
3436	WRITE_ONCE(msk->allow_infinite_fallback, false);
3437
3438out:
3439	mptcp_event(MPTCP_EVENT_SUB_ESTABLISHED, msk, ssk, GFP_ATOMIC);
3440	return true;
3441}
3442
3443static void mptcp_shutdown(struct sock *sk, int how)
3444{
3445	pr_debug("sk=%p, how=%d", sk, how);
3446
3447	if ((how & SEND_SHUTDOWN) && mptcp_close_state(sk))
3448		__mptcp_wr_shutdown(sk);
3449}
3450
3451static int mptcp_forward_alloc_get(const struct sock *sk)
3452{
3453	return sk->sk_forward_alloc + mptcp_sk(sk)->rmem_fwd_alloc;
3454}
3455
3456static int mptcp_ioctl_outq(const struct mptcp_sock *msk, u64 v)
3457{
3458	const struct sock *sk = (void *)msk;
3459	u64 delta;
3460
3461	if (sk->sk_state == TCP_LISTEN)
3462		return -EINVAL;
3463
3464	if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
3465		return 0;
3466
3467	delta = msk->write_seq - v;
3468	if (__mptcp_check_fallback(msk) && msk->first) {
3469		struct tcp_sock *tp = tcp_sk(msk->first);
3470
3471		/* the first subflow is disconnected after close - see
3472		 * __mptcp_close_ssk(). tcp_disconnect() moves the write_seq
3473		 * so ignore that status, too.
3474		 */
3475		if (!((1 << msk->first->sk_state) &
3476		      (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_CLOSE)))
3477			delta += READ_ONCE(tp->write_seq) - tp->snd_una;
3478	}
3479	if (delta > INT_MAX)
3480		delta = INT_MAX;
3481
3482	return (int)delta;
3483}
3484
3485static int mptcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
3486{
3487	struct mptcp_sock *msk = mptcp_sk(sk);
3488	bool slow;
3489	int answ;
3490
3491	switch (cmd) {
3492	case SIOCINQ:
3493		if (sk->sk_state == TCP_LISTEN)
3494			return -EINVAL;
3495
3496		lock_sock(sk);
3497		__mptcp_move_skbs(msk);
3498		answ = mptcp_inq_hint(sk);
3499		release_sock(sk);
3500		break;
3501	case SIOCOUTQ:
3502		slow = lock_sock_fast(sk);
3503		answ = mptcp_ioctl_outq(msk, READ_ONCE(msk->snd_una));
3504		unlock_sock_fast(sk, slow);
3505		break;
3506	case SIOCOUTQNSD:
3507		slow = lock_sock_fast(sk);
3508		answ = mptcp_ioctl_outq(msk, msk->snd_nxt);
3509		unlock_sock_fast(sk, slow);
3510		break;
3511	default:
3512		return -ENOIOCTLCMD;
3513	}
3514
3515	return put_user(answ, (int __user *)arg);
3516}
3517
3518static void mptcp_subflow_early_fallback(struct mptcp_sock *msk,
3519					 struct mptcp_subflow_context *subflow)
3520{
3521	subflow->request_mptcp = 0;
3522	__mptcp_do_fallback(msk);
3523}
3524
3525static int mptcp_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
3526{
3527	struct mptcp_subflow_context *subflow;
3528	struct mptcp_sock *msk = mptcp_sk(sk);
3529	struct socket *ssock;
3530	int err = -EINVAL;
3531
3532	ssock = __mptcp_nmpc_socket(msk);
3533	if (!ssock)
3534		return -EINVAL;
3535
3536	mptcp_token_destroy(msk);
3537	inet_sk_state_store(sk, TCP_SYN_SENT);
3538	subflow = mptcp_subflow_ctx(ssock->sk);
3539#ifdef CONFIG_TCP_MD5SIG
3540	/* no MPTCP if MD5SIG is enabled on this socket or we may run out of
3541	 * TCP option space.
3542	 */
3543	if (rcu_access_pointer(tcp_sk(ssock->sk)->md5sig_info))
3544		mptcp_subflow_early_fallback(msk, subflow);
3545#endif
3546	if (subflow->request_mptcp && mptcp_token_new_connect(ssock->sk)) {
3547		MPTCP_INC_STATS(sock_net(ssock->sk), MPTCP_MIB_TOKENFALLBACKINIT);
3548		mptcp_subflow_early_fallback(msk, subflow);
3549	}
3550	if (likely(!__mptcp_check_fallback(msk)))
3551		MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_MPCAPABLEACTIVE);
3552
3553	/* if reaching here via the fastopen/sendmsg path, the caller already
3554	 * acquired the subflow socket lock, too.
3555	 */
3556	if (msk->fastopening)
3557		err = __inet_stream_connect(ssock, uaddr, addr_len, msk->connect_flags, 1);
3558	else
3559		err = inet_stream_connect(ssock, uaddr, addr_len, msk->connect_flags);
3560	inet_sk(sk)->defer_connect = inet_sk(ssock->sk)->defer_connect;
3561
3562	/* on successful connect, the msk state will be moved to established by
3563	 * subflow_finish_connect()
3564	 */
3565	if (unlikely(err && err != -EINPROGRESS)) {
3566		inet_sk_state_store(sk, inet_sk_state_load(ssock->sk));
3567		return err;
3568	}
3569
3570	mptcp_copy_inaddrs(sk, ssock->sk);
3571
3572	/* unblocking connect, mptcp-level inet_stream_connect will error out
3573	 * without changing the socket state, update it here.
3574	 */
3575	if (err == -EINPROGRESS)
3576		sk->sk_socket->state = ssock->state;
3577	return err;
3578}
3579
3580static struct proto mptcp_prot = {
3581	.name		= "MPTCP",
3582	.owner		= THIS_MODULE,
3583	.init		= mptcp_init_sock,
3584	.connect	= mptcp_connect,
3585	.disconnect	= mptcp_disconnect,
3586	.close		= mptcp_close,
3587	.accept		= mptcp_accept,
3588	.setsockopt	= mptcp_setsockopt,
3589	.getsockopt	= mptcp_getsockopt,
3590	.shutdown	= mptcp_shutdown,
3591	.destroy	= mptcp_destroy,
3592	.sendmsg	= mptcp_sendmsg,
3593	.ioctl		= mptcp_ioctl,
3594	.recvmsg	= mptcp_recvmsg,
3595	.release_cb	= mptcp_release_cb,
3596	.hash		= mptcp_hash,
3597	.unhash		= mptcp_unhash,
3598	.get_port	= mptcp_get_port,
3599	.forward_alloc_get	= mptcp_forward_alloc_get,
3600	.sockets_allocated	= &mptcp_sockets_allocated,
3601
3602	.memory_allocated	= &tcp_memory_allocated,
3603	.per_cpu_fw_alloc	= &tcp_memory_per_cpu_fw_alloc,
3604
3605	.memory_pressure	= &tcp_memory_pressure,
3606	.sysctl_wmem_offset	= offsetof(struct net, ipv4.sysctl_tcp_wmem),
3607	.sysctl_rmem_offset	= offsetof(struct net, ipv4.sysctl_tcp_rmem),
3608	.sysctl_mem	= sysctl_tcp_mem,
3609	.obj_size	= sizeof(struct mptcp_sock),
3610	.slab_flags	= SLAB_TYPESAFE_BY_RCU,
3611	.no_autobind	= true,
3612};
3613
3614static int mptcp_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
3615{
3616	struct mptcp_sock *msk = mptcp_sk(sock->sk);
3617	struct socket *ssock;
3618	int err;
3619
3620	lock_sock(sock->sk);
3621	ssock = __mptcp_nmpc_socket(msk);
3622	if (!ssock) {
3623		err = -EINVAL;
3624		goto unlock;
3625	}
3626
3627	err = ssock->ops->bind(ssock, uaddr, addr_len);
3628	if (!err)
3629		mptcp_copy_inaddrs(sock->sk, ssock->sk);
3630
3631unlock:
3632	release_sock(sock->sk);
3633	return err;
3634}
3635
3636static int mptcp_stream_connect(struct socket *sock, struct sockaddr *uaddr,
3637				int addr_len, int flags)
3638{
3639	int ret;
3640
3641	lock_sock(sock->sk);
3642	mptcp_sk(sock->sk)->connect_flags = flags;
3643	ret = __inet_stream_connect(sock, uaddr, addr_len, flags, 0);
3644	release_sock(sock->sk);
3645	return ret;
3646}
3647
3648static int mptcp_listen(struct socket *sock, int backlog)
3649{
3650	struct mptcp_sock *msk = mptcp_sk(sock->sk);
3651	struct socket *ssock;
3652	int err;
3653
3654	pr_debug("msk=%p", msk);
3655
3656	lock_sock(sock->sk);
3657	ssock = __mptcp_nmpc_socket(msk);
3658	if (!ssock) {
3659		err = -EINVAL;
3660		goto unlock;
3661	}
3662
3663	mptcp_token_destroy(msk);
3664	inet_sk_state_store(sock->sk, TCP_LISTEN);
3665	sock_set_flag(sock->sk, SOCK_RCU_FREE);
3666
3667	err = ssock->ops->listen(ssock, backlog);
3668	inet_sk_state_store(sock->sk, inet_sk_state_load(ssock->sk));
3669	if (!err)
3670		mptcp_copy_inaddrs(sock->sk, ssock->sk);
3671
3672	mptcp_event_pm_listener(ssock->sk, MPTCP_EVENT_LISTENER_CREATED);
3673
3674unlock:
3675	release_sock(sock->sk);
3676	return err;
3677}
3678
3679static int mptcp_stream_accept(struct socket *sock, struct socket *newsock,
3680			       int flags, bool kern)
3681{
3682	struct mptcp_sock *msk = mptcp_sk(sock->sk);
3683	struct socket *ssock;
3684	int err;
3685
3686	pr_debug("msk=%p", msk);
3687
3688	ssock = __mptcp_nmpc_socket(msk);
3689	if (!ssock)
3690		return -EINVAL;
3691
3692	err = ssock->ops->accept(sock, newsock, flags, kern);
3693	if (err == 0 && !mptcp_is_tcpsk(newsock->sk)) {
3694		struct mptcp_sock *msk = mptcp_sk(newsock->sk);
3695		struct mptcp_subflow_context *subflow;
3696		struct sock *newsk = newsock->sk;
3697
3698		set_bit(SOCK_CUSTOM_SOCKOPT, &newsock->flags);
3699
3700		lock_sock(newsk);
3701
3702		/* PM/worker can now acquire the first subflow socket
3703		 * lock without racing with listener queue cleanup,
3704		 * we can notify it, if needed.
3705		 *
3706		 * Even if remote has reset the initial subflow by now
3707		 * the refcnt is still at least one.
3708		 */
3709		subflow = mptcp_subflow_ctx(msk->first);
3710		list_add(&subflow->node, &msk->conn_list);
3711		sock_hold(msk->first);
3712		if (mptcp_is_fully_established(newsk))
3713			mptcp_pm_fully_established(msk, msk->first, GFP_KERNEL);
3714
3715		mptcp_rcv_space_init(msk, msk->first);
3716		mptcp_propagate_sndbuf(newsk, msk->first);
3717
3718		/* set ssk->sk_socket of accept()ed flows to mptcp socket.
3719		 * This is needed so NOSPACE flag can be set from tcp stack.
3720		 */
3721		mptcp_for_each_subflow(msk, subflow) {
3722			struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
3723
3724			if (!ssk->sk_socket)
3725				mptcp_sock_graft(ssk, newsock);
3726		}
3727		release_sock(newsk);
3728	}
3729
3730	return err;
3731}
3732
3733static __poll_t mptcp_check_writeable(struct mptcp_sock *msk)
3734{
3735	struct sock *sk = (struct sock *)msk;
3736
3737	if (unlikely(sk->sk_shutdown & SEND_SHUTDOWN))
3738		return EPOLLOUT | EPOLLWRNORM;
3739
3740	if (sk_stream_is_writeable(sk))
3741		return EPOLLOUT | EPOLLWRNORM;
3742
3743	mptcp_set_nospace(sk);
3744	smp_mb__after_atomic(); /* msk->flags is changed by write_space cb */
3745	if (sk_stream_is_writeable(sk))
3746		return EPOLLOUT | EPOLLWRNORM;
3747
3748	return 0;
3749}
3750
3751static __poll_t mptcp_poll(struct file *file, struct socket *sock,
3752			   struct poll_table_struct *wait)
3753{
3754	struct sock *sk = sock->sk;
3755	struct mptcp_sock *msk;
3756	__poll_t mask = 0;
3757	int state;
3758
3759	msk = mptcp_sk(sk);
3760	sock_poll_wait(file, sock, wait);
3761
3762	state = inet_sk_state_load(sk);
3763	pr_debug("msk=%p state=%d flags=%lx", msk, state, msk->flags);
3764	if (state == TCP_LISTEN) {
3765		if (WARN_ON_ONCE(!msk->subflow || !msk->subflow->sk))
3766			return 0;
3767
3768		return inet_csk_listen_poll(msk->subflow->sk);
3769	}
3770
3771	if (state != TCP_SYN_SENT && state != TCP_SYN_RECV) {
3772		mask |= mptcp_check_readable(msk);
3773		mask |= mptcp_check_writeable(msk);
3774	} else if (state == TCP_SYN_SENT && inet_sk(sk)->defer_connect) {
3775		/* cf tcp_poll() note about TFO */
3776		mask |= EPOLLOUT | EPOLLWRNORM;
3777	}
3778	if (sk->sk_shutdown == SHUTDOWN_MASK || state == TCP_CLOSE)
3779		mask |= EPOLLHUP;
3780	if (sk->sk_shutdown & RCV_SHUTDOWN)
3781		mask |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP;
3782
3783	/* This barrier is coupled with smp_wmb() in __mptcp_error_report() */
3784	smp_rmb();
3785	if (sk->sk_err)
3786		mask |= EPOLLERR;
3787
3788	return mask;
3789}
3790
3791static const struct proto_ops mptcp_stream_ops = {
3792	.family		   = PF_INET,
3793	.owner		   = THIS_MODULE,
3794	.release	   = inet_release,
3795	.bind		   = mptcp_bind,
3796	.connect	   = mptcp_stream_connect,
3797	.socketpair	   = sock_no_socketpair,
3798	.accept		   = mptcp_stream_accept,
3799	.getname	   = inet_getname,
3800	.poll		   = mptcp_poll,
3801	.ioctl		   = inet_ioctl,
3802	.gettstamp	   = sock_gettstamp,
3803	.listen		   = mptcp_listen,
3804	.shutdown	   = inet_shutdown,
3805	.setsockopt	   = sock_common_setsockopt,
3806	.getsockopt	   = sock_common_getsockopt,
3807	.sendmsg	   = inet_sendmsg,
3808	.recvmsg	   = inet_recvmsg,
3809	.mmap		   = sock_no_mmap,
3810	.sendpage	   = inet_sendpage,
3811};
3812
3813static struct inet_protosw mptcp_protosw = {
3814	.type		= SOCK_STREAM,
3815	.protocol	= IPPROTO_MPTCP,
3816	.prot		= &mptcp_prot,
3817	.ops		= &mptcp_stream_ops,
3818	.flags		= INET_PROTOSW_ICSK,
3819};
3820
3821static int mptcp_napi_poll(struct napi_struct *napi, int budget)
3822{
3823	struct mptcp_delegated_action *delegated;
3824	struct mptcp_subflow_context *subflow;
3825	int work_done = 0;
3826
3827	delegated = container_of(napi, struct mptcp_delegated_action, napi);
3828	while ((subflow = mptcp_subflow_delegated_next(delegated)) != NULL) {
3829		struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
3830
3831		bh_lock_sock_nested(ssk);
3832		if (!sock_owned_by_user(ssk) &&
3833		    mptcp_subflow_has_delegated_action(subflow))
3834			mptcp_subflow_process_delegated(ssk);
3835		/* ... elsewhere tcp_release_cb_override already processed
3836		 * the action or will do at next release_sock().
3837		 * In both case must dequeue the subflow here - on the same
3838		 * CPU that scheduled it.
3839		 */
3840		bh_unlock_sock(ssk);
3841		sock_put(ssk);
3842
3843		if (++work_done == budget)
3844			return budget;
3845	}
3846
3847	/* always provide a 0 'work_done' argument, so that napi_complete_done
3848	 * will not try accessing the NULL napi->dev ptr
3849	 */
3850	napi_complete_done(napi, 0);
3851	return work_done;
3852}
3853
3854void __init mptcp_proto_init(void)
3855{
3856	struct mptcp_delegated_action *delegated;
3857	int cpu;
3858
3859	mptcp_prot.h.hashinfo = tcp_prot.h.hashinfo;
3860
3861	if (percpu_counter_init(&mptcp_sockets_allocated, 0, GFP_KERNEL))
3862		panic("Failed to allocate MPTCP pcpu counter\n");
3863
3864	init_dummy_netdev(&mptcp_napi_dev);
3865	for_each_possible_cpu(cpu) {
3866		delegated = per_cpu_ptr(&mptcp_delegated_actions, cpu);
3867		INIT_LIST_HEAD(&delegated->head);
3868		netif_napi_add_tx(&mptcp_napi_dev, &delegated->napi,
3869				  mptcp_napi_poll);
3870		napi_enable(&delegated->napi);
3871	}
3872
3873	mptcp_subflow_init();
3874	mptcp_pm_init();
3875	mptcp_token_init();
3876
3877	if (proto_register(&mptcp_prot, 1) != 0)
3878		panic("Failed to register MPTCP proto.\n");
3879
3880	inet_register_protosw(&mptcp_protosw);
3881
3882	BUILD_BUG_ON(sizeof(struct mptcp_skb_cb) > sizeof_field(struct sk_buff, cb));
3883}
3884
3885#if IS_ENABLED(CONFIG_MPTCP_IPV6)
3886static const struct proto_ops mptcp_v6_stream_ops = {
3887	.family		   = PF_INET6,
3888	.owner		   = THIS_MODULE,
3889	.release	   = inet6_release,
3890	.bind		   = mptcp_bind,
3891	.connect	   = mptcp_stream_connect,
3892	.socketpair	   = sock_no_socketpair,
3893	.accept		   = mptcp_stream_accept,
3894	.getname	   = inet6_getname,
3895	.poll		   = mptcp_poll,
3896	.ioctl		   = inet6_ioctl,
3897	.gettstamp	   = sock_gettstamp,
3898	.listen		   = mptcp_listen,
3899	.shutdown	   = inet_shutdown,
3900	.setsockopt	   = sock_common_setsockopt,
3901	.getsockopt	   = sock_common_getsockopt,
3902	.sendmsg	   = inet6_sendmsg,
3903	.recvmsg	   = inet6_recvmsg,
3904	.mmap		   = sock_no_mmap,
3905	.sendpage	   = inet_sendpage,
3906#ifdef CONFIG_COMPAT
3907	.compat_ioctl	   = inet6_compat_ioctl,
3908#endif
3909};
3910
3911static struct proto mptcp_v6_prot;
3912
3913static struct inet_protosw mptcp_v6_protosw = {
3914	.type		= SOCK_STREAM,
3915	.protocol	= IPPROTO_MPTCP,
3916	.prot		= &mptcp_v6_prot,
3917	.ops		= &mptcp_v6_stream_ops,
3918	.flags		= INET_PROTOSW_ICSK,
3919};
3920
3921int __init mptcp_proto_v6_init(void)
3922{
3923	int err;
3924
3925	mptcp_v6_prot = mptcp_prot;
3926	strcpy(mptcp_v6_prot.name, "MPTCPv6");
3927	mptcp_v6_prot.slab = NULL;
3928	mptcp_v6_prot.obj_size = sizeof(struct mptcp6_sock);
3929
3930	err = proto_register(&mptcp_v6_prot, 1);
3931	if (err)
3932		return err;
3933
3934	err = inet6_register_protosw(&mptcp_v6_protosw);
3935	if (err)
3936		proto_unregister(&mptcp_v6_prot);
3937
3938	return err;
3939}
3940#endif