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