1 // SPDX-License-Identifier: GPL-2.0
4 * Copyright (c) 2017 - 2019, Intel Corporation.
7 #define pr_fmt(fmt) "MPTCP: " fmt
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>
15 #include <net/inet_common.h>
16 #include <net/inet_hashtables.h>
17 #include <net/protocol.h>
19 #include <net/tcp_states.h>
20 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
21 #include <net/transp_v6.h>
23 #include <net/mptcp.h>
27 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
29 struct mptcp_sock msk;
40 #define MPTCP_SKB_CB(__skb) ((struct mptcp_skb_cb *)&((__skb)->cb[0]))
42 static struct percpu_counter mptcp_sockets_allocated;
44 /* If msk has an initial subflow socket, and the MP_CAPABLE handshake has not
45 * completed yet or has failed, return the subflow socket.
46 * Otherwise return NULL.
48 static struct socket *__mptcp_nmpc_socket(const struct mptcp_sock *msk)
50 if (!msk->subflow || READ_ONCE(msk->can_ack))
56 static bool mptcp_is_tcpsk(struct sock *sk)
58 struct socket *sock = sk->sk_socket;
60 if (unlikely(sk->sk_prot == &tcp_prot)) {
61 /* we are being invoked after mptcp_accept() has
62 * accepted a non-mp-capable flow: sk is a tcp_sk,
65 * Hand the socket over to tcp so all further socket ops
68 sock->ops = &inet_stream_ops;
70 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
71 } else if (unlikely(sk->sk_prot == &tcpv6_prot)) {
72 sock->ops = &inet6_stream_ops;
80 static struct sock *__mptcp_tcp_fallback(struct mptcp_sock *msk)
82 sock_owned_by_me((const struct sock *)msk);
84 if (likely(!__mptcp_check_fallback(msk)))
90 static int __mptcp_socket_create(struct mptcp_sock *msk)
92 struct mptcp_subflow_context *subflow;
93 struct sock *sk = (struct sock *)msk;
97 err = mptcp_subflow_create_socket(sk, &ssock);
101 msk->first = ssock->sk;
102 msk->subflow = ssock;
103 subflow = mptcp_subflow_ctx(ssock->sk);
104 list_add(&subflow->node, &msk->conn_list);
105 subflow->request_mptcp = 1;
107 /* accept() will wait on first subflow sk_wq, and we always wakes up
110 RCU_INIT_POINTER(msk->first->sk_wq, &sk->sk_socket->wq);
115 static void mptcp_drop(struct sock *sk, struct sk_buff *skb)
117 sk_drops_add(sk, skb);
121 static bool mptcp_try_coalesce(struct sock *sk, struct sk_buff *to,
122 struct sk_buff *from)
127 if (MPTCP_SKB_CB(from)->offset ||
128 !skb_try_coalesce(to, from, &fragstolen, &delta))
131 pr_debug("colesced seq %llx into %llx new len %d new end seq %llx",
132 MPTCP_SKB_CB(from)->map_seq, MPTCP_SKB_CB(to)->map_seq,
133 to->len, MPTCP_SKB_CB(from)->end_seq);
134 MPTCP_SKB_CB(to)->end_seq = MPTCP_SKB_CB(from)->end_seq;
135 kfree_skb_partial(from, fragstolen);
136 atomic_add(delta, &sk->sk_rmem_alloc);
137 sk_mem_charge(sk, delta);
141 static bool mptcp_ooo_try_coalesce(struct mptcp_sock *msk, struct sk_buff *to,
142 struct sk_buff *from)
144 if (MPTCP_SKB_CB(from)->map_seq != MPTCP_SKB_CB(to)->end_seq)
147 return mptcp_try_coalesce((struct sock *)msk, to, from);
150 /* "inspired" by tcp_data_queue_ofo(), main differences:
152 * - don't cope with sacks
154 static void mptcp_data_queue_ofo(struct mptcp_sock *msk, struct sk_buff *skb)
156 struct sock *sk = (struct sock *)msk;
157 struct rb_node **p, *parent;
158 u64 seq, end_seq, max_seq;
159 struct sk_buff *skb1;
162 seq = MPTCP_SKB_CB(skb)->map_seq;
163 end_seq = MPTCP_SKB_CB(skb)->end_seq;
164 space = tcp_space(sk);
165 max_seq = space > 0 ? space + msk->ack_seq : msk->ack_seq;
167 pr_debug("msk=%p seq=%llx limit=%llx empty=%d", msk, seq, max_seq,
168 RB_EMPTY_ROOT(&msk->out_of_order_queue));
169 if (after64(seq, max_seq)) {
172 MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_NODSSWINDOW);
176 p = &msk->out_of_order_queue.rb_node;
177 MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOQUEUE);
178 if (RB_EMPTY_ROOT(&msk->out_of_order_queue)) {
179 rb_link_node(&skb->rbnode, NULL, p);
180 rb_insert_color(&skb->rbnode, &msk->out_of_order_queue);
181 msk->ooo_last_skb = skb;
185 /* with 2 subflows, adding at end of ooo queue is quite likely
186 * Use of ooo_last_skb avoids the O(Log(N)) rbtree lookup.
188 if (mptcp_ooo_try_coalesce(msk, msk->ooo_last_skb, skb)) {
189 MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOMERGE);
190 MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOQUEUETAIL);
194 /* Can avoid an rbtree lookup if we are adding skb after ooo_last_skb */
195 if (!before64(seq, MPTCP_SKB_CB(msk->ooo_last_skb)->end_seq)) {
196 MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOQUEUETAIL);
197 parent = &msk->ooo_last_skb->rbnode;
198 p = &parent->rb_right;
202 /* Find place to insert this segment. Handle overlaps on the way. */
206 skb1 = rb_to_skb(parent);
207 if (before64(seq, MPTCP_SKB_CB(skb1)->map_seq)) {
208 p = &parent->rb_left;
211 if (before64(seq, MPTCP_SKB_CB(skb1)->end_seq)) {
212 if (!after64(end_seq, MPTCP_SKB_CB(skb1)->end_seq)) {
213 /* All the bits are present. Drop. */
215 MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
218 if (after64(seq, MPTCP_SKB_CB(skb1)->map_seq)) {
222 * continue traversing
225 /* skb's seq == skb1's seq and skb covers skb1.
226 * Replace skb1 with skb.
228 rb_replace_node(&skb1->rbnode, &skb->rbnode,
229 &msk->out_of_order_queue);
230 mptcp_drop(sk, skb1);
231 MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
234 } else if (mptcp_ooo_try_coalesce(msk, skb1, skb)) {
235 MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_OFOMERGE);
238 p = &parent->rb_right;
242 /* Insert segment into RB tree. */
243 rb_link_node(&skb->rbnode, parent, p);
244 rb_insert_color(&skb->rbnode, &msk->out_of_order_queue);
247 /* Remove other segments covered by skb. */
248 while ((skb1 = skb_rb_next(skb)) != NULL) {
249 if (before64(end_seq, MPTCP_SKB_CB(skb1)->end_seq))
251 rb_erase(&skb1->rbnode, &msk->out_of_order_queue);
252 mptcp_drop(sk, skb1);
253 MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
255 /* If there is no skb after us, we are the last_skb ! */
257 msk->ooo_last_skb = skb;
261 skb_set_owner_r(skb, sk);
264 static bool __mptcp_move_skb(struct mptcp_sock *msk, struct sock *ssk,
265 struct sk_buff *skb, unsigned int offset,
268 struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
269 struct sock *sk = (struct sock *)msk;
270 struct sk_buff *tail;
272 __skb_unlink(skb, &ssk->sk_receive_queue);
277 /* try to fetch required memory from subflow */
278 if (!sk_rmem_schedule(sk, skb, skb->truesize)) {
279 int amount = sk_mem_pages(skb->truesize) << SK_MEM_QUANTUM_SHIFT;
281 if (ssk->sk_forward_alloc < amount)
284 ssk->sk_forward_alloc -= amount;
285 sk->sk_forward_alloc += amount;
288 /* the skb map_seq accounts for the skb offset:
289 * mptcp_subflow_get_mapped_dsn() is based on the current tp->copied_seq
292 MPTCP_SKB_CB(skb)->map_seq = mptcp_subflow_get_mapped_dsn(subflow);
293 MPTCP_SKB_CB(skb)->end_seq = MPTCP_SKB_CB(skb)->map_seq + copy_len;
294 MPTCP_SKB_CB(skb)->offset = offset;
296 if (MPTCP_SKB_CB(skb)->map_seq == msk->ack_seq) {
298 WRITE_ONCE(msk->ack_seq, msk->ack_seq + copy_len);
299 tail = skb_peek_tail(&sk->sk_receive_queue);
300 if (tail && mptcp_try_coalesce(sk, tail, skb))
303 skb_set_owner_r(skb, sk);
304 __skb_queue_tail(&sk->sk_receive_queue, skb);
306 } else if (after64(MPTCP_SKB_CB(skb)->map_seq, msk->ack_seq)) {
307 mptcp_data_queue_ofo(msk, skb);
311 /* old data, keep it simple and drop the whole pkt, sender
312 * will retransmit as needed, if needed.
314 MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
320 static void mptcp_stop_timer(struct sock *sk)
322 struct inet_connection_sock *icsk = inet_csk(sk);
324 sk_stop_timer(sk, &icsk->icsk_retransmit_timer);
325 mptcp_sk(sk)->timer_ival = 0;
328 static void mptcp_check_data_fin_ack(struct sock *sk)
330 struct mptcp_sock *msk = mptcp_sk(sk);
332 if (__mptcp_check_fallback(msk))
335 /* Look for an acknowledged DATA_FIN */
336 if (((1 << sk->sk_state) &
337 (TCPF_FIN_WAIT1 | TCPF_CLOSING | TCPF_LAST_ACK)) &&
338 msk->write_seq == atomic64_read(&msk->snd_una)) {
339 mptcp_stop_timer(sk);
341 WRITE_ONCE(msk->snd_data_fin_enable, 0);
343 switch (sk->sk_state) {
345 inet_sk_state_store(sk, TCP_FIN_WAIT2);
346 sk->sk_state_change(sk);
350 inet_sk_state_store(sk, TCP_CLOSE);
351 sk->sk_state_change(sk);
355 if (sk->sk_shutdown == SHUTDOWN_MASK ||
356 sk->sk_state == TCP_CLOSE)
357 sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
359 sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
363 static bool mptcp_pending_data_fin(struct sock *sk, u64 *seq)
365 struct mptcp_sock *msk = mptcp_sk(sk);
367 if (READ_ONCE(msk->rcv_data_fin) &&
368 ((1 << sk->sk_state) &
369 (TCPF_ESTABLISHED | TCPF_FIN_WAIT1 | TCPF_FIN_WAIT2))) {
370 u64 rcv_data_fin_seq = READ_ONCE(msk->rcv_data_fin_seq);
372 if (msk->ack_seq == rcv_data_fin_seq) {
374 *seq = rcv_data_fin_seq;
383 static void mptcp_set_timeout(const struct sock *sk, const struct sock *ssk)
385 long tout = ssk && inet_csk(ssk)->icsk_pending ?
386 inet_csk(ssk)->icsk_timeout - jiffies : 0;
389 tout = mptcp_sk(sk)->timer_ival;
390 mptcp_sk(sk)->timer_ival = tout > 0 ? tout : TCP_RTO_MIN;
393 static void mptcp_check_data_fin(struct sock *sk)
395 struct mptcp_sock *msk = mptcp_sk(sk);
396 u64 rcv_data_fin_seq;
398 if (__mptcp_check_fallback(msk) || !msk->first)
401 /* Need to ack a DATA_FIN received from a peer while this side
402 * of the connection is in ESTABLISHED, FIN_WAIT1, or FIN_WAIT2.
403 * msk->rcv_data_fin was set when parsing the incoming options
404 * at the subflow level and the msk lock was not held, so this
405 * is the first opportunity to act on the DATA_FIN and change
408 * If we are caught up to the sequence number of the incoming
409 * DATA_FIN, send the DATA_ACK now and do state transition. If
410 * not caught up, do nothing and let the recv code send DATA_ACK
414 if (mptcp_pending_data_fin(sk, &rcv_data_fin_seq)) {
415 struct mptcp_subflow_context *subflow;
417 WRITE_ONCE(msk->ack_seq, msk->ack_seq + 1);
418 WRITE_ONCE(msk->rcv_data_fin, 0);
420 sk->sk_shutdown |= RCV_SHUTDOWN;
421 smp_mb__before_atomic(); /* SHUTDOWN must be visible first */
422 set_bit(MPTCP_DATA_READY, &msk->flags);
424 switch (sk->sk_state) {
425 case TCP_ESTABLISHED:
426 inet_sk_state_store(sk, TCP_CLOSE_WAIT);
429 inet_sk_state_store(sk, TCP_CLOSING);
432 inet_sk_state_store(sk, TCP_CLOSE);
433 // @@ Close subflows now?
436 /* Other states not expected */
441 mptcp_set_timeout(sk, NULL);
442 mptcp_for_each_subflow(msk, subflow) {
443 struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
450 sk->sk_state_change(sk);
452 if (sk->sk_shutdown == SHUTDOWN_MASK ||
453 sk->sk_state == TCP_CLOSE)
454 sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
456 sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
460 static bool __mptcp_move_skbs_from_subflow(struct mptcp_sock *msk,
464 struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
465 struct sock *sk = (struct sock *)msk;
466 unsigned int moved = 0;
467 bool more_data_avail;
472 pr_debug("msk=%p ssk=%p", msk, ssk);
474 old_copied_seq = tp->copied_seq;
476 u32 map_remaining, offset;
477 u32 seq = tp->copied_seq;
481 /* try to move as much data as available */
482 map_remaining = subflow->map_data_len -
483 mptcp_subflow_get_map_offset(subflow);
485 skb = skb_peek(&ssk->sk_receive_queue);
487 /* if no data is found, a racing workqueue/recvmsg
488 * already processed the new data, stop here or we
489 * can enter an infinite loop
496 if (__mptcp_check_fallback(msk)) {
497 /* if we are running under the workqueue, TCP could have
498 * collapsed skbs between dummy map creation and now
499 * be sure to adjust the size
501 map_remaining = skb->len;
502 subflow->map_data_len = skb->len;
505 offset = seq - TCP_SKB_CB(skb)->seq;
506 fin = TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN;
512 if (offset < skb->len) {
513 size_t len = skb->len - offset;
518 if (__mptcp_move_skb(msk, ssk, skb, offset, len))
522 if (WARN_ON_ONCE(map_remaining < len))
526 sk_eat_skb(ssk, skb);
530 WRITE_ONCE(tp->copied_seq, seq);
531 more_data_avail = mptcp_subflow_data_available(ssk);
533 if (atomic_read(&sk->sk_rmem_alloc) > READ_ONCE(sk->sk_rcvbuf)) {
537 } while (more_data_avail);
540 if (tp->copied_seq != old_copied_seq)
541 tcp_cleanup_rbuf(ssk, 1);
546 static bool mptcp_ofo_queue(struct mptcp_sock *msk)
548 struct sock *sk = (struct sock *)msk;
549 struct sk_buff *skb, *tail;
554 p = rb_first(&msk->out_of_order_queue);
555 pr_debug("msk=%p empty=%d", msk, RB_EMPTY_ROOT(&msk->out_of_order_queue));
558 if (after64(MPTCP_SKB_CB(skb)->map_seq, msk->ack_seq))
562 rb_erase(&skb->rbnode, &msk->out_of_order_queue);
564 if (unlikely(!after64(MPTCP_SKB_CB(skb)->end_seq,
567 MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_DUPDATA);
571 end_seq = MPTCP_SKB_CB(skb)->end_seq;
572 tail = skb_peek_tail(&sk->sk_receive_queue);
573 if (!tail || !mptcp_ooo_try_coalesce(msk, tail, skb)) {
574 int delta = msk->ack_seq - MPTCP_SKB_CB(skb)->map_seq;
576 /* skip overlapping data, if any */
577 pr_debug("uncoalesced seq=%llx ack seq=%llx delta=%d",
578 MPTCP_SKB_CB(skb)->map_seq, msk->ack_seq,
580 MPTCP_SKB_CB(skb)->offset += delta;
581 __skb_queue_tail(&sk->sk_receive_queue, skb);
583 msk->ack_seq = end_seq;
589 /* In most cases we will be able to lock the mptcp socket. If its already
590 * owned, we need to defer to the work queue to avoid ABBA deadlock.
592 static bool move_skbs_to_msk(struct mptcp_sock *msk, struct sock *ssk)
594 struct sock *sk = (struct sock *)msk;
595 unsigned int moved = 0;
597 if (READ_ONCE(sk->sk_lock.owned))
600 if (unlikely(!spin_trylock_bh(&sk->sk_lock.slock)))
603 /* must re-check after taking the lock */
604 if (!READ_ONCE(sk->sk_lock.owned)) {
605 __mptcp_move_skbs_from_subflow(msk, ssk, &moved);
606 mptcp_ofo_queue(msk);
608 /* If the moves have caught up with the DATA_FIN sequence number
609 * it's time to ack the DATA_FIN and change socket state, but
610 * this is not a good place to change state. Let the workqueue
613 if (mptcp_pending_data_fin(sk, NULL) &&
614 schedule_work(&msk->work))
618 spin_unlock_bh(&sk->sk_lock.slock);
623 void mptcp_data_ready(struct sock *sk, struct sock *ssk)
625 struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(ssk);
626 struct mptcp_sock *msk = mptcp_sk(sk);
629 /* move_skbs_to_msk below can legitly clear the data_avail flag,
630 * but we will need later to properly woke the reader, cache its
633 wake = subflow->data_avail == MPTCP_SUBFLOW_DATA_AVAIL;
635 set_bit(MPTCP_DATA_READY, &msk->flags);
637 if (atomic_read(&sk->sk_rmem_alloc) < READ_ONCE(sk->sk_rcvbuf) &&
638 move_skbs_to_msk(msk, ssk))
641 /* don't schedule if mptcp sk is (still) over limit */
642 if (atomic_read(&sk->sk_rmem_alloc) > READ_ONCE(sk->sk_rcvbuf))
645 /* mptcp socket is owned, release_cb should retry */
646 if (!test_and_set_bit(TCP_DELACK_TIMER_DEFERRED,
647 &sk->sk_tsq_flags)) {
650 /* need to try again, its possible release_cb() has already
651 * been called after the test_and_set_bit() above.
653 move_skbs_to_msk(msk, ssk);
657 sk->sk_data_ready(sk);
660 static void __mptcp_flush_join_list(struct mptcp_sock *msk)
662 if (likely(list_empty(&msk->join_list)))
665 spin_lock_bh(&msk->join_list_lock);
666 list_splice_tail_init(&msk->join_list, &msk->conn_list);
667 spin_unlock_bh(&msk->join_list_lock);
670 static bool mptcp_timer_pending(struct sock *sk)
672 return timer_pending(&inet_csk(sk)->icsk_retransmit_timer);
675 static void mptcp_reset_timer(struct sock *sk)
677 struct inet_connection_sock *icsk = inet_csk(sk);
680 /* should never be called with mptcp level timer cleared */
681 tout = READ_ONCE(mptcp_sk(sk)->timer_ival);
682 if (WARN_ON_ONCE(!tout))
684 sk_reset_timer(sk, &icsk->icsk_retransmit_timer, jiffies + tout);
687 void mptcp_data_acked(struct sock *sk)
689 mptcp_reset_timer(sk);
691 if ((!test_bit(MPTCP_SEND_SPACE, &mptcp_sk(sk)->flags) ||
692 (inet_sk_state_load(sk) != TCP_ESTABLISHED)) &&
693 schedule_work(&mptcp_sk(sk)->work))
697 void mptcp_subflow_eof(struct sock *sk)
699 struct mptcp_sock *msk = mptcp_sk(sk);
701 if (!test_and_set_bit(MPTCP_WORK_EOF, &msk->flags) &&
702 schedule_work(&msk->work))
706 static void mptcp_check_for_eof(struct mptcp_sock *msk)
708 struct mptcp_subflow_context *subflow;
709 struct sock *sk = (struct sock *)msk;
712 mptcp_for_each_subflow(msk, subflow)
713 receivers += !subflow->rx_eof;
715 if (!receivers && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
716 /* hopefully temporary hack: propagate shutdown status
717 * to msk, when all subflows agree on it
719 sk->sk_shutdown |= RCV_SHUTDOWN;
721 smp_mb__before_atomic(); /* SHUTDOWN must be visible first */
722 set_bit(MPTCP_DATA_READY, &msk->flags);
723 sk->sk_data_ready(sk);
727 static bool mptcp_ext_cache_refill(struct mptcp_sock *msk)
729 const struct sock *sk = (const struct sock *)msk;
731 if (!msk->cached_ext)
732 msk->cached_ext = __skb_ext_alloc(sk->sk_allocation);
734 return !!msk->cached_ext;
737 static struct sock *mptcp_subflow_recv_lookup(const struct mptcp_sock *msk)
739 struct mptcp_subflow_context *subflow;
740 struct sock *sk = (struct sock *)msk;
742 sock_owned_by_me(sk);
744 mptcp_for_each_subflow(msk, subflow) {
745 if (subflow->data_avail)
746 return mptcp_subflow_tcp_sock(subflow);
752 static bool mptcp_skb_can_collapse_to(u64 write_seq,
753 const struct sk_buff *skb,
754 const struct mptcp_ext *mpext)
756 if (!tcp_skb_can_collapse_to(skb))
759 /* can collapse only if MPTCP level sequence is in order */
760 return mpext && mpext->data_seq + mpext->data_len == write_seq;
763 /* we can append data to the given data frag if:
764 * - there is space available in the backing page_frag
765 * - the data frag tail matches the current page_frag free offset
766 * - the data frag end sequence number matches the current write seq
768 static bool mptcp_frag_can_collapse_to(const struct mptcp_sock *msk,
769 const struct page_frag *pfrag,
770 const struct mptcp_data_frag *df)
772 return df && pfrag->page == df->page &&
773 pfrag->offset == (df->offset + df->data_len) &&
774 df->data_seq + df->data_len == msk->write_seq;
777 static void dfrag_uncharge(struct sock *sk, int len)
779 sk_mem_uncharge(sk, len);
780 sk_wmem_queued_add(sk, -len);
783 static void dfrag_clear(struct sock *sk, struct mptcp_data_frag *dfrag)
785 int len = dfrag->data_len + dfrag->overhead;
787 list_del(&dfrag->list);
788 dfrag_uncharge(sk, len);
789 put_page(dfrag->page);
792 static bool mptcp_is_writeable(struct mptcp_sock *msk)
794 struct mptcp_subflow_context *subflow;
796 if (!sk_stream_is_writeable((struct sock *)msk))
799 mptcp_for_each_subflow(msk, subflow) {
800 if (sk_stream_is_writeable(subflow->tcp_sock))
806 static void mptcp_clean_una(struct sock *sk)
808 struct mptcp_sock *msk = mptcp_sk(sk);
809 struct mptcp_data_frag *dtmp, *dfrag;
810 bool cleaned = false;
813 /* on fallback we just need to ignore snd_una, as this is really
816 if (__mptcp_check_fallback(msk))
817 atomic64_set(&msk->snd_una, msk->write_seq);
818 snd_una = atomic64_read(&msk->snd_una);
820 list_for_each_entry_safe(dfrag, dtmp, &msk->rtx_queue, list) {
821 if (after64(dfrag->data_seq + dfrag->data_len, snd_una))
824 dfrag_clear(sk, dfrag);
828 dfrag = mptcp_rtx_head(sk);
829 if (dfrag && after64(snd_una, dfrag->data_seq)) {
830 u64 delta = snd_una - dfrag->data_seq;
832 if (WARN_ON_ONCE(delta > dfrag->data_len))
835 dfrag->data_seq += delta;
836 dfrag->offset += delta;
837 dfrag->data_len -= delta;
839 dfrag_uncharge(sk, delta);
845 sk_mem_reclaim_partial(sk);
847 /* Only wake up writers if a subflow is ready */
848 if (mptcp_is_writeable(msk)) {
849 set_bit(MPTCP_SEND_SPACE, &mptcp_sk(sk)->flags);
850 smp_mb__after_atomic();
852 /* set SEND_SPACE before sk_stream_write_space clears
855 sk_stream_write_space(sk);
860 /* ensure we get enough memory for the frag hdr, beyond some minimal amount of
863 static bool mptcp_page_frag_refill(struct sock *sk, struct page_frag *pfrag)
865 if (likely(skb_page_frag_refill(32U + sizeof(struct mptcp_data_frag),
866 pfrag, sk->sk_allocation)))
869 sk->sk_prot->enter_memory_pressure(sk);
870 sk_stream_moderate_sndbuf(sk);
874 static struct mptcp_data_frag *
875 mptcp_carve_data_frag(const struct mptcp_sock *msk, struct page_frag *pfrag,
878 int offset = ALIGN(orig_offset, sizeof(long));
879 struct mptcp_data_frag *dfrag;
881 dfrag = (struct mptcp_data_frag *)(page_to_virt(pfrag->page) + offset);
883 dfrag->data_seq = msk->write_seq;
884 dfrag->overhead = offset - orig_offset + sizeof(struct mptcp_data_frag);
885 dfrag->offset = offset + sizeof(struct mptcp_data_frag);
886 dfrag->page = pfrag->page;
891 static int mptcp_sendmsg_frag(struct sock *sk, struct sock *ssk,
892 struct msghdr *msg, struct mptcp_data_frag *dfrag,
893 long *timeo, int *pmss_now,
896 int mss_now, avail_size, size_goal, offset, ret, frag_truesize = 0;
897 bool dfrag_collapsed, can_collapse = false;
898 struct mptcp_sock *msk = mptcp_sk(sk);
899 struct mptcp_ext *mpext = NULL;
900 bool retransmission = !!dfrag;
901 struct sk_buff *skb, *tail;
902 struct page_frag *pfrag;
907 /* use the mptcp page cache so that we can easily move the data
908 * from one substream to another, but do per subflow memory accounting
909 * Note: pfrag is used only !retransmission, but the compiler if
910 * fooled into a warning if we don't init here
912 pfrag = sk_page_frag(sk);
913 if (!retransmission) {
914 write_seq = &msk->write_seq;
917 write_seq = &dfrag->data_seq;
921 /* compute copy limit */
922 mss_now = tcp_send_mss(ssk, &size_goal, msg->msg_flags);
924 *ps_goal = size_goal;
925 avail_size = size_goal;
926 skb = tcp_write_queue_tail(ssk);
928 mpext = skb_ext_find(skb, SKB_EXT_MPTCP);
930 /* Limit the write to the size available in the
931 * current skb, if any, so that we create at most a new skb.
932 * Explicitly tells TCP internals to avoid collapsing on later
933 * queue management operation, to avoid breaking the ext <->
934 * SSN association set here
936 can_collapse = (size_goal - skb->len > 0) &&
937 mptcp_skb_can_collapse_to(*write_seq, skb, mpext);
939 TCP_SKB_CB(skb)->eor = 1;
941 avail_size = size_goal - skb->len;
944 if (!retransmission) {
945 /* reuse tail pfrag, if possible, or carve a new one from the
948 dfrag = mptcp_rtx_tail(sk);
949 offset = pfrag->offset;
950 dfrag_collapsed = mptcp_frag_can_collapse_to(msk, pfrag, dfrag);
951 if (!dfrag_collapsed) {
952 dfrag = mptcp_carve_data_frag(msk, pfrag, offset);
953 offset = dfrag->offset;
954 frag_truesize = dfrag->overhead;
956 psize = min_t(size_t, pfrag->size - offset, avail_size);
959 pr_debug("left=%zu", msg_data_left(msg));
960 psize = copy_page_from_iter(pfrag->page, offset,
961 min_t(size_t, msg_data_left(msg),
964 pr_debug("left=%zu", msg_data_left(msg));
968 if (!sk_wmem_schedule(sk, psize + dfrag->overhead)) {
969 iov_iter_revert(&msg->msg_iter, psize);
973 offset = dfrag->offset;
974 psize = min_t(size_t, dfrag->data_len, avail_size);
977 /* tell the TCP stack to delay the push so that we can safely
978 * access the skb after the sendpages call
980 ret = do_tcp_sendpages(ssk, page, offset, psize,
981 msg->msg_flags | MSG_SENDPAGE_NOTLAST | MSG_DONTWAIT);
984 iov_iter_revert(&msg->msg_iter, psize);
988 frag_truesize += ret;
989 if (!retransmission) {
990 if (unlikely(ret < psize))
991 iov_iter_revert(&msg->msg_iter, psize - ret);
993 /* send successful, keep track of sent data for mptcp-level
996 dfrag->data_len += ret;
997 if (!dfrag_collapsed) {
998 get_page(dfrag->page);
999 list_add_tail(&dfrag->list, &msk->rtx_queue);
1000 sk_wmem_queued_add(sk, frag_truesize);
1002 sk_wmem_queued_add(sk, ret);
1005 /* charge data on mptcp rtx queue to the master socket
1006 * Note: we charge such data both to sk and ssk
1008 sk->sk_forward_alloc -= frag_truesize;
1011 /* if the tail skb extension is still the cached one, collapsing
1012 * really happened. Note: we can't check for 'same skb' as the sk_buff
1013 * hdr on tail can be transmitted, freed and re-allocated by the
1014 * do_tcp_sendpages() call
1016 tail = tcp_write_queue_tail(ssk);
1017 if (mpext && tail && mpext == skb_ext_find(tail, SKB_EXT_MPTCP)) {
1018 WARN_ON_ONCE(!can_collapse);
1019 mpext->data_len += ret;
1023 skb = tcp_write_queue_tail(ssk);
1024 mpext = __skb_ext_set(skb, SKB_EXT_MPTCP, msk->cached_ext);
1025 msk->cached_ext = NULL;
1027 memset(mpext, 0, sizeof(*mpext));
1028 mpext->data_seq = *write_seq;
1029 mpext->subflow_seq = mptcp_subflow_ctx(ssk)->rel_write_seq;
1030 mpext->data_len = ret;
1034 pr_debug("data_seq=%llu subflow_seq=%u data_len=%u dsn64=%d",
1035 mpext->data_seq, mpext->subflow_seq, mpext->data_len,
1039 if (!retransmission)
1040 pfrag->offset += frag_truesize;
1041 WRITE_ONCE(*write_seq, *write_seq + ret);
1042 mptcp_subflow_ctx(ssk)->rel_write_seq += ret;
1047 static void mptcp_nospace(struct mptcp_sock *msk)
1049 struct mptcp_subflow_context *subflow;
1051 clear_bit(MPTCP_SEND_SPACE, &msk->flags);
1052 smp_mb__after_atomic(); /* msk->flags is changed by write_space cb */
1054 mptcp_for_each_subflow(msk, subflow) {
1055 struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
1056 struct socket *sock = READ_ONCE(ssk->sk_socket);
1058 /* enables ssk->write_space() callbacks */
1060 set_bit(SOCK_NOSPACE, &sock->flags);
1064 static bool mptcp_subflow_active(struct mptcp_subflow_context *subflow)
1066 struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
1068 /* can't send if JOIN hasn't completed yet (i.e. is usable for mptcp) */
1069 if (subflow->request_join && !subflow->fully_established)
1072 /* only send if our side has not closed yet */
1073 return ((1 << ssk->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT));
1076 #define MPTCP_SEND_BURST_SIZE ((1 << 16) - \
1077 sizeof(struct tcphdr) - \
1078 MAX_TCP_OPTION_SPACE - \
1079 sizeof(struct ipv6hdr) - \
1080 sizeof(struct frag_hdr))
1082 struct subflow_send_info {
1087 static struct sock *mptcp_subflow_get_send(struct mptcp_sock *msk,
1090 struct subflow_send_info send_info[2];
1091 struct mptcp_subflow_context *subflow;
1092 int i, nr_active = 0;
1097 sock_owned_by_me((struct sock *)msk);
1100 if (!mptcp_ext_cache_refill(msk))
1103 if (__mptcp_check_fallback(msk)) {
1106 *sndbuf = msk->first->sk_sndbuf;
1107 return sk_stream_memory_free(msk->first) ? msk->first : NULL;
1110 /* re-use last subflow, if the burst allow that */
1111 if (msk->last_snd && msk->snd_burst > 0 &&
1112 sk_stream_memory_free(msk->last_snd) &&
1113 mptcp_subflow_active(mptcp_subflow_ctx(msk->last_snd))) {
1114 mptcp_for_each_subflow(msk, subflow) {
1115 ssk = mptcp_subflow_tcp_sock(subflow);
1116 *sndbuf = max(tcp_sk(ssk)->snd_wnd, *sndbuf);
1118 return msk->last_snd;
1121 /* pick the subflow with the lower wmem/wspace ratio */
1122 for (i = 0; i < 2; ++i) {
1123 send_info[i].ssk = NULL;
1124 send_info[i].ratio = -1;
1126 mptcp_for_each_subflow(msk, subflow) {
1127 ssk = mptcp_subflow_tcp_sock(subflow);
1128 if (!mptcp_subflow_active(subflow))
1131 nr_active += !subflow->backup;
1132 *sndbuf = max(tcp_sk(ssk)->snd_wnd, *sndbuf);
1133 if (!sk_stream_memory_free(subflow->tcp_sock))
1136 pace = READ_ONCE(ssk->sk_pacing_rate);
1140 ratio = div_u64((u64)READ_ONCE(ssk->sk_wmem_queued) << 32,
1142 if (ratio < send_info[subflow->backup].ratio) {
1143 send_info[subflow->backup].ssk = ssk;
1144 send_info[subflow->backup].ratio = ratio;
1148 pr_debug("msk=%p nr_active=%d ssk=%p:%lld backup=%p:%lld",
1149 msk, nr_active, send_info[0].ssk, send_info[0].ratio,
1150 send_info[1].ssk, send_info[1].ratio);
1152 /* pick the best backup if no other subflow is active */
1154 send_info[0].ssk = send_info[1].ssk;
1156 if (send_info[0].ssk) {
1157 msk->last_snd = send_info[0].ssk;
1158 msk->snd_burst = min_t(int, MPTCP_SEND_BURST_SIZE,
1159 sk_stream_wspace(msk->last_snd));
1160 return msk->last_snd;
1165 static void ssk_check_wmem(struct mptcp_sock *msk)
1167 if (unlikely(!mptcp_is_writeable(msk)))
1171 static int mptcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1173 int mss_now = 0, size_goal = 0, ret = 0;
1174 struct mptcp_sock *msk = mptcp_sk(sk);
1175 struct page_frag *pfrag;
1182 if (msg->msg_flags & ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL))
1187 timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1189 if ((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) {
1190 ret = sk_stream_wait_connect(sk, &timeo);
1195 pfrag = sk_page_frag(sk);
1197 mptcp_clean_una(sk);
1199 if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN)) {
1204 __mptcp_flush_join_list(msk);
1205 ssk = mptcp_subflow_get_send(msk, &sndbuf);
1206 while (!sk_stream_memory_free(sk) ||
1208 !mptcp_page_frag_refill(ssk, pfrag)) {
1210 /* make sure retransmit timer is
1211 * running before we wait for memory.
1213 * The retransmit timer might be needed
1214 * to make the peer send an up-to-date
1217 mptcp_set_timeout(sk, ssk);
1218 if (!mptcp_timer_pending(sk))
1219 mptcp_reset_timer(sk);
1223 ret = sk_stream_wait_memory(sk, &timeo);
1227 mptcp_clean_una(sk);
1229 ssk = mptcp_subflow_get_send(msk, &sndbuf);
1230 if (list_empty(&msk->conn_list)) {
1236 /* do auto tuning */
1237 if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK) &&
1238 sndbuf > READ_ONCE(sk->sk_sndbuf))
1239 WRITE_ONCE(sk->sk_sndbuf, sndbuf);
1241 pr_debug("conn_list->subflow=%p", ssk);
1244 tx_ok = msg_data_left(msg);
1246 ret = mptcp_sendmsg_frag(sk, ssk, msg, NULL, &timeo, &mss_now,
1249 if (ret == -EAGAIN && timeo > 0) {
1250 mptcp_set_timeout(sk, ssk);
1257 /* burst can be negative, we will try move to the next subflow
1258 * at selection time, if possible.
1260 msk->snd_burst -= ret;
1263 tx_ok = msg_data_left(msg);
1267 if (!sk_stream_memory_free(ssk) ||
1268 !mptcp_page_frag_refill(ssk, pfrag) ||
1269 !mptcp_ext_cache_refill(msk)) {
1270 tcp_push(ssk, msg->msg_flags, mss_now,
1271 tcp_sk(ssk)->nonagle, size_goal);
1272 mptcp_set_timeout(sk, ssk);
1277 /* memory is charged to mptcp level socket as well, i.e.
1278 * if msg is very large, mptcp socket may run out of buffer
1279 * space. mptcp_clean_una() will release data that has
1280 * been acked at mptcp level in the mean time, so there is
1281 * a good chance we can continue sending data right away.
1283 * Normally, when the tcp subflow can accept more data, then
1284 * so can the MPTCP socket. However, we need to cope with
1285 * peers that might lag behind in their MPTCP-level
1286 * acknowledgements, i.e. data might have been acked at
1287 * tcp level only. So, we must also check the MPTCP socket
1288 * limits before we send more data.
1290 if (unlikely(!sk_stream_memory_free(sk))) {
1291 tcp_push(ssk, msg->msg_flags, mss_now,
1292 tcp_sk(ssk)->nonagle, size_goal);
1293 mptcp_clean_una(sk);
1294 if (!sk_stream_memory_free(sk)) {
1295 /* can't send more for now, need to wait for
1296 * MPTCP-level ACKs from peer.
1298 * Wakeup will happen via mptcp_clean_una().
1300 mptcp_set_timeout(sk, ssk);
1307 mptcp_set_timeout(sk, ssk);
1309 tcp_push(ssk, msg->msg_flags, mss_now, tcp_sk(ssk)->nonagle,
1312 /* start the timer, if it's not pending */
1313 if (!mptcp_timer_pending(sk))
1314 mptcp_reset_timer(sk);
1319 ssk_check_wmem(msk);
1321 return copied ? : ret;
1324 static void mptcp_wait_data(struct sock *sk, long *timeo)
1326 DEFINE_WAIT_FUNC(wait, woken_wake_function);
1327 struct mptcp_sock *msk = mptcp_sk(sk);
1329 add_wait_queue(sk_sleep(sk), &wait);
1330 sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1332 sk_wait_event(sk, timeo,
1333 test_and_clear_bit(MPTCP_DATA_READY, &msk->flags), &wait);
1335 sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
1336 remove_wait_queue(sk_sleep(sk), &wait);
1339 static int __mptcp_recvmsg_mskq(struct mptcp_sock *msk,
1343 struct sock *sk = (struct sock *)msk;
1344 struct sk_buff *skb;
1347 while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
1348 u32 offset = MPTCP_SKB_CB(skb)->offset;
1349 u32 data_len = skb->len - offset;
1350 u32 count = min_t(size_t, len - copied, data_len);
1353 err = skb_copy_datagram_msg(skb, offset, msg, count);
1354 if (unlikely(err < 0)) {
1362 if (count < data_len) {
1363 MPTCP_SKB_CB(skb)->offset += count;
1367 __skb_unlink(skb, &sk->sk_receive_queue);
1377 /* receive buffer autotuning. See tcp_rcv_space_adjust for more information.
1379 * Only difference: Use highest rtt estimate of the subflows in use.
1381 static void mptcp_rcv_space_adjust(struct mptcp_sock *msk, int copied)
1383 struct mptcp_subflow_context *subflow;
1384 struct sock *sk = (struct sock *)msk;
1385 u32 time, advmss = 1;
1388 sock_owned_by_me(sk);
1393 msk->rcvq_space.copied += copied;
1395 mstamp = div_u64(tcp_clock_ns(), NSEC_PER_USEC);
1396 time = tcp_stamp_us_delta(mstamp, msk->rcvq_space.time);
1398 rtt_us = msk->rcvq_space.rtt_us;
1399 if (rtt_us && time < (rtt_us >> 3))
1403 mptcp_for_each_subflow(msk, subflow) {
1404 const struct tcp_sock *tp;
1408 tp = tcp_sk(mptcp_subflow_tcp_sock(subflow));
1410 sf_rtt_us = READ_ONCE(tp->rcv_rtt_est.rtt_us);
1411 sf_advmss = READ_ONCE(tp->advmss);
1413 rtt_us = max(sf_rtt_us, rtt_us);
1414 advmss = max(sf_advmss, advmss);
1417 msk->rcvq_space.rtt_us = rtt_us;
1418 if (time < (rtt_us >> 3) || rtt_us == 0)
1421 if (msk->rcvq_space.copied <= msk->rcvq_space.space)
1424 if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_moderate_rcvbuf) &&
1425 !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
1429 rcvwin = ((u64)msk->rcvq_space.copied << 1) + 16 * advmss;
1431 grow = rcvwin * (msk->rcvq_space.copied - msk->rcvq_space.space);
1433 do_div(grow, msk->rcvq_space.space);
1434 rcvwin += (grow << 1);
1436 rcvmem = SKB_TRUESIZE(advmss + MAX_TCP_HEADER);
1437 while (tcp_win_from_space(sk, rcvmem) < advmss)
1440 do_div(rcvwin, advmss);
1441 rcvbuf = min_t(u64, rcvwin * rcvmem,
1442 READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2]));
1444 if (rcvbuf > sk->sk_rcvbuf) {
1447 window_clamp = tcp_win_from_space(sk, rcvbuf);
1448 WRITE_ONCE(sk->sk_rcvbuf, rcvbuf);
1450 /* Make subflows follow along. If we do not do this, we
1451 * get drops at subflow level if skbs can't be moved to
1452 * the mptcp rx queue fast enough (announced rcv_win can
1453 * exceed ssk->sk_rcvbuf).
1455 mptcp_for_each_subflow(msk, subflow) {
1459 ssk = mptcp_subflow_tcp_sock(subflow);
1460 slow = lock_sock_fast(ssk);
1461 WRITE_ONCE(ssk->sk_rcvbuf, rcvbuf);
1462 tcp_sk(ssk)->window_clamp = window_clamp;
1463 tcp_cleanup_rbuf(ssk, 1);
1464 unlock_sock_fast(ssk, slow);
1469 msk->rcvq_space.space = msk->rcvq_space.copied;
1471 msk->rcvq_space.copied = 0;
1472 msk->rcvq_space.time = mstamp;
1475 static bool __mptcp_move_skbs(struct mptcp_sock *msk)
1477 unsigned int moved = 0;
1480 /* avoid looping forever below on racing close */
1481 if (((struct sock *)msk)->sk_state == TCP_CLOSE)
1484 __mptcp_flush_join_list(msk);
1486 struct sock *ssk = mptcp_subflow_recv_lookup(msk);
1492 done = __mptcp_move_skbs_from_subflow(msk, ssk, &moved);
1496 if (mptcp_ofo_queue(msk) || moved > 0) {
1497 mptcp_check_data_fin((struct sock *)msk);
1503 static int mptcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
1504 int nonblock, int flags, int *addr_len)
1506 struct mptcp_sock *msk = mptcp_sk(sk);
1511 if (msg->msg_flags & ~(MSG_WAITALL | MSG_DONTWAIT))
1515 timeo = sock_rcvtimeo(sk, nonblock);
1517 len = min_t(size_t, len, INT_MAX);
1518 target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
1519 __mptcp_flush_join_list(msk);
1521 while (len > (size_t)copied) {
1524 bytes_read = __mptcp_recvmsg_mskq(msk, msg, len - copied);
1525 if (unlikely(bytes_read < 0)) {
1527 copied = bytes_read;
1531 copied += bytes_read;
1533 if (skb_queue_empty(&sk->sk_receive_queue) &&
1534 __mptcp_move_skbs(msk))
1537 /* only the master socket status is relevant here. The exit
1538 * conditions mirror closely tcp_recvmsg()
1540 if (copied >= target)
1545 sk->sk_state == TCP_CLOSE ||
1546 (sk->sk_shutdown & RCV_SHUTDOWN) ||
1548 signal_pending(current))
1552 copied = sock_error(sk);
1556 if (test_and_clear_bit(MPTCP_WORK_EOF, &msk->flags))
1557 mptcp_check_for_eof(msk);
1559 if (sk->sk_shutdown & RCV_SHUTDOWN)
1562 if (sk->sk_state == TCP_CLOSE) {
1572 if (signal_pending(current)) {
1573 copied = sock_intr_errno(timeo);
1578 pr_debug("block timeout %ld", timeo);
1579 mptcp_wait_data(sk, &timeo);
1582 if (skb_queue_empty(&sk->sk_receive_queue)) {
1583 /* entire backlog drained, clear DATA_READY. */
1584 clear_bit(MPTCP_DATA_READY, &msk->flags);
1586 /* .. race-breaker: ssk might have gotten new data
1587 * after last __mptcp_move_skbs() returned false.
1589 if (unlikely(__mptcp_move_skbs(msk)))
1590 set_bit(MPTCP_DATA_READY, &msk->flags);
1591 } else if (unlikely(!test_bit(MPTCP_DATA_READY, &msk->flags))) {
1592 /* data to read but mptcp_wait_data() cleared DATA_READY */
1593 set_bit(MPTCP_DATA_READY, &msk->flags);
1596 pr_debug("msk=%p data_ready=%d rx queue empty=%d copied=%d",
1597 msk, test_bit(MPTCP_DATA_READY, &msk->flags),
1598 skb_queue_empty(&sk->sk_receive_queue), copied);
1599 mptcp_rcv_space_adjust(msk, copied);
1605 static void mptcp_retransmit_handler(struct sock *sk)
1607 struct mptcp_sock *msk = mptcp_sk(sk);
1609 if (atomic64_read(&msk->snd_una) == READ_ONCE(msk->write_seq)) {
1610 mptcp_stop_timer(sk);
1612 set_bit(MPTCP_WORK_RTX, &msk->flags);
1613 if (schedule_work(&msk->work))
1618 static void mptcp_retransmit_timer(struct timer_list *t)
1620 struct inet_connection_sock *icsk = from_timer(icsk, t,
1621 icsk_retransmit_timer);
1622 struct sock *sk = &icsk->icsk_inet.sk;
1625 if (!sock_owned_by_user(sk)) {
1626 mptcp_retransmit_handler(sk);
1628 /* delegate our work to tcp_release_cb() */
1629 if (!test_and_set_bit(TCP_WRITE_TIMER_DEFERRED,
1637 /* Find an idle subflow. Return NULL if there is unacked data at tcp
1640 * A backup subflow is returned only if that is the only kind available.
1642 static struct sock *mptcp_subflow_get_retrans(const struct mptcp_sock *msk)
1644 struct mptcp_subflow_context *subflow;
1645 struct sock *backup = NULL;
1647 sock_owned_by_me((const struct sock *)msk);
1649 if (__mptcp_check_fallback(msk))
1652 mptcp_for_each_subflow(msk, subflow) {
1653 struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
1655 if (!mptcp_subflow_active(subflow))
1658 /* still data outstanding at TCP level? Don't retransmit. */
1659 if (!tcp_write_queue_empty(ssk)) {
1660 if (inet_csk(ssk)->icsk_ca_state >= TCP_CA_Loss)
1665 if (subflow->backup) {
1677 /* subflow sockets can be either outgoing (connect) or incoming
1680 * Outgoing subflows use in-kernel sockets.
1681 * Incoming subflows do not have their own 'struct socket' allocated,
1682 * so we need to use tcp_close() after detaching them from the mptcp
1685 void __mptcp_close_ssk(struct sock *sk, struct sock *ssk,
1686 struct mptcp_subflow_context *subflow,
1689 struct socket *sock = READ_ONCE(ssk->sk_socket);
1691 list_del(&subflow->node);
1693 if (sock && sock != sk->sk_socket) {
1694 /* outgoing subflow */
1697 /* incoming subflow */
1698 tcp_close(ssk, timeout);
1702 static unsigned int mptcp_sync_mss(struct sock *sk, u32 pmtu)
1707 static void pm_work(struct mptcp_sock *msk)
1709 struct mptcp_pm_data *pm = &msk->pm;
1711 spin_lock_bh(&msk->pm.lock);
1713 pr_debug("msk=%p status=%x", msk, pm->status);
1714 if (pm->status & BIT(MPTCP_PM_ADD_ADDR_RECEIVED)) {
1715 pm->status &= ~BIT(MPTCP_PM_ADD_ADDR_RECEIVED);
1716 mptcp_pm_nl_add_addr_received(msk);
1718 if (pm->status & BIT(MPTCP_PM_RM_ADDR_RECEIVED)) {
1719 pm->status &= ~BIT(MPTCP_PM_RM_ADDR_RECEIVED);
1720 mptcp_pm_nl_rm_addr_received(msk);
1722 if (pm->status & BIT(MPTCP_PM_ESTABLISHED)) {
1723 pm->status &= ~BIT(MPTCP_PM_ESTABLISHED);
1724 mptcp_pm_nl_fully_established(msk);
1726 if (pm->status & BIT(MPTCP_PM_SUBFLOW_ESTABLISHED)) {
1727 pm->status &= ~BIT(MPTCP_PM_SUBFLOW_ESTABLISHED);
1728 mptcp_pm_nl_subflow_established(msk);
1731 spin_unlock_bh(&msk->pm.lock);
1734 static void __mptcp_close_subflow(struct mptcp_sock *msk)
1736 struct mptcp_subflow_context *subflow, *tmp;
1738 list_for_each_entry_safe(subflow, tmp, &msk->conn_list, node) {
1739 struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
1741 if (inet_sk_state_load(ssk) != TCP_CLOSE)
1744 __mptcp_close_ssk((struct sock *)msk, ssk, subflow, 0);
1748 static void mptcp_worker(struct work_struct *work)
1750 struct mptcp_sock *msk = container_of(work, struct mptcp_sock, work);
1751 struct sock *ssk, *sk = &msk->sk.icsk_inet.sk;
1752 int orig_len, orig_offset, mss_now = 0, size_goal = 0;
1753 struct mptcp_data_frag *dfrag;
1756 struct msghdr msg = {
1757 .msg_flags = MSG_DONTWAIT,
1762 mptcp_clean_una(sk);
1763 mptcp_check_data_fin_ack(sk);
1764 __mptcp_flush_join_list(msk);
1765 if (test_and_clear_bit(MPTCP_WORK_CLOSE_SUBFLOW, &msk->flags))
1766 __mptcp_close_subflow(msk);
1768 __mptcp_move_skbs(msk);
1773 if (test_and_clear_bit(MPTCP_WORK_EOF, &msk->flags))
1774 mptcp_check_for_eof(msk);
1776 mptcp_check_data_fin(sk);
1778 if (!test_and_clear_bit(MPTCP_WORK_RTX, &msk->flags))
1781 dfrag = mptcp_rtx_head(sk);
1785 if (!mptcp_ext_cache_refill(msk))
1788 ssk = mptcp_subflow_get_retrans(msk);
1794 orig_len = dfrag->data_len;
1795 orig_offset = dfrag->offset;
1796 orig_write_seq = dfrag->data_seq;
1797 while (dfrag->data_len > 0) {
1798 int ret = mptcp_sendmsg_frag(sk, ssk, &msg, dfrag, &timeo,
1799 &mss_now, &size_goal);
1803 MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_RETRANSSEGS);
1805 dfrag->data_len -= ret;
1806 dfrag->offset += ret;
1808 if (!mptcp_ext_cache_refill(msk))
1812 tcp_push(ssk, msg.msg_flags, mss_now, tcp_sk(ssk)->nonagle,
1815 dfrag->data_seq = orig_write_seq;
1816 dfrag->offset = orig_offset;
1817 dfrag->data_len = orig_len;
1819 mptcp_set_timeout(sk, ssk);
1823 if (!mptcp_timer_pending(sk))
1824 mptcp_reset_timer(sk);
1831 static int __mptcp_init_sock(struct sock *sk)
1833 struct mptcp_sock *msk = mptcp_sk(sk);
1835 spin_lock_init(&msk->join_list_lock);
1837 INIT_LIST_HEAD(&msk->conn_list);
1838 INIT_LIST_HEAD(&msk->join_list);
1839 INIT_LIST_HEAD(&msk->rtx_queue);
1840 __set_bit(MPTCP_SEND_SPACE, &msk->flags);
1841 INIT_WORK(&msk->work, mptcp_worker);
1842 msk->out_of_order_queue = RB_ROOT;
1845 inet_csk(sk)->icsk_sync_mss = mptcp_sync_mss;
1847 mptcp_pm_data_init(msk);
1849 /* re-use the csk retrans timer for MPTCP-level retrans */
1850 timer_setup(&msk->sk.icsk_retransmit_timer, mptcp_retransmit_timer, 0);
1855 static int mptcp_init_sock(struct sock *sk)
1857 struct net *net = sock_net(sk);
1860 ret = __mptcp_init_sock(sk);
1864 if (!mptcp_is_enabled(net))
1865 return -ENOPROTOOPT;
1867 if (unlikely(!net->mib.mptcp_statistics) && !mptcp_mib_alloc(net))
1870 ret = __mptcp_socket_create(mptcp_sk(sk));
1874 sk_sockets_allocated_inc(sk);
1875 sk->sk_rcvbuf = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[1]);
1876 sk->sk_sndbuf = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_wmem[1]);
1881 static void __mptcp_clear_xmit(struct sock *sk)
1883 struct mptcp_sock *msk = mptcp_sk(sk);
1884 struct mptcp_data_frag *dtmp, *dfrag;
1886 sk_stop_timer(sk, &msk->sk.icsk_retransmit_timer);
1888 list_for_each_entry_safe(dfrag, dtmp, &msk->rtx_queue, list)
1889 dfrag_clear(sk, dfrag);
1892 static void mptcp_cancel_work(struct sock *sk)
1894 struct mptcp_sock *msk = mptcp_sk(sk);
1896 if (cancel_work_sync(&msk->work))
1900 void mptcp_subflow_shutdown(struct sock *sk, struct sock *ssk, int how)
1904 switch (ssk->sk_state) {
1906 if (!(how & RCV_SHUTDOWN))
1910 tcp_disconnect(ssk, O_NONBLOCK);
1913 if (__mptcp_check_fallback(mptcp_sk(sk))) {
1914 pr_debug("Fallback");
1915 ssk->sk_shutdown |= how;
1916 tcp_shutdown(ssk, how);
1918 pr_debug("Sending DATA_FIN on subflow %p", ssk);
1919 mptcp_set_timeout(sk, ssk);
1928 static const unsigned char new_state[16] = {
1929 /* current state: new state: action: */
1930 [0 /* (Invalid) */] = TCP_CLOSE,
1931 [TCP_ESTABLISHED] = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
1932 [TCP_SYN_SENT] = TCP_CLOSE,
1933 [TCP_SYN_RECV] = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
1934 [TCP_FIN_WAIT1] = TCP_FIN_WAIT1,
1935 [TCP_FIN_WAIT2] = TCP_FIN_WAIT2,
1936 [TCP_TIME_WAIT] = TCP_CLOSE, /* should not happen ! */
1937 [TCP_CLOSE] = TCP_CLOSE,
1938 [TCP_CLOSE_WAIT] = TCP_LAST_ACK | TCP_ACTION_FIN,
1939 [TCP_LAST_ACK] = TCP_LAST_ACK,
1940 [TCP_LISTEN] = TCP_CLOSE,
1941 [TCP_CLOSING] = TCP_CLOSING,
1942 [TCP_NEW_SYN_RECV] = TCP_CLOSE, /* should not happen ! */
1945 static int mptcp_close_state(struct sock *sk)
1947 int next = (int)new_state[sk->sk_state];
1948 int ns = next & TCP_STATE_MASK;
1950 inet_sk_state_store(sk, ns);
1952 return next & TCP_ACTION_FIN;
1955 static void mptcp_close(struct sock *sk, long timeout)
1957 struct mptcp_subflow_context *subflow, *tmp;
1958 struct mptcp_sock *msk = mptcp_sk(sk);
1959 LIST_HEAD(conn_list);
1962 sk->sk_shutdown = SHUTDOWN_MASK;
1964 if (sk->sk_state == TCP_LISTEN) {
1965 inet_sk_state_store(sk, TCP_CLOSE);
1967 } else if (sk->sk_state == TCP_CLOSE) {
1971 if (__mptcp_check_fallback(msk)) {
1973 } else if (mptcp_close_state(sk)) {
1974 pr_debug("Sending DATA_FIN sk=%p", sk);
1975 WRITE_ONCE(msk->write_seq, msk->write_seq + 1);
1976 WRITE_ONCE(msk->snd_data_fin_enable, 1);
1978 mptcp_for_each_subflow(msk, subflow) {
1979 struct sock *tcp_sk = mptcp_subflow_tcp_sock(subflow);
1981 mptcp_subflow_shutdown(sk, tcp_sk, SHUTDOWN_MASK);
1985 sk_stream_wait_close(sk, timeout);
1988 inet_sk_state_store(sk, TCP_CLOSE);
1991 /* be sure to always acquire the join list lock, to sync vs
1992 * mptcp_finish_join().
1994 spin_lock_bh(&msk->join_list_lock);
1995 list_splice_tail_init(&msk->join_list, &msk->conn_list);
1996 spin_unlock_bh(&msk->join_list_lock);
1997 list_splice_init(&msk->conn_list, &conn_list);
1999 __mptcp_clear_xmit(sk);
2003 list_for_each_entry_safe(subflow, tmp, &conn_list, node) {
2004 struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
2005 __mptcp_close_ssk(sk, ssk, subflow, timeout);
2008 mptcp_cancel_work(sk);
2010 __skb_queue_purge(&sk->sk_receive_queue);
2012 sk_common_release(sk);
2015 static void mptcp_copy_inaddrs(struct sock *msk, const struct sock *ssk)
2017 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
2018 const struct ipv6_pinfo *ssk6 = inet6_sk(ssk);
2019 struct ipv6_pinfo *msk6 = inet6_sk(msk);
2021 msk->sk_v6_daddr = ssk->sk_v6_daddr;
2022 msk->sk_v6_rcv_saddr = ssk->sk_v6_rcv_saddr;
2025 msk6->saddr = ssk6->saddr;
2026 msk6->flow_label = ssk6->flow_label;
2030 inet_sk(msk)->inet_num = inet_sk(ssk)->inet_num;
2031 inet_sk(msk)->inet_dport = inet_sk(ssk)->inet_dport;
2032 inet_sk(msk)->inet_sport = inet_sk(ssk)->inet_sport;
2033 inet_sk(msk)->inet_daddr = inet_sk(ssk)->inet_daddr;
2034 inet_sk(msk)->inet_saddr = inet_sk(ssk)->inet_saddr;
2035 inet_sk(msk)->inet_rcv_saddr = inet_sk(ssk)->inet_rcv_saddr;
2038 static int mptcp_disconnect(struct sock *sk, int flags)
2040 /* Should never be called.
2041 * inet_stream_connect() calls ->disconnect, but that
2042 * refers to the subflow socket, not the mptcp one.
2048 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
2049 static struct ipv6_pinfo *mptcp_inet6_sk(const struct sock *sk)
2051 unsigned int offset = sizeof(struct mptcp6_sock) - sizeof(struct ipv6_pinfo);
2053 return (struct ipv6_pinfo *)(((u8 *)sk) + offset);
2056 static void mptcp_copy_ip6_options(struct sock *newsk, const struct sock *sk)
2058 const struct ipv6_pinfo *np = inet6_sk(sk);
2059 struct ipv6_txoptions *opt;
2060 struct ipv6_pinfo *newnp;
2062 newnp = inet6_sk(newsk);
2065 opt = rcu_dereference(np->opt);
2067 opt = ipv6_dup_options(newsk, opt);
2069 net_warn_ratelimited("%s: Failed to copy ip6 options\n", __func__);
2071 RCU_INIT_POINTER(newnp->opt, opt);
2076 static void mptcp_copy_ip_options(struct sock *newsk, const struct sock *sk)
2078 struct ip_options_rcu *inet_opt, *newopt = NULL;
2079 const struct inet_sock *inet = inet_sk(sk);
2080 struct inet_sock *newinet;
2082 newinet = inet_sk(newsk);
2085 inet_opt = rcu_dereference(inet->inet_opt);
2087 newopt = sock_kmalloc(newsk, sizeof(*inet_opt) +
2088 inet_opt->opt.optlen, GFP_ATOMIC);
2090 memcpy(newopt, inet_opt, sizeof(*inet_opt) +
2091 inet_opt->opt.optlen);
2093 net_warn_ratelimited("%s: Failed to copy ip options\n", __func__);
2095 RCU_INIT_POINTER(newinet->inet_opt, newopt);
2099 struct sock *mptcp_sk_clone(const struct sock *sk,
2100 const struct mptcp_options_received *mp_opt,
2101 struct request_sock *req)
2103 struct mptcp_subflow_request_sock *subflow_req = mptcp_subflow_rsk(req);
2104 struct sock *nsk = sk_clone_lock(sk, GFP_ATOMIC);
2105 struct mptcp_sock *msk;
2111 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
2112 if (nsk->sk_family == AF_INET6)
2113 inet_sk(nsk)->pinet6 = mptcp_inet6_sk(nsk);
2116 __mptcp_init_sock(nsk);
2118 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
2119 if (nsk->sk_family == AF_INET6)
2120 mptcp_copy_ip6_options(nsk, sk);
2123 mptcp_copy_ip_options(nsk, sk);
2125 msk = mptcp_sk(nsk);
2126 msk->local_key = subflow_req->local_key;
2127 msk->token = subflow_req->token;
2128 msk->subflow = NULL;
2129 WRITE_ONCE(msk->fully_established, false);
2131 msk->write_seq = subflow_req->idsn + 1;
2132 atomic64_set(&msk->snd_una, msk->write_seq);
2133 if (mp_opt->mp_capable) {
2134 msk->can_ack = true;
2135 msk->remote_key = mp_opt->sndr_key;
2136 mptcp_crypto_key_sha(msk->remote_key, NULL, &ack_seq);
2138 WRITE_ONCE(msk->ack_seq, ack_seq);
2141 sock_reset_flag(nsk, SOCK_RCU_FREE);
2142 /* will be fully established after successful MPC subflow creation */
2143 inet_sk_state_store(nsk, TCP_SYN_RECV);
2145 security_inet_csk_clone(nsk, req);
2146 bh_unlock_sock(nsk);
2148 /* keep a single reference */
2153 void mptcp_rcv_space_init(struct mptcp_sock *msk, const struct sock *ssk)
2155 const struct tcp_sock *tp = tcp_sk(ssk);
2157 msk->rcvq_space.copied = 0;
2158 msk->rcvq_space.rtt_us = 0;
2160 msk->rcvq_space.time = tp->tcp_mstamp;
2162 /* initial rcv_space offering made to peer */
2163 msk->rcvq_space.space = min_t(u32, tp->rcv_wnd,
2164 TCP_INIT_CWND * tp->advmss);
2165 if (msk->rcvq_space.space == 0)
2166 msk->rcvq_space.space = TCP_INIT_CWND * TCP_MSS_DEFAULT;
2169 static struct sock *mptcp_accept(struct sock *sk, int flags, int *err,
2172 struct mptcp_sock *msk = mptcp_sk(sk);
2173 struct socket *listener;
2176 listener = __mptcp_nmpc_socket(msk);
2177 if (WARN_ON_ONCE(!listener)) {
2182 pr_debug("msk=%p, listener=%p", msk, mptcp_subflow_ctx(listener->sk));
2183 newsk = inet_csk_accept(listener->sk, flags, err, kern);
2187 pr_debug("msk=%p, subflow is mptcp=%d", msk, sk_is_mptcp(newsk));
2188 if (sk_is_mptcp(newsk)) {
2189 struct mptcp_subflow_context *subflow;
2190 struct sock *new_mptcp_sock;
2191 struct sock *ssk = newsk;
2193 subflow = mptcp_subflow_ctx(newsk);
2194 new_mptcp_sock = subflow->conn;
2196 /* is_mptcp should be false if subflow->conn is missing, see
2197 * subflow_syn_recv_sock()
2199 if (WARN_ON_ONCE(!new_mptcp_sock)) {
2200 tcp_sk(newsk)->is_mptcp = 0;
2204 /* acquire the 2nd reference for the owning socket */
2205 sock_hold(new_mptcp_sock);
2208 bh_lock_sock(new_mptcp_sock);
2209 msk = mptcp_sk(new_mptcp_sock);
2212 newsk = new_mptcp_sock;
2213 mptcp_copy_inaddrs(newsk, ssk);
2214 list_add(&subflow->node, &msk->conn_list);
2216 mptcp_rcv_space_init(msk, ssk);
2217 bh_unlock_sock(new_mptcp_sock);
2219 __MPTCP_INC_STATS(sock_net(sk), MPTCP_MIB_MPCAPABLEPASSIVEACK);
2224 newsk->sk_kern_sock = kern;
2228 void mptcp_destroy_common(struct mptcp_sock *msk)
2230 skb_rbtree_purge(&msk->out_of_order_queue);
2231 mptcp_token_destroy(msk);
2232 mptcp_pm_free_anno_list(msk);
2235 static void mptcp_destroy(struct sock *sk)
2237 struct mptcp_sock *msk = mptcp_sk(sk);
2239 if (msk->cached_ext)
2240 __skb_ext_put(msk->cached_ext);
2242 mptcp_destroy_common(msk);
2243 sk_sockets_allocated_dec(sk);
2246 static int mptcp_setsockopt_sol_socket(struct mptcp_sock *msk, int optname,
2247 sockptr_t optval, unsigned int optlen)
2249 struct sock *sk = (struct sock *)msk;
2250 struct socket *ssock;
2257 ssock = __mptcp_nmpc_socket(msk);
2263 ret = sock_setsockopt(ssock, SOL_SOCKET, optname, optval, optlen);
2265 if (optname == SO_REUSEPORT)
2266 sk->sk_reuseport = ssock->sk->sk_reuseport;
2267 else if (optname == SO_REUSEADDR)
2268 sk->sk_reuse = ssock->sk->sk_reuse;
2274 return sock_setsockopt(sk->sk_socket, SOL_SOCKET, optname, optval, optlen);
2277 static int mptcp_setsockopt_v6(struct mptcp_sock *msk, int optname,
2278 sockptr_t optval, unsigned int optlen)
2280 struct sock *sk = (struct sock *)msk;
2281 int ret = -EOPNOTSUPP;
2282 struct socket *ssock;
2287 ssock = __mptcp_nmpc_socket(msk);
2293 ret = tcp_setsockopt(ssock->sk, SOL_IPV6, optname, optval, optlen);
2295 sk->sk_ipv6only = ssock->sk->sk_ipv6only;
2304 static bool mptcp_unsupported(int level, int optname)
2306 if (level == SOL_IP) {
2308 case IP_ADD_MEMBERSHIP:
2309 case IP_ADD_SOURCE_MEMBERSHIP:
2310 case IP_DROP_MEMBERSHIP:
2311 case IP_DROP_SOURCE_MEMBERSHIP:
2312 case IP_BLOCK_SOURCE:
2313 case IP_UNBLOCK_SOURCE:
2314 case MCAST_JOIN_GROUP:
2315 case MCAST_LEAVE_GROUP:
2316 case MCAST_JOIN_SOURCE_GROUP:
2317 case MCAST_LEAVE_SOURCE_GROUP:
2318 case MCAST_BLOCK_SOURCE:
2319 case MCAST_UNBLOCK_SOURCE:
2320 case MCAST_MSFILTER:
2325 if (level == SOL_IPV6) {
2328 case IPV6_ADD_MEMBERSHIP:
2329 case IPV6_DROP_MEMBERSHIP:
2330 case IPV6_JOIN_ANYCAST:
2331 case IPV6_LEAVE_ANYCAST:
2332 case MCAST_JOIN_GROUP:
2333 case MCAST_LEAVE_GROUP:
2334 case MCAST_JOIN_SOURCE_GROUP:
2335 case MCAST_LEAVE_SOURCE_GROUP:
2336 case MCAST_BLOCK_SOURCE:
2337 case MCAST_UNBLOCK_SOURCE:
2338 case MCAST_MSFILTER:
2346 static int mptcp_setsockopt(struct sock *sk, int level, int optname,
2347 sockptr_t optval, unsigned int optlen)
2349 struct mptcp_sock *msk = mptcp_sk(sk);
2352 pr_debug("msk=%p", msk);
2354 if (mptcp_unsupported(level, optname))
2355 return -ENOPROTOOPT;
2357 if (level == SOL_SOCKET)
2358 return mptcp_setsockopt_sol_socket(msk, optname, optval, optlen);
2360 /* @@ the meaning of setsockopt() when the socket is connected and
2361 * there are multiple subflows is not yet defined. It is up to the
2362 * MPTCP-level socket to configure the subflows until the subflow
2363 * is in TCP fallback, when TCP socket options are passed through
2364 * to the one remaining subflow.
2367 ssk = __mptcp_tcp_fallback(msk);
2370 return tcp_setsockopt(ssk, level, optname, optval, optlen);
2372 if (level == SOL_IPV6)
2373 return mptcp_setsockopt_v6(msk, optname, optval, optlen);
2378 static int mptcp_getsockopt(struct sock *sk, int level, int optname,
2379 char __user *optval, int __user *option)
2381 struct mptcp_sock *msk = mptcp_sk(sk);
2384 pr_debug("msk=%p", msk);
2386 /* @@ the meaning of setsockopt() when the socket is connected and
2387 * there are multiple subflows is not yet defined. It is up to the
2388 * MPTCP-level socket to configure the subflows until the subflow
2389 * is in TCP fallback, when socket options are passed through
2390 * to the one remaining subflow.
2393 ssk = __mptcp_tcp_fallback(msk);
2396 return tcp_getsockopt(ssk, level, optname, optval, option);
2401 #define MPTCP_DEFERRED_ALL (TCPF_DELACK_TIMER_DEFERRED | \
2402 TCPF_WRITE_TIMER_DEFERRED)
2404 /* this is very alike tcp_release_cb() but we must handle differently a
2405 * different set of events
2407 static void mptcp_release_cb(struct sock *sk)
2409 unsigned long flags, nflags;
2412 flags = sk->sk_tsq_flags;
2413 if (!(flags & MPTCP_DEFERRED_ALL))
2415 nflags = flags & ~MPTCP_DEFERRED_ALL;
2416 } while (cmpxchg(&sk->sk_tsq_flags, flags, nflags) != flags);
2418 sock_release_ownership(sk);
2420 if (flags & TCPF_DELACK_TIMER_DEFERRED) {
2421 struct mptcp_sock *msk = mptcp_sk(sk);
2424 ssk = mptcp_subflow_recv_lookup(msk);
2425 if (!ssk || !schedule_work(&msk->work))
2429 if (flags & TCPF_WRITE_TIMER_DEFERRED) {
2430 mptcp_retransmit_handler(sk);
2435 static int mptcp_hash(struct sock *sk)
2437 /* should never be called,
2438 * we hash the TCP subflows not the master socket
2444 static void mptcp_unhash(struct sock *sk)
2446 /* called from sk_common_release(), but nothing to do here */
2449 static int mptcp_get_port(struct sock *sk, unsigned short snum)
2451 struct mptcp_sock *msk = mptcp_sk(sk);
2452 struct socket *ssock;
2454 ssock = __mptcp_nmpc_socket(msk);
2455 pr_debug("msk=%p, subflow=%p", msk, ssock);
2456 if (WARN_ON_ONCE(!ssock))
2459 return inet_csk_get_port(ssock->sk, snum);
2462 void mptcp_finish_connect(struct sock *ssk)
2464 struct mptcp_subflow_context *subflow;
2465 struct mptcp_sock *msk;
2469 subflow = mptcp_subflow_ctx(ssk);
2473 pr_debug("msk=%p, token=%u", sk, subflow->token);
2475 mptcp_crypto_key_sha(subflow->remote_key, NULL, &ack_seq);
2477 subflow->map_seq = ack_seq;
2478 subflow->map_subflow_seq = 1;
2480 /* the socket is not connected yet, no msk/subflow ops can access/race
2481 * accessing the field below
2483 WRITE_ONCE(msk->remote_key, subflow->remote_key);
2484 WRITE_ONCE(msk->local_key, subflow->local_key);
2485 WRITE_ONCE(msk->write_seq, subflow->idsn + 1);
2486 WRITE_ONCE(msk->ack_seq, ack_seq);
2487 WRITE_ONCE(msk->can_ack, 1);
2488 atomic64_set(&msk->snd_una, msk->write_seq);
2490 mptcp_pm_new_connection(msk, 0);
2492 mptcp_rcv_space_init(msk, ssk);
2495 static void mptcp_sock_graft(struct sock *sk, struct socket *parent)
2497 write_lock_bh(&sk->sk_callback_lock);
2498 rcu_assign_pointer(sk->sk_wq, &parent->wq);
2499 sk_set_socket(sk, parent);
2500 sk->sk_uid = SOCK_INODE(parent)->i_uid;
2501 write_unlock_bh(&sk->sk_callback_lock);
2504 bool mptcp_finish_join(struct sock *sk)
2506 struct mptcp_subflow_context *subflow = mptcp_subflow_ctx(sk);
2507 struct mptcp_sock *msk = mptcp_sk(subflow->conn);
2508 struct sock *parent = (void *)msk;
2509 struct socket *parent_sock;
2512 pr_debug("msk=%p, subflow=%p", msk, subflow);
2514 /* mptcp socket already closing? */
2515 if (!mptcp_is_fully_established(parent))
2518 if (!msk->pm.server_side)
2521 if (!mptcp_pm_allow_new_subflow(msk))
2524 /* active connections are already on conn_list, and we can't acquire
2526 * use the join list lock as synchronization point and double-check
2527 * msk status to avoid racing with mptcp_close()
2529 spin_lock_bh(&msk->join_list_lock);
2530 ret = inet_sk_state_load(parent) == TCP_ESTABLISHED;
2531 if (ret && !WARN_ON_ONCE(!list_empty(&subflow->node)))
2532 list_add_tail(&subflow->node, &msk->join_list);
2533 spin_unlock_bh(&msk->join_list_lock);
2537 /* attach to msk socket only after we are sure he will deal with us
2540 parent_sock = READ_ONCE(parent->sk_socket);
2541 if (parent_sock && !sk->sk_socket)
2542 mptcp_sock_graft(sk, parent_sock);
2543 subflow->map_seq = READ_ONCE(msk->ack_seq);
2547 static bool mptcp_memory_free(const struct sock *sk, int wake)
2549 struct mptcp_sock *msk = mptcp_sk(sk);
2551 return wake ? test_bit(MPTCP_SEND_SPACE, &msk->flags) : true;
2554 static struct proto mptcp_prot = {
2556 .owner = THIS_MODULE,
2557 .init = mptcp_init_sock,
2558 .disconnect = mptcp_disconnect,
2559 .close = mptcp_close,
2560 .accept = mptcp_accept,
2561 .setsockopt = mptcp_setsockopt,
2562 .getsockopt = mptcp_getsockopt,
2563 .shutdown = tcp_shutdown,
2564 .destroy = mptcp_destroy,
2565 .sendmsg = mptcp_sendmsg,
2566 .recvmsg = mptcp_recvmsg,
2567 .release_cb = mptcp_release_cb,
2569 .unhash = mptcp_unhash,
2570 .get_port = mptcp_get_port,
2571 .sockets_allocated = &mptcp_sockets_allocated,
2572 .memory_allocated = &tcp_memory_allocated,
2573 .memory_pressure = &tcp_memory_pressure,
2574 .stream_memory_free = mptcp_memory_free,
2575 .sysctl_wmem_offset = offsetof(struct net, ipv4.sysctl_tcp_wmem),
2576 .sysctl_rmem_offset = offsetof(struct net, ipv4.sysctl_tcp_rmem),
2577 .sysctl_mem = sysctl_tcp_mem,
2578 .obj_size = sizeof(struct mptcp_sock),
2579 .slab_flags = SLAB_TYPESAFE_BY_RCU,
2580 .no_autobind = true,
2583 static int mptcp_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
2585 struct mptcp_sock *msk = mptcp_sk(sock->sk);
2586 struct socket *ssock;
2589 lock_sock(sock->sk);
2590 ssock = __mptcp_nmpc_socket(msk);
2596 err = ssock->ops->bind(ssock, uaddr, addr_len);
2598 mptcp_copy_inaddrs(sock->sk, ssock->sk);
2601 release_sock(sock->sk);
2605 static void mptcp_subflow_early_fallback(struct mptcp_sock *msk,
2606 struct mptcp_subflow_context *subflow)
2608 subflow->request_mptcp = 0;
2609 __mptcp_do_fallback(msk);
2612 static int mptcp_stream_connect(struct socket *sock, struct sockaddr *uaddr,
2613 int addr_len, int flags)
2615 struct mptcp_sock *msk = mptcp_sk(sock->sk);
2616 struct mptcp_subflow_context *subflow;
2617 struct socket *ssock;
2620 lock_sock(sock->sk);
2621 if (sock->state != SS_UNCONNECTED && msk->subflow) {
2622 /* pending connection or invalid state, let existing subflow
2625 ssock = msk->subflow;
2629 ssock = __mptcp_nmpc_socket(msk);
2635 mptcp_token_destroy(msk);
2636 inet_sk_state_store(sock->sk, TCP_SYN_SENT);
2637 subflow = mptcp_subflow_ctx(ssock->sk);
2638 #ifdef CONFIG_TCP_MD5SIG
2639 /* no MPTCP if MD5SIG is enabled on this socket or we may run out of
2642 if (rcu_access_pointer(tcp_sk(ssock->sk)->md5sig_info))
2643 mptcp_subflow_early_fallback(msk, subflow);
2645 if (subflow->request_mptcp && mptcp_token_new_connect(ssock->sk))
2646 mptcp_subflow_early_fallback(msk, subflow);
2648 WRITE_ONCE(msk->write_seq, subflow->idsn);
2651 err = ssock->ops->connect(ssock, uaddr, addr_len, flags);
2652 sock->state = ssock->state;
2654 /* on successful connect, the msk state will be moved to established by
2655 * subflow_finish_connect()
2657 if (!err || err == -EINPROGRESS)
2658 mptcp_copy_inaddrs(sock->sk, ssock->sk);
2660 inet_sk_state_store(sock->sk, inet_sk_state_load(ssock->sk));
2663 release_sock(sock->sk);
2667 static int mptcp_listen(struct socket *sock, int backlog)
2669 struct mptcp_sock *msk = mptcp_sk(sock->sk);
2670 struct socket *ssock;
2673 pr_debug("msk=%p", msk);
2675 lock_sock(sock->sk);
2676 ssock = __mptcp_nmpc_socket(msk);
2682 mptcp_token_destroy(msk);
2683 inet_sk_state_store(sock->sk, TCP_LISTEN);
2684 sock_set_flag(sock->sk, SOCK_RCU_FREE);
2686 err = ssock->ops->listen(ssock, backlog);
2687 inet_sk_state_store(sock->sk, inet_sk_state_load(ssock->sk));
2689 mptcp_copy_inaddrs(sock->sk, ssock->sk);
2692 release_sock(sock->sk);
2696 static int mptcp_stream_accept(struct socket *sock, struct socket *newsock,
2697 int flags, bool kern)
2699 struct mptcp_sock *msk = mptcp_sk(sock->sk);
2700 struct socket *ssock;
2703 pr_debug("msk=%p", msk);
2705 lock_sock(sock->sk);
2706 if (sock->sk->sk_state != TCP_LISTEN)
2709 ssock = __mptcp_nmpc_socket(msk);
2713 clear_bit(MPTCP_DATA_READY, &msk->flags);
2714 sock_hold(ssock->sk);
2715 release_sock(sock->sk);
2717 err = ssock->ops->accept(sock, newsock, flags, kern);
2718 if (err == 0 && !mptcp_is_tcpsk(newsock->sk)) {
2719 struct mptcp_sock *msk = mptcp_sk(newsock->sk);
2720 struct mptcp_subflow_context *subflow;
2722 /* set ssk->sk_socket of accept()ed flows to mptcp socket.
2723 * This is needed so NOSPACE flag can be set from tcp stack.
2725 __mptcp_flush_join_list(msk);
2726 mptcp_for_each_subflow(msk, subflow) {
2727 struct sock *ssk = mptcp_subflow_tcp_sock(subflow);
2729 if (!ssk->sk_socket)
2730 mptcp_sock_graft(ssk, newsock);
2734 if (inet_csk_listen_poll(ssock->sk))
2735 set_bit(MPTCP_DATA_READY, &msk->flags);
2736 sock_put(ssock->sk);
2740 release_sock(sock->sk);
2744 static __poll_t mptcp_check_readable(struct mptcp_sock *msk)
2746 return test_bit(MPTCP_DATA_READY, &msk->flags) ? EPOLLIN | EPOLLRDNORM :
2750 static __poll_t mptcp_poll(struct file *file, struct socket *sock,
2751 struct poll_table_struct *wait)
2753 struct sock *sk = sock->sk;
2754 struct mptcp_sock *msk;
2759 sock_poll_wait(file, sock, wait);
2761 state = inet_sk_state_load(sk);
2762 pr_debug("msk=%p state=%d flags=%lx", msk, state, msk->flags);
2763 if (state == TCP_LISTEN)
2764 return mptcp_check_readable(msk);
2766 if (state != TCP_SYN_SENT && state != TCP_SYN_RECV) {
2767 mask |= mptcp_check_readable(msk);
2768 if (test_bit(MPTCP_SEND_SPACE, &msk->flags))
2769 mask |= EPOLLOUT | EPOLLWRNORM;
2771 if (sk->sk_shutdown & RCV_SHUTDOWN)
2772 mask |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP;
2777 static int mptcp_shutdown(struct socket *sock, int how)
2779 struct mptcp_sock *msk = mptcp_sk(sock->sk);
2780 struct mptcp_subflow_context *subflow;
2783 pr_debug("sk=%p, how=%d", msk, how);
2785 lock_sock(sock->sk);
2788 if ((how & ~SHUTDOWN_MASK) || !how) {
2793 if (sock->state == SS_CONNECTING) {
2794 if ((1 << sock->sk->sk_state) &
2795 (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_CLOSE))
2796 sock->state = SS_DISCONNECTING;
2798 sock->state = SS_CONNECTED;
2801 /* If we've already sent a FIN, or it's a closed state, skip this. */
2802 if (__mptcp_check_fallback(msk)) {
2803 if (how == SHUT_WR || how == SHUT_RDWR)
2804 inet_sk_state_store(sock->sk, TCP_FIN_WAIT1);
2806 mptcp_for_each_subflow(msk, subflow) {
2807 struct sock *tcp_sk = mptcp_subflow_tcp_sock(subflow);
2809 mptcp_subflow_shutdown(sock->sk, tcp_sk, how);
2811 } else if ((how & SEND_SHUTDOWN) &&
2812 ((1 << sock->sk->sk_state) &
2813 (TCPF_ESTABLISHED | TCPF_SYN_SENT |
2814 TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) &&
2815 mptcp_close_state(sock->sk)) {
2816 __mptcp_flush_join_list(msk);
2818 WRITE_ONCE(msk->write_seq, msk->write_seq + 1);
2819 WRITE_ONCE(msk->snd_data_fin_enable, 1);
2821 mptcp_for_each_subflow(msk, subflow) {
2822 struct sock *tcp_sk = mptcp_subflow_tcp_sock(subflow);
2824 mptcp_subflow_shutdown(sock->sk, tcp_sk, how);
2828 /* Wake up anyone sleeping in poll. */
2829 sock->sk->sk_state_change(sock->sk);
2832 release_sock(sock->sk);
2837 static const struct proto_ops mptcp_stream_ops = {
2839 .owner = THIS_MODULE,
2840 .release = inet_release,
2842 .connect = mptcp_stream_connect,
2843 .socketpair = sock_no_socketpair,
2844 .accept = mptcp_stream_accept,
2845 .getname = inet_getname,
2847 .ioctl = inet_ioctl,
2848 .gettstamp = sock_gettstamp,
2849 .listen = mptcp_listen,
2850 .shutdown = mptcp_shutdown,
2851 .setsockopt = sock_common_setsockopt,
2852 .getsockopt = sock_common_getsockopt,
2853 .sendmsg = inet_sendmsg,
2854 .recvmsg = inet_recvmsg,
2855 .mmap = sock_no_mmap,
2856 .sendpage = inet_sendpage,
2859 static struct inet_protosw mptcp_protosw = {
2860 .type = SOCK_STREAM,
2861 .protocol = IPPROTO_MPTCP,
2862 .prot = &mptcp_prot,
2863 .ops = &mptcp_stream_ops,
2864 .flags = INET_PROTOSW_ICSK,
2867 void __init mptcp_proto_init(void)
2869 mptcp_prot.h.hashinfo = tcp_prot.h.hashinfo;
2871 if (percpu_counter_init(&mptcp_sockets_allocated, 0, GFP_KERNEL))
2872 panic("Failed to allocate MPTCP pcpu counter\n");
2874 mptcp_subflow_init();
2878 if (proto_register(&mptcp_prot, 1) != 0)
2879 panic("Failed to register MPTCP proto.\n");
2881 inet_register_protosw(&mptcp_protosw);
2883 BUILD_BUG_ON(sizeof(struct mptcp_skb_cb) > sizeof_field(struct sk_buff, cb));
2886 #if IS_ENABLED(CONFIG_MPTCP_IPV6)
2887 static const struct proto_ops mptcp_v6_stream_ops = {
2889 .owner = THIS_MODULE,
2890 .release = inet6_release,
2892 .connect = mptcp_stream_connect,
2893 .socketpair = sock_no_socketpair,
2894 .accept = mptcp_stream_accept,
2895 .getname = inet6_getname,
2897 .ioctl = inet6_ioctl,
2898 .gettstamp = sock_gettstamp,
2899 .listen = mptcp_listen,
2900 .shutdown = mptcp_shutdown,
2901 .setsockopt = sock_common_setsockopt,
2902 .getsockopt = sock_common_getsockopt,
2903 .sendmsg = inet6_sendmsg,
2904 .recvmsg = inet6_recvmsg,
2905 .mmap = sock_no_mmap,
2906 .sendpage = inet_sendpage,
2907 #ifdef CONFIG_COMPAT
2908 .compat_ioctl = inet6_compat_ioctl,
2912 static struct proto mptcp_v6_prot;
2914 static struct inet_protosw mptcp_v6_protosw = {
2915 .type = SOCK_STREAM,
2916 .protocol = IPPROTO_MPTCP,
2917 .prot = &mptcp_v6_prot,
2918 .ops = &mptcp_v6_stream_ops,
2919 .flags = INET_PROTOSW_ICSK,
2922 int __init mptcp_proto_v6_init(void)
2926 mptcp_v6_prot = mptcp_prot;
2927 strcpy(mptcp_v6_prot.name, "MPTCPv6");
2928 mptcp_v6_prot.slab = NULL;
2929 mptcp_v6_prot.obj_size = sizeof(struct mptcp6_sock);
2931 err = proto_register(&mptcp_v6_prot, 1);
2935 err = inet6_register_protosw(&mptcp_v6_protosw);
2937 proto_unregister(&mptcp_v6_prot);