tcp: Prevent tcp_collapse() from bloating queue.
Subsystems (5)
Kuniyuki Iwashima
reviewerv3 cover tcp: Prevent tcp_collapse() from bloating queue.
This is a follow-up for commit 031c403d13e5 ("tcp: do not let tcp_collapse() drive sk_forward_alloc negative").
The core algorithm in tcp_collapse() is so simple and has not been changed since commit 1da177e4c3f4 ("Linux-2.6.12-rc2"); finding a collapsible skb and repacking it into up-to-SKB_MAX_ORDER() skb.
Now that we use 4K MSS and tp->scaling_ratio, the simple algorithm does not work well, and it could even end up consuming more memory contrary to the intention.
For example, the scaling ratio of SKB_MAX_ORDER() is 222, but typically tp->scaling_ratio for 4K MSS flow is 252, and repacking data rather bloats high-density skb.
Also, once a low-density skb starts collapsing, it drags all the following skbs into collapsing regardless of the density.
This series changes the algorithm so that it skips high-density skb and a single low-density skb between high-density skbs, batches memory accounting at the end, and removes sk_forced_mem_schedule().
This series still keeps linear SKB_MAX_ORDER(0, 0) skbs as the collapse target, and Eric is working on a follow-up patch to store the collapsed payload in order-0 page frags instead.
https://lore.kernel.org/netdev/CAL4WiiqekjxZw3EoDYXLc0Phd3i0GStE2ZHWQkH2iAkSM5D8TQ@mail.gmail.com/
Changes:
v3:
* Patch 3:
* Remove fully-overlapping skb in the 2nd loop
* Skip range on overlapping unmergeable ofo skb
* Update tcp_collapse() comment
* Patch 4:
* Remove redundant kmalloc_size_roundup()
* Rename helper with skb_ prefix
* Declare {old,new}_truesize as unsigned int
* Patch 5:
* Make TCP_COLLAPSE_MAX_TOTAL_SIZE hard-limit for multiple skbs
v2: https://lore.kernel.org/netdev/[email protected]/
* Patch 1: Describe SYN/FIN behaviour change
* Patch 3: Describe behavioural change for MPTCP
* Patch 4: Add compute_skb_truesize() instead of macro
* Patch 7: Rename test to tcp_rcv_collapse_bloated.pkt
v1: https://lore.kernel.org/netdev/[email protected]/
Kuniyuki Iwashima (7):
tcp: Refactor the first loop in tcp_collapse().
tcp: Don't collapse high density skb.
tcp: Stop collapsing if not bloated.
tcp: Skip collapsing if collapsed skb is less-dense.
tcp: Allocate all new skb before collapsing.
tcp: Batch memory accounting in tcp_collapse().
selftest: packetdrill: Add test for tcp_collapse().
include/linux/skbuff.h | 2 + net/core/skbuff.c | 27 ++- net/ipv4/tcp_input.c | 190 +++++++++++++----- .../selftests/net/packetdrill/ksft_runner.sh | 9 + .../packetdrill/tcp_rcv_collapse_bloated.pkt | 135 +++++++++++++ 5 files changed, 311 insertions(+), 52 deletions(-) create mode 100644 tools/testing/selftests/net/packetdrill/tcp_rcv_collapse_bloated.pkt
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Kuniyuki Iwashima
reviewerPATCH v3 1/7 tcp: Refactor the first loop in tcp_collapse().
tcp_collapse() detects skb to start collapsing from in the first loop.
If the last skb has SYN or FIN, the condition is tested again after the loop.
skb_frags_readable() is placed inside and outside of the loop as well.
If we goto skip_this in both cases, we can remove the second tests and simply replace end_of_skbs with the inverted loop condition.
Then, we do not need a test for tcp_collapse_one() too.
Also, skb_frags_readable() should be tested after the fully overlapping check.
Let's refactor the loop.
Note that previously, when a SYN/FIN skb overlapped with the next skb, the loop broke with end_of_skbs set to false and the check after the loop returned without collapsing anything further. Now such a skb is skipped instead, allowing the following skbs to be collapsed.
---
v2: Document SYN/FIN behaviour change
--- net/ipv4/tcp_input.c | 28 ++++++++++------------------ 1 file changed, 10 insertions(+), 18 deletions(-)
net/ipv4/tcp_input.c +10 -18
@@ -5849,23 +5849,17 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, {struct sk_buff *skb = head, *n;struct sk_buff_head tmp; -bool end_of_skbs;/* First, check that queue is collapsible and find * the point where collapsing can be useful. */ restart: -for (end_of_skbs = true; skb !=NULL && skb != tail; skb = n) { +for (; skb && skb != tail; skb = n) { n =tcp_skb_next (skb, list); -if (!skb_frags_readable (skb)) - goto skip_this; -/* No new bits? It is possible on ofo queue. */ if (!before (start,TCP_SKB_CB (skb)->end_seq)) { skb =tcp_collapse_one (sk, skb, list, root); -if (!skb) -break ; goto restart; }
@@ -5874,27 +5868,25 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,* - bloated or contains data before "start" or * overlaps to the next one and mptcp allow collapsing. */ -if (!(TCP_SKB_CB (skb)->tcp_flags & (TCPHDR_SYN |TCPHDR_FIN )) && - (tcp_win_from_space (sk, skb->truesize) > skb->len || -before (TCP_SKB_CB (skb)->seq, start))) { - end_of_skbs = false; +if (!skb_frags_readable (skb) || +TCP_SKB_CB (skb)->tcp_flags & (TCPHDR_SYN |TCPHDR_FIN )) + goto skip_this; + +if (tcp_win_from_space (sk, skb->truesize) > skb->len || +before (TCP_SKB_CB (skb)->seq, start))break ; - }if (n && n != tail &&skb_frags_readable (n) &&tcp_skb_can_collapse_rx (skb, n) && -TCP_SKB_CB (skb)->end_seq !=TCP_SKB_CB (n)->seq) { - end_of_skbs = false; +TCP_SKB_CB (skb)->end_seq !=TCP_SKB_CB (n)->seq)break ; - } skip_this:/* Decided to skip this, advance start seq. */ start =TCP_SKB_CB (skb)->end_seq; } -if (end_of_skbs || - (TCP_SKB_CB (skb)->tcp_flags & (TCPHDR_SYN |TCPHDR_FIN )) || - !skb_frags_readable (skb)) + +if (!skb || skb == tail)return ;__skb_queue_head_init (&tmp);
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
[email protected]
AI reviewRe: [PATCH v3 net-next 1/7] tcp: Refactor the first loop in tcp_collapse().
Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…
Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.
Low priority / nit picks for your consideration:
- [Low] The commit "tcp: Refactor the first loop in tcp_collapse()" is titled as a refactor.
- [Low] In tcp_collapse() (net/ipv4/tcp_input.c), the patch merges the !skb_frags_readable(skb) test into the condition directly below the…
--
tcp: Refactor the first loop in tcp_collapse().
This patch restructures the first loop in tcp_collapse(). SYN/FIN skbs and skbs with unreadable frags now go to skip_this, which removes end_of_skbs and the rechecks after the loop. The skb_frags_readable() test also moves below the fully-covered check, and the v2 note documents the SYN/FIN overlap behaviour change.
Quoted 5 lines
net/ipv4/tcp_input.c +0
-0@@ -5849,23 +5849,17 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,
[ ... ]
Quoted 5 lines
restart:
net/ipv4/tcp_input.c +1
-1-for (end_of_skbs = true; skb !=NULL && skb != tail; skb = n) { +for (; skb && skb != tail; skb = n) { n =tcp_skb_next (skb, list);
net/ipv4/tcp_input.c tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, · line 5864
Quoted 10 lines
net/ipv4/tcp_input.c +0
-5-if (!skb_frags_readable (skb)) - goto skip_this; -/* No new bits? It is possible on ofo queue. */ if (!before (start,TCP_SKB_CB (skb)->end_seq)) { skb =tcp_collapse_one (sk, skb, list, root); -if (!skb) -break ; goto restart; }
[Severity: Low]
In tcp_collapse(), the skb_frags_readable() test now runs after the "No new bits?" check. Should the commit message describe what this changes for unreadable (devmem/net_iov) skbs?
Before this patch, an unreadable skb that was fully covered by start always went to skip_this. It stayed in the receive queue or the ofo rbtree, and this line could move start backwards:
start = TCP_SKB_CB(skb)->end_seq;
With this patch, the same skb reaches tcp_collapse_one() first. It is unlinked or rb_erase()d and freed, and start only moves forward.
The commit message only says:
Also, skb_frags_readable() should be tested after the fully overlapping check.
It gives no reason for the move. It also does not say that fully covered unreadable skbs are now freed.
The v2 note already covers the SYN/FIN change. Could it also cover this one? The new behaviour looks fine to me, so this is only about the commit message.
Quoted 14 lines
net/ipv4/tcp_input.c +6
-4@@ -5874,27 +5868,25 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,* - bloated or contains data before "start" or * overlaps to the next one and mptcp allow collapsing. */ -if (!(TCP_SKB_CB (skb)->tcp_flags & (TCPHDR_SYN |TCPHDR_FIN )) && - (tcp_win_from_space (sk, skb->truesize) > skb->len || -before (TCP_SKB_CB (skb)->seq, start))) { - end_of_skbs = false; +if (!skb_frags_readable (skb) || +TCP_SKB_CB (skb)->tcp_flags & (TCPHDR_SYN |TCPHDR_FIN )) + goto skip_this; + +if (tcp_win_from_space (sk, skb->truesize) > skb->len || +before (TCP_SKB_CB (skb)->seq, start))
net/ipv4/tcp_input.c tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, · line 5889
Quoted 10 lines
net/ipv4/tcp_input.c +1
-4break ; - }if (n && n != tail &&skb_frags_readable (n) &&tcp_skb_can_collapse_rx (skb, n) && -TCP_SKB_CB (skb)->end_seq !=TCP_SKB_CB (n)->seq) { - end_of_skbs = false; +TCP_SKB_CB (skb)->end_seq !=TCP_SKB_CB (n)->seq)break ; - }
[Severity: Low]
This isn't a bug, but the readability test now sits directly under the comment in tcp_collapse() that lists the conditions for the first skb to collapse:
/* The first skb to collapse is:
* - not SYN/FIN and
* - bloated or contains data before "start" or
* overlaps to the next one and mptcp allow collapsing.
*/
The comment does not say that the skb's frags must be readable. It also does not mention the skb_frags_readable(n) requirement in the overlap check.
A later patch in the series rewrites this comment as "not SYN/FIN and the unread portion starting from "start" is bloated". That version still leaves out readability.
Would it be worth adding the readability requirement to the comment?
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261119071649.374106-1-kuniyu%40google.com
Kuniyuki Iwashima
reviewerPATCH v3 2/7 tcp: Don't collapse high density skb.
In reply to Kuniyuki Iwashimatcp_collapse() starts collapsing skb to a new skb if either of the following is true:
1. skb is less dense compared to tp->scaling_ratio
2. skb has read data before @start
However, this could make situation worse.
The new skb size is SKB_TRUESIZE(SKB_MAX_ORDER(0, 0)) at most, and with PAGE_SIZE being 4K, its scaling_ratio is 222 (86%).
If 4K-MSS GRO skb updates tp->scaling_ratio, it can be larger than 222.
Then, even the newly collapsed skb could be detected as bloated by the next tcp_collapse().
Also, even when only a few bytes are read from GRO skb, it is collapsed by the 2nd rule, making less-efficient skb.
Let's cap tp->scaling_ratio with the collapsed skb's maximum scaling_ratio and use unread bytes for bloat detection.
--- net/ipv4/tcp_input.c | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-)
net/ipv4/tcp_input.c +20 -4
@@ -5818,6 +5818,19 @@ static struct sk_buff *tcp_skb_next(struct sk_buff *skb, struct sk_buff_head *lireturn skb_rb_next (skb); } +#define TCP_COLLAPSE_MAX_SIZE SKB_MAX_ORDER(0, 0) +#define TCP_COLLAPSE_SCALING_RATIO \ + ((TCP_COLLAPSE_MAX_SIZE << TCP_RMEM_TO_WIN_SCALE) / \ + (SKB_TRUESIZE(TCP_COLLAPSE_MAX_SIZE))) + +static bool tcp_collapse_skb_bloated (const struct sk_buff *skb, +u32 start,u8 scaling_ratio) +{ +int unread =TCP_SKB_CB (skb)->end_seq - start; + +return __tcp_win_from_space (scaling_ratio, skb->truesize) > unread; +} +static struct sk_buff *tcp_collapse_one (struct sock *sk,struct sk_buff *skb,struct sk_buff_head *list,struct rb_root *root)
@@ -5849,6 +5862,10 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, {struct sk_buff *skb = head, *n;struct sk_buff_head tmp; +u8 scaling_ratio; + + scaling_ratio =min (tcp_sk (sk)->scaling_ratio, +TCP_COLLAPSE_SCALING_RATIO );/* First, check that queue is collapsible and find * the point where collapsing can be useful.
@@ -5865,15 +5882,14 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,/* The first skb to collapse is: * - not SYN/FIN and -* - bloated or contains data before "start" or +* - the unread portion starting from "start" is bloated, or * overlaps to the next one and mptcp allow collapsing. */ if (!skb_frags_readable (skb) ||TCP_SKB_CB (skb)->tcp_flags & (TCPHDR_SYN |TCPHDR_FIN )) goto skip_this; -if (tcp_win_from_space (sk, skb->truesize) > skb->len || -before (TCP_SKB_CB (skb)->seq, start)) +if (tcp_collapse_skb_bloated (skb, start, scaling_ratio))break ; if (n && n != tail && skb_frags_readable(n) &&
@@ -5892,7 +5908,7 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,__skb_queue_head_init (&tmp);while (before (start, end)) { -int copy =min_t (int,SKB_MAX_ORDER (0 ,0 ), end - start); +int copy =min_t (int,TCP_COLLAPSE_MAX_SIZE , end - start);struct sk_buff *nskb; nskb =alloc_skb (copy,GFP_ATOMIC );
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Kuniyuki Iwashima
reviewerPATCH v3 3/7 tcp: Stop collapsing if not bloated.
In reply to Kuniyuki IwashimaEven when a skb is not bloated, tcp_collapse() starts collapsing if the next skb has overlapping data.
Also, tcp_collapse() does not stop until it reaches the tail or unmergable skb (SYN/FIN, unreadable frags).
Assume we detect a low-density skb followed by fully-packed 4K-MSS GRO skbs:
skb->len truesize scaling_ratio skb #1 1448 2944 125 (49%) skb #2 65536 66432 252 (98%) skb #3 65536 66432 252 (98%)
...
skb #9 65536 66432 252 (98%)
--------------------------------------------
total 534400
Then, even the high-density skbs are repacked into lower-density skbs, and we end up consuming much more memory.
skb->len truesize scaling_ratio nskb #1 3776 4352 222 (86%) nskb #2 3776 4352 222 (86%)
...
nskb #139 3776 4352 222 (86%)
nskb #140 872 2304 96 (37%)
--------------------------------------------
total 607232 (+72832!)
Even if we find a collapsible skb, we should not collapse subsequent skbs with scaling_ratio >= TCP_COLLAPSE_SCALING_RATIO.
Conversely, even if tp->scaling_ratio is smaller than TCP_COLLAPSE_SCALING_RATIO, we should repack skbs once we start collapsing, which results in higher-density skb.
Let's remove the next skb condition in the first loop, search for collapsible bloated skb range, and repeat collapsing for each range.
Note that even when the next skb is not bloated, we must collapse it for OOO rbtree if it has overlapping data.
overlap = !list && before(TCP_SKB_CB(n)->seq, sub_end); ... if (!overlap && !tcp_collapse_skb_bloated(n, sub_end, TCP_COLLAPSE_SCALING_RATIO)) break;
For example, bloated skb_1 and non-bloated skb_2 have overlapping data and only skb_1 is collapsed to nskb_1 and nskb_2.
skb_1 = [1000, 5000]
skb_2 = [2000, 66000]
Then, nskb_2 will be inserted after skb_2 in rbtree, wrongly setting tp->ooo_last_skb to 5000.
nskb_1 = [1000, 4776]
skb_2 = [2000, 66000]
nskb_2 = [4776, 5000]
This case is still inefficient, but a later patch handles this.
On the other hand, if an overlapping skb on the OOO rbtree cannot be collapsed, we skip the range instead of breaking out, as splitting the range could insert the tail nskb after that skb and break the same rbtree ordering.
Another notable thing is that tcp_skb_can_collapse_rx() now checks candidates against the first skb before mptcp_skb_ext_move(), not against each nskb.
When a skb with an MPTCP ext spans multiple nskbs, collapsing previously stopped at the next skb with the same ext because later nskbs lacked the ext.
skb1 (ext A), skb2 (ext A)
nskb1 (ext A), nskb2 (no ext) ^
^- not collapsible -'
Now such skbs are also collapsed with the redundant ext dropped, while the first nskb still carries the same mapping in sequence order.
skb1 (ext A), skb2 (ext A)
nskb1 (ext A), nskb2 (no ext) <-' collapsed into nskb2
---
v3:
* Remove fully-overlapping skb in the 2nd loop
* Skip range on overlapping unmergeable ofo skb
* Update tcp_collapse() comment
v2: Describe slight behavioural change for MPTCP
--- net/ipv4/tcp_input.c | 83 ++++++++++++++++++++++++++++---------------- 1 file changed, 53 insertions(+), 30 deletions(-)
net/ipv4/tcp_input.c +53 -30
@@ -5848,8 +5848,8 @@ static struct sk_buff *tcp_collapse_one(struct sock *sk, struct sk_buff *skb,return next; } -/* Collapse contiguous sequence of skbs head..tail with -* sequence numbers start..end. +/* Collapse bloated sub-ranges in contiguous sequence of skbs +* head..tail starting from sequence number start. * * If tail is NULL, this means until the end of the queue. *
@@ -5858,15 +5858,18 @@ static struct sk_buff *tcp_collapse_one(struct sock *sk, struct sk_buff *skb,*/ static void tcp_collapse (struct sock *sk,struct sk_buff_head *list,struct rb_root *root, -struct sk_buff *head,struct sk_buff *tail,u32 start,u32 end) +struct sk_buff *head,struct sk_buff *tail,u32 start) {struct sk_buff *skb = head, *n;struct sk_buff_head tmp;u8 scaling_ratio; +u32 sub_end; scaling_ratio =min (tcp_sk (sk)->scaling_ratio,TCP_COLLAPSE_SCALING_RATIO ); +__skb_queue_head_init (&tmp); +/* First, check that queue is collapsible and find * the point where collapsing can be useful. */
@@ -5882,38 +5885,59 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,/* The first skb to collapse is: * - not SYN/FIN and -* - the unread portion starting from "start" is bloated, or -* overlaps to the next one and mptcp allow collapsing. +* - the unread portion starting from "start" is bloated. */ -if (!skb_frags_readable (skb) || -TCP_SKB_CB (skb)->tcp_flags & (TCPHDR_SYN |TCPHDR_FIN )) - goto skip_this; - -if (tcp_collapse_skb_bloated (skb, start, scaling_ratio)) +if (skb_frags_readable (skb) && + !(TCP_SKB_CB (skb)->tcp_flags & (TCPHDR_SYN |TCPHDR_FIN )) && +tcp_collapse_skb_bloated (skb, start, scaling_ratio))break ; -if (n && n != tail &&skb_frags_readable (n) && -tcp_skb_can_collapse_rx (skb, n) && -TCP_SKB_CB (skb)->end_seq !=TCP_SKB_CB (n)->seq) -break ; - -skip_this:/* Decided to skip this, advance start seq. */ start =TCP_SKB_CB (skb)->end_seq; }if (!skb || skb == tail) -return ; + goto end; -__skb_queue_head_init (&tmp); +/* Second, find consecutive collapsible skb. */ + sub_end =TCP_SKB_CB (skb)->end_seq; + n =tcp_skb_next (skb, list); + +while (n && n != tail) { +bool overlap; + +if (!after (TCP_SKB_CB (n)->end_seq, sub_end)) { + n =tcp_collapse_one (sk, n, list, root); +continue ; + } + +/* seq and end_seq must increase monotonically for rbtree. */ + overlap = !list &&before (TCP_SKB_CB (n)->seq, sub_end); + +if (!skb_frags_readable (n) || +TCP_SKB_CB (n)->tcp_flags & (TCPHDR_SYN |TCPHDR_FIN ) || + !tcp_skb_can_collapse_rx (skb, n)) { +if (overlap) + goto skip; +break ; + } -while (before (start, end)) { -int copy =min_t (int,TCP_COLLAPSE_MAX_SIZE , end - start); +if (!overlap && + !tcp_collapse_skb_bloated (n, sub_end, +TCP_COLLAPSE_SCALING_RATIO )) +break ; + + sub_end =TCP_SKB_CB (n)->end_seq; + n =tcp_skb_next (n, list); + } + +while (before (start, sub_end)) { +int copy =min_t (int,TCP_COLLAPSE_MAX_SIZE , sub_end - start);struct sk_buff *nskb; nskb =alloc_skb (copy,GFP_ATOMIC );if (!nskb) -break ; + goto end;memcpy (nskb->cb, skb->cb,sizeof (skb->cb));TCP_SKB_CB (nskb)->has_rxtstamp = false;
@@ -5952,15 +5976,15 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, }if (!before (start,TCP_SKB_CB (skb)->end_seq)) { skb =tcp_collapse_one (sk, skb, list, root); -if (!skb || - skb == tail || - !tcp_skb_can_collapse_rx (nskb, skb) || - (TCP_SKB_CB (skb)->tcp_flags & (TCPHDR_SYN |TCPHDR_FIN )) || - !skb_frags_readable (skb)) - goto end; } } } + + goto restart; +skip: + start = sub_end; + skb = n; + goto restart; end: skb_queue_walk_safe(&tmp, skb, n)tcp_rbtree_insert (root, skb);
@@ -5999,7 +6023,7 @@ static void tcp_collapse_ofo_queue(struct sock *sk)if (range_truesize != head->truesize || end - start >=SKB_WITH_OVERHEAD (PAGE_SIZE )) {tcp_collapse (sk,NULL , &tp->out_of_order_queue, - head, skb, start, end); + head, skb, start); }else { sum_tiny += range_truesize;if (sum_tiny > sk->sk_rcvbuf >>3 )
@@ -6113,8 +6137,7 @@ static int tcp_prune_queue(struct sock *sk, const struct sk_buff *in_skb)if (!skb_queue_empty (&sk->sk_receive_queue))tcp_collapse (sk, &sk->sk_receive_queue,NULL ,skb_peek (&sk->sk_receive_queue), -NULL , - tp->copied_seq, tp->rcv_nxt); +NULL , tp->copied_seq);if (tcp_can_ingest (sk, in_skb))return 0 ;
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Re: [PATCH v3 net-next 3/7] tcp: Stop collapsing if not bloated.
Quoted 84 lines · Kuniyuki Iwashima
Even when a skb is not bloated,
tcp_collapse()starts collapsing if the next skb has overlapping data.Also,
tcp_collapse()does not stop until it reaches the tail or unmergable skb (SYN/FIN, unreadable frags).Assume we detect a low-density skb followed by fully-packed 4K-MSS GRO skbs:
skb->len truesize scaling_ratio skb #1 1448 2944 125 (49%) skb #2 65536 66432 252 (98%) skb #3 65536 66432 252 (98%)...
skb #9 65536 66432 252 (98%)
--------------------------------------------
total 534400Then, even the high-density skbs are repacked into lower-density skbs, and we end up consuming much more memory.
skb->len truesize scaling_ratio nskb #1 3776 4352 222 (86%) nskb #2 3776 4352 222 (86%)...
nskb #139 3776 4352 222 (86%)
nskb #140 872 2304 96 (37%)
--------------------------------------------
total 607232 (+72832!)Even if we find a collapsible skb, we should not collapse subsequent skbs with
scaling_ratio>=TCP_COLLAPSE_SCALING_RATIO.Conversely, even if
tp->scaling_ratiois smaller thanTCP_COLLAPSE_SCALING_RATIO, we should repack skbs once we start collapsing, which results in higher-density skb.Let's remove the next skb condition in the first loop, search for collapsible bloated skb range, and repeat collapsing for each range.
Note that even when the next skb is not bloated, we must collapse it for OOO rbtree if it has overlapping data.
overlap = !list && before(TCP_SKB_CB(n)->seq, sub_end); ... if (!overlap && !tcp_collapse_skb_bloated(n, sub_end, TCP_COLLAPSE_SCALING_RATIO)) break;For example, bloated
skb_1and non-bloatedskb_2have overlapping data and onlyskb_1is collapsed tonskb_1andnskb_2.skb_1 = [1000, 5000] skb_2 = [2000, 66000]Then,
nskb_2will be inserted afterskb_2in rbtree, wrongly settingtp->ooo_last_skbto 5000.
nskb_1= [1000, 4776]
skb_2= [2000, 66000]
nskb_2= [4776, 5000]This case is still inefficient, but a later patch handles this.
On the other hand, if an overlapping skb on the OOO rbtree cannot be collapsed, we skip the range instead of breaking out, as splitting the range could insert the tail nskb after that skb and break the same rbtree ordering.
Another notable thing is that
tcp_skb_can_collapse_rx()now checks candidates against the first skb beforemptcp_skb_ext_move(), not against each nskb.When a skb with an MPTCP ext spans multiple nskbs, collapsing previously stopped at the next skb with the same ext because later nskbs lacked the ext.
skb1 (ext A), skb2 (ext A)
nskb1 (ext A), nskb2 (no ext) ^
^- not collapsible -'
Quoted 8 lines
Now such skbs are also collapsed with the redundant ext dropped, while the first nskb still carries the same mapping in sequence order.
skb1 (ext A), skb2 (ext A)
nskb1 (ext A), nskb2 (no ext) <-' collapsed into nskb2Signed-off-by Kuniyuki Iwashima <[email protected]>
Re: [PATCH v3 net-next 3/7] tcp: Stop collapsing if not bloated.
In reply to Kuniyuki IwashimaHi Kuniyuki,
Quoted 5 lines · Kuniyuki Iwashima
Even when a skb is not bloated,
tcp_collapse()starts collapsing if the next skb has overlapping data.Also,
tcp_collapse()does not stop until it reaches the tail or unmergable skb (SYN/FIN, unreadable frags).
(...)
Quoted 4 lines
On the other hand, if an overlapping skb on the OOO rbtree cannot be collapsed, we skip the range instead of breaking out, as splitting the range could insert the tail nskb after that skb and break the same rbtree ordering.
Thank you for having added this ...
Quoted 12 lines
Another notable thing is that
tcp_skb_can_collapse_rx()now checks candidates against the first skb beforemptcp_skb_ext_move(), not against each nskb.When a skb with an MPTCP ext spans multiple nskbs, collapsing previously stopped at the next skb with the same ext because later nskbs lacked the ext.
skb1 (ext A), skb2 (ext A)
nskb1 (ext A), nskb2 (no ext) ^
^- not collapsible -'
Quoted 6 lines
Now such skbs are also collapsed with the redundant ext dropped, while the first nskb still carries the same mapping in sequence order.
skb1 (ext A), skb2 (ext A)
nskb1 (ext A), nskb2 (no ext) <-' collapsed into nskb2
... and that!
Cheers,
Matt
Signature · 1 line
Sponsored by the NGI0 Core fund.
[email protected]
AI reviewRe: [PATCH v3 net-next 3/7] tcp: Stop collapsing if not bloated.
In reply to Kuniyuki IwashimaThank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…
Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.
Low priority / nit picks for your consideration:
- [Low] This patch changes what tcp_collapse() does, but the comments describing it are now out of date.
--
tcp: Stop collapsing if not bloated.
This patch changes tcp_collapse() to look for sub-ranges that start with a bloated skb. Each range stops at the first dense, non-overlapping skb, and collapsing repeats for every such range. On the OOO rbtree, overlapping skbs are still merged whatever their density, and a range is skipped when an overlapping skb cannot be merged.
Quoted 15 lines
net/ipv4/tcp_input.c +2
-2@@ -5848,8 +5848,8 @@ static struct sk_buff *tcp_collapse_one(struct sock *sk, struct sk_buff *skb,return next; } -/* Collapse contiguous sequence of skbs head..tail with -* sequence numbers start..end. +/* Collapse bloated sub-ranges in contiguous sequence of skbs +* head..tail starting from sequence number start. * * If tail is NULL, this means until the end of the queue. *
[ ... ]
Quoted 1 line
net/ipv4/tcp_input.c +0
-0@@ -5882,38 +5885,59 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,
[ ... ]
Quoted 19 lines
net/ipv4/tcp_input.c +19
-0+/* Second, find consecutive collapsible skb. */ + sub_end =TCP_SKB_CB (skb)->end_seq; + n =tcp_skb_next (skb, list); + +while (n && n != tail) { +bool overlap; + +if (!after (TCP_SKB_CB (n)->end_seq, sub_end)) { + n =tcp_collapse_one (sk, n, list, root); +continue ; + } + +/* seq and end_seq must increase monotonically for rbtree. */ + overlap = !list &&before (TCP_SKB_CB (n)->seq, sub_end); + +if (!skb_frags_readable (n) || +TCP_SKB_CB (n)->tcp_flags & (TCPHDR_SYN |TCPHDR_FIN ) || + !tcp_skb_can_collapse_rx (skb, n)) { +if (overlap)
net/ipv4/tcp_input.c tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, · line 5928
Quoted 10 lines
net/ipv4/tcp_input.c +7
-2+ goto skip; +break ; + } -while (before (start, end)) { -int copy =min_t (int,TCP_COLLAPSE_MAX_SIZE , end - start); +if (!overlap && + !tcp_collapse_skb_bloated (n, sub_end, +TCP_COLLAPSE_SCALING_RATIO )) +break ;
[Severity: Low]
This isn't a bug, but are the comments around tcp_collapse() still accurate after this change?
The new tcp_collapse() header says it collapses "bloated sub-ranges". On the OOO rbtree, though, this loop does more than that:
- it pulls in non-bloated skbs when overlap is true, because the tcp_collapse_skb_bloated() check is skipped
- it frees skbs that sub_end fully covers, via tcp_collapse_one()
- it skips the whole range with goto skip when an overlapping skb can't be merged
These overlap rules keep the rbtree ordered. Right now they are only described in the commit message and the one-line inline comment.
The comment above tcp_collapse_ofo_queue() is also unchanged:
/* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
* and tcp_collapse() them until all the queue is collapsed. */
With this patch, tcp_collapse() repacks only sub-ranges that start at a bloated skb, and it leaves dense skbs in place. So the queue is no longer fully collapsed.
Both comments are still unchanged at the end of the series. By then, tcp_collapse() also skips ranges whose repacked skbs would not be denser, and it caps the total size with TCP_COLLAPSE_MAX_TOTAL_SIZE.
Could these two comments be updated to describe the sub-range and overlap behavior?
[ ... ]
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261119071649.374106-1-kuniyu%40google.com
Kuniyuki Iwashima
reviewerPATCH v3 4/7 tcp: Skip collapsing if collapsed skb is less-dense.
In reply to Kuniyuki IwashimaOnce tcp_collapse() finds a collapsible skb, it collapses consecutive bloated skbs.
However, the end result could be the same or larger than as is in some cases:
1. skb is already minimum
If SKB_HEAD_ALIGN(len) <= SKB_SMALL_HEAD_CACHE_SIZE, skb is allocated from skbuff_small_head, and skb->truesize never changes.
2. SKB_HEAD_ALIGN() and kmalloc_size_roundup() in alloc_skb()
Assume two bloated skbs with len = 1448 B (truesize =
2304 B, scaling_ratio = 160) and len = 300 B (truesize =
896 B, scaling_ratio = 85), whose total truesize is
3200 B.
Collapsing them calls alloc_skb(1748), which rounds up
SKB_HEAD_ALIGN(1748) = 2112 B to 4096 B and allocates a
new skb with truesize = 4352 B (+1152 B!).Even worse, in case 1, such a skb is reallocated repeatedly by every tcp_collapse() in vain.
Let's calculate the final collapsed truesize before collapsing skbs and skip the range if it does not shrink.
We could allocate skbs first and calculate the new truesize, but given tcp_collapse() is called under memory pressure, we want to avoid unnecessary allocation.
Note that kmalloc_reserve_size() uses __always_inline so that this change does not affect non-FDO builds, and returns 0 when skb_small_head_cache is used, similar to kmalloc_pfmemalloc().
---
v3:
* Remove redundant kmalloc_size_roundup()
* Rename helper with skb_ prefix
* Declare {old,new}_truesize as unsigned int
v2: Add compute_skb_truesize() instead of macro
--- include/linux/skbuff.h | 2 ++ net/core/skbuff.c | 27 +++++++++++++++++++++++---- net/ipv4/tcp_input.c | 15 +++++++++++++++ 3 files changed, 40 insertions(+), 4 deletions(-)
include/linux/skbuff.h +2 -0
@@ -274,6 +274,8 @@ SKB_DATA_ALIGN(sizeof(struct sk_buff)) + \ SKB_DATA_ALIGN(sizeof(struct skb_shared_info))) +unsigned int skb_head_truesize (unsigned int size,gfp_t flags); +struct net_device ;struct scatterlist ;struct pipe_inode_info ;
net/core/skbuff.c +23 -4
@@ -589,6 +589,17 @@ struct sk_buff *napi_build_skb(void *data, unsigned int frag_size) }EXPORT_SYMBOL (napi_build_skb); +static __always_inline size_t kmalloc_reserve_size(unsigned int size, gfp_t flags) +{ +size_t obj_size =SKB_HEAD_ALIGN (size); + +if (obj_size <=SKB_SMALL_HEAD_CACHE_SIZE && + !(flags &KMALLOC_NOT_NORMAL_BITS )) +return 0 ; + +return kmalloc_size_roundup (obj_size); +} +static void *kmalloc_pfmemalloc (size_t obj_size,gfp_t flags,int node) {if (!gfp_pfmemalloc_allowed (flags))
@@ -612,9 +623,8 @@ static void *kmalloc_reserve(unsigned int *size, gfp_t flags, int node,size_t obj_size;void *obj; - obj_size =SKB_HEAD_ALIGN (*size); -if (obj_size <=SKB_SMALL_HEAD_CACHE_SIZE && - !(flags &KMALLOC_NOT_NORMAL_BITS )) { + obj_size =kmalloc_reserve_size (*size, flags); +if (!obj_size) { obj =kmem_cache_alloc_node (net_hotdata.skb_small_head_cache, flags | __GFP_NOMEMALLOC | __GFP_NOWARN, node);
@@ -627,7 +637,6 @@ static void *kmalloc_reserve(unsigned int *size, gfp_t flags, int node,return kmalloc_pfmemalloc (0 , flags, node); } - obj_size =kmalloc_size_roundup (obj_size);/* The following cast might truncate high-order bits of obj_size, this * is harmless because kmalloc(obj_size >= 2^32) will fail anyway. */
@@ -651,6 +660,16 @@ static void *kmalloc_reserve(unsigned int *size, gfp_t flags, int node,return obj; } +unsigned int skb_head_truesize (unsigned int size,gfp_t flags) +{ +size_t obj_size =kmalloc_reserve_size (size, flags); + +if (!obj_size) + obj_size =SKB_SMALL_HEAD_CACHE_SIZE ; + +return obj_size +SKB_DATA_ALIGN (sizeof (struct sk_buff )); +} +/* Allocate a new skbuff. We do this ourselves so we can fill in a few * 'private' fields and also do memory statistics to find all the * [BEEP] leaks.
net/ipv4/tcp_input.c +15 -0
@@ -5860,8 +5860,10 @@ static void tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, struct sk_buff *head, struct sk_buff *tail, u32 start) { + unsigned int old_truesize, new_truesize;struct sk_buff *skb = head, *n;struct sk_buff_head tmp; +int remainder, nskbs;u8 scaling_ratio;u32 sub_end;
@@ -5901,6 +5903,7 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,/* Second, find consecutive collapsible skb. */ sub_end =TCP_SKB_CB (skb)->end_seq; + old_truesize = skb->truesize; n =tcp_skb_next (skb, list);while (n && n != tail) {
@@ -5928,9 +5931,21 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,break ; sub_end =TCP_SKB_CB (n)->end_seq; + old_truesize += n->truesize; n =tcp_skb_next (n, list); } +/* Third, check if the new skbs have high density. */ + nskbs = (sub_end - start) /TCP_COLLAPSE_MAX_SIZE ; + new_truesize = nskbs *SKB_TRUESIZE (TCP_COLLAPSE_MAX_SIZE ); + + remainder = (sub_end - start) %TCP_COLLAPSE_MAX_SIZE ; +if (remainder) + new_truesize +=skb_head_truesize (remainder,GFP_ATOMIC ); + +if (old_truesize <= new_truesize) + goto skip; +while (before (start, sub_end)) {int copy =min_t (int,TCP_COLLAPSE_MAX_SIZE , sub_end - start);struct sk_buff *nskb;
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Re: [PATCH v3 net-next 4/7] tcp: Skip collapsing if collapsed skb is less-dense.
Quoted 34 lines · Kuniyuki Iwashima
Once
tcp_collapse()finds a collapsible skb, it collapses consecutive bloated skbs.However, the end result could be the same or larger than as is in some cases:
1. skb is already minimum
If
SKB_HEAD_ALIGN(len)<=SKB_SMALL_HEAD_CACHE_SIZE, skb is allocated fromskbuff_small_head, andskb->truesizenever changes.2.
SKB_HEAD_ALIGN()andkmalloc_size_roundup()inalloc_skb()Assume two bloated skbs with len = 1448 B (truesize = 2304 B, scaling_ratio = 160) and len = 300 B (truesize = 896 B, scaling_ratio = 85), whose total truesize is 3200 B. Collapsing them calls alloc_skb(1748), which rounds up SKB_HEAD_ALIGN(1748) = 2112 B to 4096 B and allocates a new skb with truesize = 4352 B (+1152 B!).Even worse, in case 1, such a skb is reallocated repeatedly by every
tcp_collapse()in vain.Let's calculate the final collapsed truesize before collapsing skbs and skip the range if it does not shrink.
We could allocate skbs first and calculate the new truesize, but given
tcp_collapse()is called under memory pressure, we want to avoid unnecessary allocation.
Quoted 5 lines
Note that
kmalloc_reserve_size()uses__always_inlineso that this change does not affect non-FDO builds, and returns 0 whenskb_small_head_cacheis used, similar tokmalloc_pfmemalloc().Signed-off-by Kuniyuki Iwashima <[email protected]>
Kuniyuki Iwashima
reviewerPATCH v3 5/7 tcp: Allocate all new skb before collapsing.
In reply to Kuniyuki IwashimaAt the final stage, tcp_collapse() iterates over collapsible candidate skbs and repacks them to new skbs.
In each iteration, a new skb is allocated and inserted to the receive queue or a temporary list for RB tree.
If alloc_skb() fails while splitting a large bloated skb across multiple new skbs, the partially-copied skb is not removed and new skbs remain in the queue as duplicates, consuming more memory.
It is only when all candidates are properly collapsed that we can save memory.
To avoid complicated rollback, let's preallocate skbs before collapsing.
Now all skb in [start, sub_end) must be allocated in a batch, so the section size is capped at TCP_COLLAPSE_MAX_TOTAL_SIZE (16 skbs), except for the first single skb.
Once the size exceeds the limit, the remaining skbs are re-evaluated from restart:.
Legitimate overlaps (retransmits with a different segmentation) only involve a few skbs, so if an overlapping OOO chain reaches the limit, we simply skip it.
Note that the next skb can be skipped if its density already meets tp->scaling_ratio, and each cut adds at most one remainder skb (~3.4% worst-case truesize overhead on 4 KiB pages), which is a small tradeoff to bound the temporary allocation.
---
v3: Make TCP_COLLAPSE_MAX_TOTAL_SIZE hard-limit for multiple skbs
--- net/ipv4/tcp_input.c | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-)
net/ipv4/tcp_input.c +32 -9
@@ -5822,6 +5822,11 @@ static struct sk_buff *tcp_skb_next(struct sk_buff *skb, struct sk_buff_head *li#define TCP_COLLAPSE_SCALING_RATIO \ ((TCP_COLLAPSE_MAX_SIZE << TCP_RMEM_TO_WIN_SCALE) / \ (SKB_TRUESIZE(TCP_COLLAPSE_MAX_SIZE))) +/* Cap pool preallocation per sub-range to at most 16 skbs in seq +* space. A single first skb exceeding this is still collapsed, +* whereas an exceeding overlapping ofo range is skipped. +*/ +#define TCP_COLLAPSE_MAX_TOTAL_SIZE (TCP_COLLAPSE_MAX_SIZE * 16)static bool tcp_collapse_skb_bloated (const struct sk_buff *skb,u32 start,u8 scaling_ratio)
@@ -5862,8 +5867,9 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, {unsigned int old_truesize, new_truesize;struct sk_buff *skb = head, *n; -struct sk_buff_head tmp; +struct sk_buff_head tmp, pool;int remainder, nskbs; +struct sk_buff *nskb;u8 scaling_ratio;u32 sub_end;
@@ -5871,6 +5877,7 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, TCP_COLLAPSE_SCALING_RATIO);__skb_queue_head_init (&tmp); +__skb_queue_head_init (&pool);/* First, check that queue is collapsible and find * the point where collapsing can be useful.
@@ -5926,8 +5933,9 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, }if (!overlap && - !tcp_collapse_skb_bloated (n, sub_end, -TCP_COLLAPSE_SCALING_RATIO )) + (TCP_SKB_CB (n)->end_seq - start >=TCP_COLLAPSE_MAX_TOTAL_SIZE || + !tcp_collapse_skb_bloated (n, sub_end, +TCP_COLLAPSE_SCALING_RATIO )))break ; sub_end =TCP_SKB_CB (n)->end_seq;
@@ -5935,25 +5943,38 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, n =tcp_skb_next (n, list); } +if (sub_end !=TCP_SKB_CB (skb)->end_seq && + sub_end - start >=TCP_COLLAPSE_MAX_TOTAL_SIZE ) + goto skip; +/* Third, check if the new skbs have high density. */ nskbs = (sub_end - start) /TCP_COLLAPSE_MAX_SIZE ; new_truesize = nskbs *SKB_TRUESIZE (TCP_COLLAPSE_MAX_SIZE ); remainder = (sub_end - start) %TCP_COLLAPSE_MAX_SIZE ; -if (remainder) +if (remainder) { + nskbs++; new_truesize +=skb_head_truesize (remainder,GFP_ATOMIC ); + }else { + remainder =TCP_COLLAPSE_MAX_SIZE ; + }if (old_truesize <= new_truesize) goto skip; -while (before (start, sub_end)) { -int copy =min_t (int,TCP_COLLAPSE_MAX_SIZE , sub_end - start); -struct sk_buff *nskb; - - nskb =alloc_skb (copy,GFP_ATOMIC ); +while (nskbs--) { + nskb =alloc_skb (nskbs ?TCP_COLLAPSE_MAX_SIZE : remainder, +GFP_ATOMIC );if (!nskb) goto end; +__skb_queue_tail (&pool, nskb); + } + +while (before (start, sub_end)) { +int copy =min_t (int,TCP_COLLAPSE_MAX_SIZE , sub_end - start); + + nskb =__skb_dequeue (&pool);memcpy (nskb->cb, skb->cb,sizeof (skb->cb));TCP_SKB_CB (nskb)->has_rxtstamp = false;skb_copy_decrypted (nskb, skb);
@@ -6003,6 +6024,8 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, end: skb_queue_walk_safe(&tmp, skb, n)tcp_rbtree_insert (root, skb); + +__skb_queue_purge_reason (&pool,SKB_CONSUMED ); }/* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Re: [PATCH v3 net-next 5/7] tcp: Allocate all new skb before collapsing.
Quoted 88 lines · Kuniyuki Iwashima
At the final stage,
tcp_collapse()iterates over collapsible candidate skbs and repacks them to new skbs.In each iteration, a new skb is allocated and inserted to the receive queue or a temporary list for RB tree.
If
alloc_skb()fails while splitting a large bloated skb across multiple new skbs, the partially-copied skb is not removed and new skbs remain in the queue as duplicates, consuming more memory.It is only when all candidates are properly collapsed that we can save memory.
To avoid complicated rollback, let's preallocate skbs before collapsing.
Now all skb in [start,
sub_end) must be allocated in a batch, so the section size is capped atTCP_COLLAPSE_MAX_TOTAL_SIZE(16 skbs), except for the first single skb.Once the size exceeds the limit, the remaining skbs are re-evaluated from restart:.
Legitimate overlaps (retransmits with a different segmentation) only involve a few skbs, so if an overlapping OOO chain reaches the limit, we simply skip it.
Note that the next skb can be skipped if its density already meets
tp->scaling_ratio, and each cut adds at most one remainder skb (~3.4% worst-case truesize overhead on 4 KiB pages), which is a small tradeoff to bound the temporary allocation.Signed-off-by Kuniyuki Iwashima <[email protected]>---
v3: MakeTCP_COLLAPSE_MAX_TOTAL_SIZEhard-limit for multiple skbs--- net/ipv4/tcp_input.c | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-)net/ipv4/tcp_input.c +11
-3@@ -5822,6 +5822,11 @@ static struct sk_buff *tcp_skb_next(struct sk_buff *skb, struct sk_buff_head *li#define TCP_COLLAPSE_SCALING_RATIO \ ((TCP_COLLAPSE_MAX_SIZE << TCP_RMEM_TO_WIN_SCALE) / \ (SKB_TRUESIZE(TCP_COLLAPSE_MAX_SIZE))) +/* Cap pool preallocation per sub-range to at most 16 skbs in seq +* space. A single first skb exceeding this is still collapsed, +* whereas an exceeding overlapping ofo range is skipped. +*/ +#define TCP_COLLAPSE_MAX_TOTAL_SIZE (TCP_COLLAPSE_MAX_SIZE * 16)static bool tcp_collapse_skb_bloated (const struct sk_buff *skb,u32 start,u8 scaling_ratio)@@ -5862,8 +5867,9 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, {unsigned int old_truesize, new_truesize;struct sk_buff *skb = head, *n; -struct sk_buff_head tmp; +struct sk_buff_head tmp, pool;int remainder, nskbs; +struct sk_buff *nskb;u8 scaling_ratio;u32 sub_end;@@ -5871,6 +5877,7 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, TCP_COLLAPSE_SCALING_RATIO);__skb_queue_head_init (&tmp); +__skb_queue_head_init (&pool);/* First, check that queue is collapsible and find * the point where collapsing can be useful. @@ -5926,8 +5933,9 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, }if (!overlap && - !tcp_collapse_skb_bloated (n, sub_end, -TCP_COLLAPSE_SCALING_RATIO )) + (TCP_SKB_CB (n)->end_seq - start >=TCP_COLLAPSE_MAX_TOTAL_SIZE || + !tcp_collapse_skb_bloated (n, sub_end, +TCP_COLLAPSE_SCALING_RATIO )))break ; sub_end =TCP_SKB_CB (n)->end_seq;
net/ipv4/tcp_input.c tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, · line 5948
Quoted 6 lines
net/ipv4/tcp_input.c +3
-0@@ -5935,25 +5943,38 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, n =tcp_skb_next (n, list); } +if (sub_end !=TCP_SKB_CB (skb)->end_seq && + sub_end - start >=TCP_COLLAPSE_MAX_TOTAL_SIZE ) + goto skip;
This is fine for now, but note that a single 64K GRO skb overlapping a bloated skb is enough to reach the limit, and the bloated skb is then never collapsed. The range is walked again at every tcp_collapse_ofo_queue() call, for no gain.
A possible followup would be to cut the range instead of skipping it.
When @n overlaps and we do not want (or can not) merge it, we know that @n already contains [TCP_SKB_CB(n)->seq, sub_end), because skbs with end_seq <= sub_end were removed earlier in the loop.
So we could do :
sub_end = TCP_SKB_CB(n)->seq;
and collapse [start, sub_end) only, as long as sub_end is after start.
All new skbs would then have a seq smaller than TCP_SKB_CB(n)->seq, so the rbtree ordering is preserved, and we would not need to drag @n into the range.
After the copy, the skbs of the range that were not fully consumed would have to be freed, since the rest of their payload is in @n.
The same trick would also work for the unmergeable overlapping skb case added in patch 3.
I have not tested this, and this can be done later.
Kuniyuki Iwashima
reviewerRe: [PATCH v3 net-next 5/7] tcp: Allocate all new skb before collapsing.
Quoted 117 lines · Eric Dumazet
Quoted 88 lines · Kuniyuki Iwashima
At the final stage,
tcp_collapse()iterates over collapsible candidate skbs and repacks them to new skbs.In each iteration, a new skb is allocated and inserted to the receive queue or a temporary list for RB tree.
If
alloc_skb()fails while splitting a large bloated skb across multiple new skbs, the partially-copied skb is not removed and new skbs remain in the queue as duplicates, consuming more memory.It is only when all candidates are properly collapsed that we can save memory.
To avoid complicated rollback, let's preallocate skbs before collapsing.
Now all skb in [start,
sub_end) must be allocated in a batch, so the section size is capped atTCP_COLLAPSE_MAX_TOTAL_SIZE(16 skbs), except for the first single skb.Once the size exceeds the limit, the remaining skbs are re-evaluated from restart:.
Legitimate overlaps (retransmits with a different segmentation) only involve a few skbs, so if an overlapping OOO chain reaches the limit, we simply skip it.
Note that the next skb can be skipped if its density already meets
tp->scaling_ratio, and each cut adds at most one remainder skb (~3.4% worst-case truesize overhead on 4 KiB pages), which is a small tradeoff to bound the temporary allocation.Signed-off-by Kuniyuki Iwashima <[email protected]>---
v3: MakeTCP_COLLAPSE_MAX_TOTAL_SIZEhard-limit for multiple skbs--- net/ipv4/tcp_input.c | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-)net/ipv4/tcp_input.c +11
-3@@ -5822,6 +5822,11 @@ static struct sk_buff *tcp_skb_next(struct sk_buff *skb, struct sk_buff_head *li#define TCP_COLLAPSE_SCALING_RATIO \ ((TCP_COLLAPSE_MAX_SIZE << TCP_RMEM_TO_WIN_SCALE) / \ (SKB_TRUESIZE(TCP_COLLAPSE_MAX_SIZE))) +/* Cap pool preallocation per sub-range to at most 16 skbs in seq +* space. A single first skb exceeding this is still collapsed, +* whereas an exceeding overlapping ofo range is skipped. +*/ +#define TCP_COLLAPSE_MAX_TOTAL_SIZE (TCP_COLLAPSE_MAX_SIZE * 16)static bool tcp_collapse_skb_bloated (const struct sk_buff *skb,u32 start,u8 scaling_ratio)@@ -5862,8 +5867,9 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, {unsigned int old_truesize, new_truesize;struct sk_buff *skb = head, *n; -struct sk_buff_head tmp; +struct sk_buff_head tmp, pool;int remainder, nskbs; +struct sk_buff *nskb;u8 scaling_ratio;u32 sub_end;@@ -5871,6 +5877,7 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, TCP_COLLAPSE_SCALING_RATIO);__skb_queue_head_init (&tmp); +__skb_queue_head_init (&pool);/* First, check that queue is collapsible and find * the point where collapsing can be useful. @@ -5926,8 +5933,9 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, }if (!overlap && - !tcp_collapse_skb_bloated (n, sub_end, -TCP_COLLAPSE_SCALING_RATIO )) + (TCP_SKB_CB (n)->end_seq - start >=TCP_COLLAPSE_MAX_TOTAL_SIZE || + !tcp_collapse_skb_bloated (n, sub_end, +TCP_COLLAPSE_SCALING_RATIO )))break ; sub_end =TCP_SKB_CB (n)->end_seq;net/ipv4/tcp_input.c tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, · line 5948
Quoted 6 lines
net/ipv4/tcp_input.c +3
-0@@ -5935,25 +5943,38 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, n =tcp_skb_next (n, list); } +if (sub_end !=TCP_SKB_CB (skb)->end_seq && + sub_end - start >=TCP_COLLAPSE_MAX_TOTAL_SIZE ) + goto skip;This is fine for now, but note that a single 64K GRO skb overlapping a bloated skb is enough to reach the limit, and the bloated skb is then never collapsed. The range is walked again at every
tcp_collapse_ofo_queue()call, for no gain.A possible followup would be to cut the range instead of skipping it.
When @n overlaps and we do not want (or can not) merge it, we know that @n already contains [TCP_SKB_CB(n)->seq,
sub_end), because skbs withend_seq<=sub_endwere removed earlier in the loop.So we could do :
sub_end = TCP_SKB_CB(n)->seq;and collapse [start,
sub_end) only, as long assub_endis after start.All new skbs would then have a seq smaller than TCP_SKB_CB(n)->seq, so the rbtree ordering is preserved, and we would not need to drag @n into the range.
Quoted 7 lines
After the copy, the skbs of the range that were not fully consumed would have to be freed, since the rest of their payload is in @n.
The same trick would also work for the unmergeable overlapping skb case added in patch 3.
I have not tested this, and this can be done later.
Ah, this sounds good too, I'll follow up after your frag series.
Thank you !
[email protected]
AI reviewRe: [PATCH v3 net-next 5/7] tcp: Allocate all new skb before collapsing.
In reply to Kuniyuki IwashimaThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider.
Critical: 0 · High: 0 · Medium: 1 · Low: 0
If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).
- [Medium] In tcp_collapse() (net/ipv4/tcp_input.c), the new TCP_COLLAPSE_MAX_TOTAL_SIZE overlap check throws away the whole…
--
tcp: Allocate all new skb before collapsing.
This commit changes tcp_collapse() to preallocate every new skb for a sub-range into a temporary pool before copying. An alloc_skb() failure then no longer leaves partially collapsed duplicates in the queue. To bound that preallocation, the sub-range is capped at TCP_COLLAPSE_MAX_TOTAL_SIZE, except when the range is a single first skb. Overlapping OOO ranges that go over the cap are skipped.
Quoted 16 lines
net/ipv4/tcp_input.c +5
-0@@ -5822,6 +5822,11 @@ static struct sk_buff *tcp_skb_next(struct sk_buff *skb, struct sk_buff_head *li#define TCP_COLLAPSE_SCALING_RATIO \ ((TCP_COLLAPSE_MAX_SIZE << TCP_RMEM_TO_WIN_SCALE) / \ (SKB_TRUESIZE(TCP_COLLAPSE_MAX_SIZE))) +/* Cap pool preallocation per sub-range to at most 16 skbs in seq +* space. A single first skb exceeding this is still collapsed, +* whereas an exceeding overlapping ofo range is skipped. +*/ +#define TCP_COLLAPSE_MAX_TOTAL_SIZE (TCP_COLLAPSE_MAX_SIZE * 16)static bool tcp_collapse_skb_bloated (const struct sk_buff *skb,u32 start,u8 scaling_ratio)
[ ... ]
Quoted 13 lines
net/ipv4/tcp_input.c +3
-2@@ -5926,8 +5933,9 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, }if (!overlap && - !tcp_collapse_skb_bloated (n, sub_end, -TCP_COLLAPSE_SCALING_RATIO )) + (TCP_SKB_CB (n)->end_seq - start >=TCP_COLLAPSE_MAX_TOTAL_SIZE || + !tcp_collapse_skb_bloated (n, sub_end, +TCP_COLLAPSE_SCALING_RATIO )))break ; sub_end =TCP_SKB_CB (n)->end_seq;
net/ipv4/tcp_input.c tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, · line 5948
Quoted 6 lines
net/ipv4/tcp_input.c +3
-0@@ -5935,25 +5943,38 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, n =tcp_skb_next (n, list); } +if (sub_end !=TCP_SKB_CB (skb)->end_seq && + sub_end - start >=TCP_COLLAPSE_MAX_TOTAL_SIZE ) + goto skip;
[Severity: Medium]
Does this goto skip discard the whole [start, sub_end) range in tcp_collapse()? That would include the bloated non-overlapping skbs gathered before the overlapping one.
In the second loop, the new size cap is only checked when overlap is false. An OOO skb where
overlap = !list && before(TCP_SKB_CB(n)->seq, sub_end);
is true gets added to sub_end with no size check. If that pushes sub_end - start past TCP_COLLAPSE_MAX_TOTAL_SIZE, skip sets start = sub_end and skb = n. None of the earlier skbs get collapsed, even though they were collapsed before this patch.
Would it work to collapse only the prefix and stop before the skb that the overlapping one overlaps? tcp_data_queue_ofo() inserts a partial overlap after its predecessor, so the rbtree ordering should still hold.
TCP_COLLAPSE_MAX_TOTAL_SIZE is 16 * SKB_MAX_ORDER(0, 0). With 4 KiB pages that is 60416 bytes of sequence space, which is less than one 64 KB GRO/TSO skb. Can a single overlapping retransmit that was re-segmented or GRO-aggregated trigger this?
As an example, take contiguous bloated OOO skbs A1..A15 (about 22 KB), followed by B, which partially overlaps A15 and extends about 40 KB further.
Before this patch the range is collapsed, saving roughly 16 KB of truesize. After it, nothing is collapsed, and the same thing happens on every prune while B stays queued. tcp_prune_queue() then falls back to tcp_prune_ofo_queue(), which drops OOO data.
The commit message says:
Legitimate overlaps (retransmits with a different segmentation) only involve a few skbs, so if an overlapping OOO chain reaches the limit, we simply skip it.
Is this accurate, given that the check counts bytes and not skbs? The message also doesn't mention that the non-overlapping skbs before the overlap are skipped as well.
[ ... ]
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261119071649.374106-1-kuniyu%40google.com
Kuniyuki Iwashima
reviewerPATCH v3 6/7 tcp: Batch memory accounting in tcp_collapse().
In reply to Kuniyuki IwashimaOnce tcp_collapse_one() calls sock_rfree(), skb->truesize is reclaimed to sk->sk_forward_alloc by sk_mem_uncharge().
However, sk_mem_uncharge() rounds down sk->sk_forward_alloc immediately once it reaches 4K since commit 4890b686f408 ("net:
keep sk->sk_forward_alloc as small as possible").
This unnecessarily reclaims memory for newly allocated skbs, and the following skb_set_owner_r() for them underflows sk->sk_forward_alloc without sk_forced_mem_schedule().
Let's cache the delta during tcp_collapse() and batch accounting at the end.
Then, we no longer need sk_forced_mem_schedule(), and instead DEBUG_NET_WARN_ON_ONCE() is added to catch a future issue.
--- net/ipv4/tcp_input.c | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-)
net/ipv4/tcp_input.c +30 -5
@@ -5836,6 +5836,24 @@ static bool tcp_collapse_skb_bloated(const struct sk_buff *skb,return __tcp_win_from_space (scaling_ratio, skb->truesize) > unread; } +static int tcp_collapse_uncharge (struct sk_buff *skb) +{ +DEBUG_NET_WARN_ON_ONCE (skb->destructor != sock_rfree); + + skb->sk =NULL ; + skb->destructor =NULL ; + +return skb->truesize; +} + +static int tcp_collapse_charge (struct sk_buff *skb,struct sock *sk) +{ + skb->sk = sk; + skb->destructor = sock_rfree; + +return -skb->truesize; +} +static struct sk_buff *tcp_collapse_one (struct sock *sk,struct sk_buff *skb,struct sk_buff_head *list,struct rb_root *root)
@@ -5871,6 +5889,7 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,int remainder, nskbs;struct sk_buff *nskb;u8 scaling_ratio; +int released =0 ;u32 sub_end; scaling_ratio = min(tcp_sk(sk)->scaling_ratio,
@@ -5888,6 +5907,7 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,/* No new bits? It is possible on ofo queue. */ if (!before (start,TCP_SKB_CB (skb)->end_seq)) { + released +=tcp_collapse_uncharge (skb); skb =tcp_collapse_one (sk, skb, list, root); goto restart; }
@@ -5917,6 +5937,7 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,bool overlap;if (!after (TCP_SKB_CB (n)->end_seq, sub_end)) { + released +=tcp_collapse_uncharge (n); n =tcp_collapse_one (sk, n, list, root);continue ; }
@@ -5983,11 +6004,8 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,__skb_queue_before (list, skb, nskb); else __skb_queue_tail(&tmp, nskb); /* defer rbtree insertion */ -/* nskb is charged before the skbs it replaces are freed. -* Make sure sk->sk_forward_alloc can not become negative. -*/ -sk_forced_mem_schedule (sk, nskb->truesize); -skb_set_owner_r (nskb, sk); + + released +=tcp_collapse_charge (nskb, sk);mptcp_skb_ext_move (nskb, skb);/* Copy data, releasing collapsed skbs. */
@@ -6011,6 +6029,7 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, start += size; }if (!before (start,TCP_SKB_CB (skb)->end_seq)) { + released +=tcp_collapse_uncharge (skb); skb =tcp_collapse_one (sk, skb, list, root); } }
@@ -6026,6 +6045,12 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,tcp_rbtree_insert (root, skb);__skb_queue_purge_reason (&pool,SKB_CONSUMED ); + +if (released) { +DEBUG_NET_WARN_ON_ONCE (released <0 ); +atomic_sub (released, &sk->sk_rmem_alloc); +sk_mem_uncharge (sk, released); + } }/* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Kuniyuki Iwashima
reviewerPATCH v3 7/7 selftest: packetdrill: Add test for tcp_collapse().
In reply to Kuniyuki Iwashimatcp_collapse() now does not collapse high-density skbs and a low-density skb sandwiched by high-density skbs.
tcp_rcv_collapse_bloated.pkt verifies the behaviour by
1. set a large SO_RCVBUF
2. send one high-density skb with 100 bytes read()
3. send one high-density skb
4. send one low-density skb
5. send one high-density skb
6. send 30 low-density skbs
7. send one high-density skb
8. set a small SO_RCVBUF
9. send a small data to trigger tcp_collapse()
10. check TcpExtTCPRcvCollapsed via nstat
Without the series, the first high-density skb is collapsed. In addition, the first low-density skb drags the following high-density skb into collapsing, consuming more memory.
If we remove sk_forced_mem_schedule() without this series, sk->sk_forward_alloc becomes negative at the end of tcp_collapse().
Note that 30 segments are to make the memory savings large enough so that the margin can absorb minor size delta of struct sk_buff or L1_CACHE_BYTES across configs.
skb truesize, TCP_COLLAPSE_MAX_SIZE, TCP_COLLAPSE_SCALING_RATIO depend on PAGE_SIZE being 4K, so the test is skipped if getconf returns non-4K PAGE_SIZE.
--- .../selftests/net/packetdrill/ksft_runner.sh | 9 ++ .../packetdrill/tcp_rcv_collapse_bloated.pkt | 135 ++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 tools/testing/selftests/net/packetdrill/tcp_rcv_collapse_bloated.pkt
tools/testing/selftests/net/packetdrill/ksft_runner.sh +9 -0
@@ -44,6 +44,15 @@ if [ -z "$(which packetdrill)" ]; then exit "$KSFT_SKIP" fi +page_size=$(grep -E '^--define="?PAGE_SIZE=' $script | sed -E 's/.*PAGE_SIZE="?([0-9]+)"?.*/\1/') +if [[ -n "$page_size" ]]; then + cur_page_size=$(getconf PAGESIZE 2>/dev/null) + if [[ "$cur_page_size" != "$page_size" ]]; then + ktap_skip_all "requires PAGE_SIZE=$page_size (current: ${cur_page_size:-unknown})" + exit "$KSFT_SKIP" + fi +fi + declare -a optargs failfunc=ktap_test_fail
tools/testing/selftests/net/packetdrill/tcp_rcv_collapse_bloated.pkt new file +135 -0
135 lines not on this page · raw message
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Re: [PATCH v3 net-next 7/7] selftest: packetdrill: Add test for tcp_collapse().
Quoted 28 lines · Kuniyuki Iwashima
tcp_collapse()now does not collapse high-density skbs and a low-density skb sandwiched by high-density skbs.tcp_rcv_collapse_bloated.pkt verifies the behaviour by
1. set a large
SO_RCVBUF
2. send one high-density skb with 100 bytesread()
3. send one high-density skb
4. send one low-density skb
5. send one high-density skb
6. send 30 low-density skbs
7. send one high-density skb
8. set a smallSO_RCVBUF
9. send a small data to triggertcp_collapse()
10. check TcpExtTCPRcvCollapsed via nstatWithout the series, the first high-density skb is collapsed. In addition, the first low-density skb drags the following high-density skb into collapsing, consuming more memory.
If we remove
sk_forced_mem_schedule()without this series,sk->sk_forward_allocbecomes negative at the end oftcp_collapse().Note that 30 segments are to make the memory savings large enough so that the margin can absorb minor size delta of struct
sk_bufforL1_CACHE_BYTESacross configs.
Quoted 5 lines
skb truesize,
TCP_COLLAPSE_MAX_SIZE,TCP_COLLAPSE_SCALING_RATIOdepend onPAGE_SIZEbeing 4K, so the test is skipped if getconf returns non-4KPAGE_SIZE.Signed-off-by Kuniyuki Iwashima <[email protected]>
This series was applied to netdev/net-next.git (main) by Jakub Kicinski <[email protected]>:
Hello:
This series was applied to netdev/net-next.git (main) by Jakub Kicinski <[email protected]>:
Quoted 9 lines · On Thu, 19 Nov 2026 07:15:52 +0000 you wrote:
This is a follow-up for commit
031c403d13e5("tcp: do not lettcp_collapse()drivesk_forward_allocnegative").The core algorithm in
tcp_collapse()is so simple and has not been changed since commit1da177e4c3f4("Linux-2.6.12-rc2"); finding a collapsible skb and repacking it into up-to-SKB_MAX_ORDER() skb.[...]
Here is the summary with links:
- [v3,net-next,1/7] tcp: Refactor the first loop in tcp_collapse().
https://git.kernel.org/netdev/net-next/c/4243888962b8 - [v3,net-next,2/7] tcp: Don't collapse high density skb. https://git.kernel.org/netdev/net-next/c/0a3f65cdf433 - [v3,net-next,3/7] tcp: Stop collapsing if not bloated. https://git.kernel.org/netdev/net-next/c/aff9a5a36670 - [v3,net-next,4/7] tcp: Skip collapsing if collapsed skb is less-dense. https://git.kernel.org/netdev/net-next/c/c4fef895b429 - [v3,net-next,5/7] tcp: Allocate all new skb before collapsing. https://git.kernel.org/netdev/net-next/c/94b6d61f13d2 - [v3,net-next,6/7] tcp: Batch memory accounting in tcp_collapse(). https://git.kernel.org/netdev/net-next/c/05e936e48791 - [v3,net-next,7/7] selftest: packetdrill: Add test for tcp_collapse(). https://git.kernel.org/netdev/net-next/c/7042d186bf6c
You are awesome, thank you!
Signature · 2 lines
Deet-doot-dot, I am a bot. https://korg.docs.kernel.org/patchwork/pwbot.html