cachepc-linux

Fork of AMDESE/linux with modifications for CachePC side-channel attack
git clone https://git.sinitax.com/sinitax/cachepc-linux
Log | Files | Refs | README | LICENSE | sfeed.txt

protocol.c (98952B)


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