🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Thread View: linux.kernel.netdev
6 messages
6 total messages Started by Alireza Asgari via B4 Relay Sun, 15 Nov 2026 22:34
[PATCH RFC nf-next 0/9] netfilter: nfqueue: account queued memory and reserve capacity
#16805
Author: Alireza Asgari via B4 Relay
Date: Sun, 15 Nov 2026 22:34
242 lines
25050 bytes
Hi,

NFQUEUE limits pending packets by count, although packet buffers can have
substantially different memory costs. Large skbs and GSO aggregates can
therefore consume much more memory than the packet-count limit suggests.
Independent queue limits also allow userspace to multiply the available
capacity by creating many queues.

This series implements the approach suggested by Florian Westphal in the
NFQUEUE memory-exhaustion discussion [1]: add a per-queue byte allowance
and reserve queue capacity against a memory cgroup. His message proposed
the overall approach; the ownership, reservation interface, and failure
policies below are implementation choices proposed for discussion in this
RFC.

The byte allowance is derived from the existing maximum queue length:

    (u64)queue_maxlen * (SKB_DATA_ALIGN(sizeof(struct sk_buff)) + 2048)

The 2048-byte contribution represents a nominal complete skb head,
including its shared-info area. The shell contribution follows skb
accounting alignment. The allowance is pooled across the queue, and the
existing packet-count limit remains enforced. Large skbs can exhaust the
byte allowance before the packet limit is reached. Existing drop and
FAIL_OPEN dispositions are preserved. No new userspace configuration
attribute is introduced.

The nominal head size is a policy choice, not a bound on ordinary receive
buffers. For example, mvneta can build a small packet's skb around a whole
page. On a 4 KiB-page system its initial cost is the aligned shell plus
4096 bytes, so it cannot enter an empty length-one queue under this policy.
With FAIL_OPEN disabled it is dropped; with FAIL_OPEN enabled it bypasses
that queue daemon's inspection and continues through reinjection. Later
Netfilter processing can still drop it. An independently configurable byte
limit could accommodate such buffers without increasing packet depth, but
the default for applications that omit it would also need agreement.

Each admitted entry saves its skb's admission-time truesize. That charge
remains through detachment from the pending list, including batch verdicts,
and is released when NFQUEUE reinjection processing begins. Failed
notification delivery rolls back admission and its charge. This ledger
measures saved accounting costs, rather than every allocation associated
with a packet; transient allocations and later payload expansion are
outside that measure.

The local byte limit applies in every network namespace. Outside the
initial network namespace, BIND captures an accounting owner from the
configuring task. The queue initially uses COPY_NONE and reserves no
capacity. Userspace can set its packet limit before enabling COPY_META or
COPY_PACKET; that first activation obtains the complete reservation before
enabling admission. A failed activation leaves the queue's prior limits,
mode, and flags intact. This allows a separate BIND, smaller-limit, and
enable sequence without first paying for the default queue size.

A BIND that includes configuration prepares the new instance privately,
including any activation reservation, and publishes it only on success.
Failed creation releases the private instance without exposing an inactive
queue to packet readers. In particular, a rule that bypasses an absent
queue cannot encounter a temporarily visible COPY_NONE queue while its
bundled creation is obtaining capacity. Standalone BIND still publishes an
inactive queue with its accounting owner captured.

Once activated, the queue retains its reservation policy even if userspace
later selects COPY_NONE. Resizing retains the BIND-time owner even if the
configuring task moves cgroups, subject to normal cgroup reparenting. The
charge makes queues owned within a constrained cgroup compete for its
budget. Reservations consume budget even for empty activated queues; they
do not preallocate packet storage or replace ordinary allocation charges.
Reservations captured with root ownership or disabled kmem accounting are
uncharged. A finite aggregate ceiling requires a constraining memory-cgroup
limit.

Charged capacity growth requires a 64-bit kernel. On 32-bit kernels,
in-range positive growth with a captured accounting owner fails with
-EOPNOTSUPP before charging or publishing a new configuration. Inactive
BIND and limit configuration remain possible; activating an affected queue
or increasing its existing reservation fails. Bundling activation into BIND
can therefore fail as well. The feature does not silently omit the charge.
Initial-network-namespace queues and reservations captured without a
chargeable owner remain supported. This restriction avoids making the
shared 32-bit page counters' arithmetic limits reachable with large virtual
charges; a per-queue maximum would not bound the aggregate hierarchy.

Using ordinary memcg charges means unused capacity contributes to
memory.current, kernel-memory statistics, and peak accounting. It can
affect configured memory.min/memory.low protection, memory.high pressure,
and the budget available to other allocations. Precharging makes capacity
refusal visible during configuration and avoids a new memcg charge
operation at packet admission. Charging retained bytes on admission instead
would avoid paying for unused capacity, but would move charging work and
possible refusal into the packet path. Neither approach reserves physical
memory or guarantees that later allocations succeed.

Increasing capacity obtains the additional reservation before publishing
the new limit. Failure leaves the existing configuration intact. Shrinking
preserves queued packets and retains page-rounded backing for the greater
of the configured allowance and outstanding saved charges. Excess capacity
is refunded as entries drain, with refund work serialized against resizing
and coordinated with queue destruction. Refunds settle the actual memory
counters as well as statistics, including charges inherited by root after
an owner's removal. On supported kernels, later growth under root ownership
remains uncharged and is excluded from those refunds.

The series also saturates the task's deferred memory.high page counter
instead of letting repeated nonblocking charges wrap it to zero. Large
virtual reservations can accumulate that debt before returning to userspace
without allocating corresponding physical pages. Saturation preserves
pending pressure handling; it does not change the owner-selection policy.

A separate MM prerequisite makes the memory.high delay calculation safe
across its scaling and multiplication steps, including consumption of the
deferred page debt. It corrects overflow and premature 32-bit truncation
while preserving the intended fixed-point rounding and previous
non-overflowing final delay results on 64-bit kernels. Large results remain
bounded at the existing maximum delay. This correction applies on both
32-bit and 64-bit kernels; it does not remove the reservation interface's
separate 64-bit restriction.

The arithmetic prerequisite overlaps Zhang Jiao's October submission [2]
and the earlier report from Song Hu [3]. Its description links the
associated MM review. The implementation here also covers the scaled
numerator and debt multiplication, and preserves sub-batch delay results.
The two generic MM fixes and their tests are separated from the reservation
interface for independent review; the arithmetic patch is an alternative
for discussion, not a revision of Zhang's submission.

The series introduces a bulk page-reservation interface in the memory
controller, with a referenced owner, transactional resizing, and module
support. Reservation growth uses GFP_NOWAIT and rejects PF_MEMALLOC growth,
avoiding direct reclaim, memcg OOM invocation, and forced overcharging.
This avoids repeated reclaim while queue configuration is serialized, but
permits refusal despite reclaimable memory. Deferred memory.high handling
remains possible, with an existing ownership limitation: the charge path
records deferred work on the current task, and the later handler selects
the cgroup from that task's memory context. If a queue bound in cgroup A is
enlarged after the task moves to sibling B, A is charged but deferred
handling can target B. A's memory.max remains enforced; handling A's
memory.high excess is not guaranteed by this path. The interface documents
this best-effort behavior rather than providing owner-aware pressure
handling on the stated base.

Shakeel Butt's queued memory.high enforcement series [4] changes this
behavior: remote charges schedule reclaim against the charged hierarchy
through high_work. It does not guarantee throttling of the configuring
task, and a fast charger can outrun that worker. That work is not included
in this nf-next base or attributed to this series. Its interaction with
reservations is assessed separately from the base tests.

I am posting this as RFC particularly for feedback on:

1. Whether packet depth and byte allowance should be independently
   configurable, and what default should apply to existing applications
   that only set NFQA_CFG_QUEUE_MAXLEN. Is the proposed 2 KiB head policy
   acceptable given its full-page-buffer and FAIL_OPEN consequences?

2. Whether configured capacity should consume ordinary memcg usage, or
   whether retained bytes should be charged at admission instead. Are the
   BIND-time owner and initial-network-namespace exception appropriate?

3. Whether the proposed bulk reservation interface is an appropriate MM
   interface for this use, including the explicit restriction of charged
   growth to 64-bit kernels. Is this compatibility tradeoff acceptable for
   the initial interface?

4. Whether non-reclaiming reservation growth is the desired failure policy.

5. Whether the queued MM work's best-effort background reclaim is
   sufficient for saved-owner capacity reservations, or stronger pressure
   semantics are needed. On the stated base, the existing owner mismatch
   described above remains.

The patched kernel passed three KUnit suites and the cgroup-enabled network
selftest in an x86-64 guest with two CPUs online, KASAN, and lockdep.
Coverage includes deferred-high saturation and delay arithmetic, creation
publication ordering, separate and bundled activation, refused activation,
retained accounting after COPY_NONE, actual root-counter refunds,
page-backed skbs, payload replacement, and bounded concurrent resizing,
verdicts, teardown, refunds, and queue reuse. The applicable KUnit cases
also passed on x86-32, with two charged-growth cases skipped as expected.
The delay tests exercise the production helpers; they do not reproduce the
complete reclaim-and-throttle path.

A separate probe requiring owner-aware memory.high handling failed: after
the task moved from the owner to its original/root cgroup, growth still
charged the owner but produced no new owner high events. This reproduces
the limitation described above, without establishing a bypass of
memory.max.

In a separate compatibility checkout with Shakeel's queued changes, that
probe observed an owner high event after migration. The growth operation
still returned promptly, consistent with background reclaim rather than
configuring-task throttling. That checkout also incorporates Pablo Neira
Ayuso's pending NFQUEUE reinjection series, with saved-charge releases
adapted to its terminal paths. Its KUnit and network tests passed. These
results concern the dependency integration, not the stated nf-next base.

Receive-driver/GRO behavior and throughput effects have not been evaluated.
Feedback is particularly requested on the allowance policy and reservation
interface, including the full-page-buffer, architecture-support, and
saved-owner memory.high behavior described above.

AI coding tools assisted with investigation, implementation, test
development, review, and drafting this RFC. I take responsibility for the
submitted changes and their technical justification.

[1] https://lists.openwall.net/netdev/2026/11/06/366
[2] https://lore.kernel.org/20261029073857.974-1-zhangjiao2@cmss.chinamobile.com/
[3] https://lore.kernel.org/20260818012115.65838-1-husong@kylinos.cn/
[4] https://lore.kernel.org/20261030205418.341214-1-shakeel.butt@linux.dev/

---
Alireza Asgari (9):
      memcg: saturate deferred memory.high page debt
      memcg: bound memory.high delay arithmetic
      memcg: add KUnit coverage for memory.high accounting
      memcg: add an owner-bound capacity reservation interface
      memcg: test capacity reservation rollback and refunds
      netfilter: nfqueue: account saved skb bytes per queue
      netfilter: nfqueue: reserve capacity against the bound owner
      netfilter: nfqueue: add KUnit memory accounting coverage
      selftests: netfilter: exercise nfqueue memory accounting

 include/linux/memcontrol.h                         |  35 ++
 include/net/netfilter/nf_queue.h                   |   1 +
 mm/Kconfig                                         |  21 +
 mm/memcontrol.c                                    | 216 +++++++++-
 mm/memcontrol_high_test.c                          | 162 ++++++++
 mm/memcontrol_reservation_test.c                   | 232 +++++++++++
 net/netfilter/Kconfig                              |  10 +
 net/netfilter/nfnetlink_queue.c                    | 281 +++++++++----
 net/netfilter/nfnetlink_queue_test.c               | 338 +++++++++++++++
 tools/testing/selftests/net/netfilter/Makefile     |   1 +
 .../selftests/net/netfilter/nft_queue_memory.py    | 460 +++++++++++++++++++++
 11 files changed, 1677 insertions(+), 80 deletions(-)
---
base-commit: 4810f60b9f0e9111cd0dcbfd2ca7a7c591a57464
change-id: 20261115-b4-nfqueue-memory-accounting-263e081fed39

Best regards,
--  
Alireza Asgari <alireza@asgari.net>
[PATCH RFC nf-next 1/9] memcg: saturate deferred memory.high page debt
#16807
Author: Alireza Asgari via B4 Relay
Date: Sun, 15 Nov 2026 22:34
51 lines
13118 bytes
From: Alireza Asgari <alireza@asgari.net>

Repeated nonblocking charges can accumulate deferred memory.high work
before the charging task returns to userspace. The unsigned-int page
counter can wrap, including to zero, and erase that pending work. Large
virtual capacity reservations can reach this range without allocating
corresponding physical memory, including on 64-bit kernels.

Saturate the addition at UINT_MAX. Ordinary additions retain their value;
very large debt retains the pressure signal instead of wrapping. This does
not change memory.max checks or promise exact debt beyond the saturation
point.

Found during AI-assisted source review of virtual capacity accounting.
The accompanying KUnit patch calls the real GFP_NOWAIT charging path with
an isolated counter fixture and a 65-page charge. It seeds debt near
UINT_MAX to cover exact-boundary, crossing, and already-saturated cases;
it does not allocate the corresponding large amount of physical memory.

The debt case passed on both 64-bit and 32-bit x86 KUnit kernels built
from this series. The test exercises the production charging and debt
update path; it does not reproduce end-to-end throttling.

Fixes: b23afb93d317 ("memcg: punt high overage reclaim to return-to-userland path")
Signed-off-by: Alireza Asgari <alireza@asgari.net>
---
 mm/memcontrol.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index 84f4a8fd4d16..1980fb7431a8 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -2894,8 +2894,12 @@ static int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
 			 * Target some best-effort fairness between the tasks,
 			 * and distribute reclaim work and delay penalties
 			 * based on how much each task is actually allocating.
+			 * Saturate so repeated nonblocking charges cannot erase
+			 * pending work by wrapping the counter back to zero.
 			 */
-			current->memcg_nr_pages_over_high += batch;
+			current->memcg_nr_pages_over_high += min(
+				batch,
+				UINT_MAX - current->memcg_nr_pages_over_high);
 			set_notify_resume(current);
 			break;
 		}

-- 
2.34.1
[PATCH RFC nf-next 3/9] memcg: add KUnit coverage for memory.high accounting
#16804
Author: Alireza Asgari via B4 Relay
Date: Sun, 15 Nov 2026 22:34
227 lines
18263 bytes
From: Alireza Asgari <alireza@asgari.net>

Exercise deferred page-debt saturation and the bounded delay arithmetic
without requiring very large memory allocations.

The debt test calls the real charge path using an isolated page-counter
fixture, small GFP_NOWAIT charges, and seeded debt values. It restores
task state and fixture counters before checking results. The arithmetic
cases call the internal helpers directly, including one-page debt and
large numerators whose scaled product would overflow u64.

Keep this coverage independent of the capacity-reservation interface so
the generic MM fixes can be reviewed and tested separately. The tests
require built-in KUnit and memcg support on either word size.

Signed-off-by: Alireza Asgari <alireza@asgari.net>
---
 mm/Kconfig                |  10 +++
 mm/memcontrol.c           |   4 ++
 mm/memcontrol_high_test.c | 162 ++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 176 insertions(+)

diff --git a/mm/Kconfig b/mm/Kconfig
index afff1b25b543..dd763d3d0e36 100644
--- a/mm/Kconfig
+++ b/mm/Kconfig
@@ -1531,6 +1531,16 @@ config PTDUMP
 	bool
 
 
+config MEMCG_HIGH_KUNIT_TEST
+	bool "Memory cgroup high limit tests" if !KUNIT_ALL_TESTS
+	depends on MEMCG && KUNIT=y
+	default KUNIT_ALL_TESTS
+	help
+	  Test deferred memory.high debt saturation through the real charging
+	  path with isolated counters and small charges. Delay tests cover
+	  fixed-point rounding and arithmetic bounds on 32-bit and 64-bit
+	  kernels. Say N unless developing memory cgroup high limit handling.
+
 source "mm/damon/Kconfig"
 
 endmenu
diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index 665ce8dfb9ec..446b60ca6aef 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -6532,3 +6532,7 @@ void mem_cgroup_show_protected_memory(struct mem_cgroup *memcg)
 		K(atomic_long_read(&memcg->memory.children_min_usage)),
 		K(atomic_long_read(&memcg->memory.children_low_usage)));
 }
+
+#if IS_ENABLED(CONFIG_MEMCG_HIGH_KUNIT_TEST)
+#include "memcontrol_high_test.c"
+#endif
diff --git a/mm/memcontrol_high_test.c b/mm/memcontrol_high_test.c
new file mode 100644
index 000000000000..bf792d398021
--- /dev/null
+++ b/mm/memcontrol_high_test.c
@@ -0,0 +1,162 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include <kunit/test.h>
+
+static void memcg_high_test_restore_counter(struct page_counter *counter,
+					    unsigned long before)
+{
+	unsigned long after = page_counter_read(counter);
+
+	if (after > before)
+		page_counter_uncharge(counter, after - before);
+	else if (after < before)
+		page_counter_charge(counter, before - after);
+}
+
+static void memcg_high_test_debt(struct kunit *test)
+{
+	const unsigned int nr_pages = MEMCG_CHARGE_BATCH + 1;
+	const struct {
+		unsigned int before;
+		unsigned int expected;
+	} cases[] = {
+		{ 0, nr_pages },
+		{ UINT_MAX - nr_pages, UINT_MAX },
+		{ UINT_MAX - nr_pages + 1, UINT_MAX },
+		{ UINT_MAX, UINT_MAX },
+	};
+	struct mem_cgroup *memcg;
+	unsigned int i;
+
+	memcg = kunit_kzalloc(test, sizeof(*memcg), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, memcg);
+	page_counter_init(&memcg->memory, NULL, false);
+	page_counter_init(&memcg->memsw, NULL, false);
+	page_counter_init(&memcg->swap, NULL, false);
+	page_counter_set_high(&memcg->memory, 0);
+	page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
+
+	for (i = 0; i < ARRAY_SIZE(cases); i++) {
+		unsigned int saved = current->memcg_nr_pages_over_high;
+		bool notify = test_thread_flag(TIF_NOTIFY_RESUME);
+		unsigned int debt;
+		bool notified;
+		int ret;
+
+		/*
+		 * Exceed the stock batch to use the real counter charge path
+		 * without leaving a reference to this isolated fixture in stock.
+		 * GFP_NOWAIT defers reclaim until return to userspace.
+		 */
+		current->memcg_nr_pages_over_high = cases[i].before;
+		ret = try_charge_memcg(memcg, GFP_NOWAIT, nr_pages);
+		debt = current->memcg_nr_pages_over_high;
+		notified = test_thread_flag(TIF_NOTIFY_RESUME);
+
+		/* Restore the test task before any assertion can abort the case. */
+		current->memcg_nr_pages_over_high = saved;
+		if (!notify)
+			clear_thread_flag(TIF_NOTIFY_RESUME);
+		memcg_high_test_restore_counter(&memcg->memory, 0);
+		if (do_memsw_account())
+			memcg_high_test_restore_counter(&memcg->memsw, 0);
+
+		KUNIT_EXPECT_EQ_MSG(test, ret, 0, "case %u", i);
+		KUNIT_EXPECT_EQ_MSG(test, debt, cases[i].expected, "case %u",
+				    i);
+		KUNIT_EXPECT_TRUE_MSG(test, notified, "case %u", i);
+	}
+}
+
+static void memcg_high_test_overage(struct kunit *test)
+{
+	const unsigned long large_high = 1UL << (BITS_PER_LONG - 3);
+	const struct {
+		unsigned long usage;
+		unsigned long high;
+		u64 expected;
+	} cases[] = {
+		{ 0, 0, 0 },
+		{ 1, 0, 0 },
+		{ 2, 0, 1ULL << 20 },
+		{ 99, 100, 0 },
+		{ 100, 100, 0 },
+		{ 110, 100, 104857 },
+		{ 150, 100, 524288 },
+		{ 299, 100, 2086666 },
+		{ 300, 100, 2ULL << 20 },
+		{ 301, 100, 2ULL << 20 },
+		{ ULONG_MAX, 1, 2ULL << 20 },
+		{ ULONG_MAX, ULONG_MAX - 1, 0 },
+		/* A modest ratio whose scaled numerator exceeds u64 on 64-bit. */
+		{ large_high + large_high / 16, large_high, 1ULL << 16 },
+	};
+	unsigned int i;
+
+	for (i = 0; i < ARRAY_SIZE(cases); i++)
+		KUNIT_EXPECT_EQ_MSG(
+			test, calculate_overage(cases[i].usage, cases[i].high),
+			cases[i].expected, "case %u", i);
+}
+
+static void memcg_high_test_delay(struct kunit *test)
+{
+	const unsigned long cap = MEMCG_MAX_HIGH_DELAY_JIFFIES;
+	const struct {
+		unsigned int pages;
+		u64 overage;
+		unsigned long expected;
+	} cases[] = {
+		{ 0, 0, 0 },
+		{ 0, U64_MAX, 0 },
+		{ UINT_MAX, 0, 0 },
+		{ 1, 1ULL << 16, (HZ / 4) / 64 },
+		{ 63, 1ULL << 16, (HZ / 4) * 63 / 64 },
+		{ 64, 1ULL << 16, HZ / 4 },
+		{ 65, 1ULL << 16, (HZ / 4) * 65 / 64 },
+		{ UINT_MAX, 1ULL << 16, cap },
+		{ 64, 1ULL << 17, HZ },
+		/* Apply debt scaling before the cap, including sub-batch debt. */
+		{ 1, 1ULL << 18, HZ / 16 },
+		{ 1, 1ULL << 20, HZ },
+		{ 2, 1ULL << 20, cap },
+		{ 1, 2ULL << 20, cap },
+		{ 64, 1ULL << 32, cap },
+		{ UINT_MAX, 1ULL << 32, cap },
+		{ 1, U64_MAX, cap },
+		{ UINT_MAX, U64_MAX, cap },
+	};
+	unsigned long delay;
+	unsigned int i;
+
+	for (i = 0; i < ARRAY_SIZE(cases); i++)
+		KUNIT_EXPECT_EQ_MSG(test,
+				    calculate_high_delay(cases[i].pages,
+							 cases[i].overage),
+				    cases[i].expected, "case %u", i);
+
+	/* 32 GiB over an 8 MiB high limit, expressed in 4 KiB pages. */
+	KUNIT_EXPECT_EQ(
+		test,
+		calculate_high_delay(64, calculate_overage((1UL << 23) + 2048,
+							   2048)),
+		cap);
+	/* Both memory and swap contributions are bounded before addition. */
+	delay = calculate_high_delay(UINT_MAX, U64_MAX);
+	delay += calculate_high_delay(UINT_MAX, U64_MAX);
+	KUNIT_EXPECT_EQ(test, delay, 2 * cap);
+}
+
+static struct kunit_case memcg_high_test_cases[] = {
+	KUNIT_CASE(memcg_high_test_debt),
+	KUNIT_CASE(memcg_high_test_overage),
+	KUNIT_CASE(memcg_high_test_delay),
+	{}
+};
+
+static struct kunit_suite memcg_high_test_suite = {
+	.name = "memcg_high",
+	.test_cases = memcg_high_test_cases,
+};
+
+kunit_test_suite(memcg_high_test_suite);

-- 
2.34.1
[PATCH RFC nf-next 5/9] memcg: test capacity reservation rollback and refunds
#16808
Author: Alireza Asgari via B4 Relay
Date: Sun, 15 Nov 2026 22:34
330 lines
23001 bytes
From: Alireza Asgari <alireza@asgari.net>

Add reservation-specific KUnit coverage for partial-growth rollback,
reparented-root growth, range and architecture checks, and root refunds.

Transaction cases inject charge results through KUnit static stubs.
The root-refund case uses temporary real root page-counter charges while
other CPUs are stopped, and restores the counters even if the expected
refund is absent. It models charges inherited after reparenting; the
network selftest separately exercises real cgroup removal.

Keep these tests separate from the generic memory.high suite and make
all redirection conditional on the reservation KUnit option.

Signed-off-by: Alireza Asgari <alireza@asgari.net>
---
 mm/Kconfig                       |  11 ++
 mm/memcontrol.c                  |  16 +++
 mm/memcontrol_reservation_test.c | 232 +++++++++++++++++++++++++++++++++++++++
 3 files changed, 259 insertions(+)

diff --git a/mm/Kconfig b/mm/Kconfig
index dd763d3d0e36..39db388f193f 100644
--- a/mm/Kconfig
+++ b/mm/Kconfig
@@ -1541,6 +1541,17 @@ config MEMCG_HIGH_KUNIT_TEST
 	  fixed-point rounding and arithmetic bounds on 32-bit and 64-bit
 	  kernels. Say N unless developing memory cgroup high limit handling.
 
+config MEMCG_RESERVATION_KUNIT_TEST
+	bool "Memory cgroup capacity reservation tests" if !KUNIT_ALL_TESTS
+	depends on MEMCG && KUNIT=y
+	default KUNIT_ALL_TESTS
+	help
+	  Test capacity reservation transactions, including partial growth
+	  failure, architecture support, and uncharged growth after reparenting
+	  to root. Transaction tests inject charge results. The root refund test
+	  checks real counters with a temporary eight-page charge while other
+	  CPUs are stopped. Say N unless developing this interface.
+
 source "mm/damon/Kconfig"
 
 endmenu
diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index 0227d9b411f5..d49ce5a92c1f 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -73,6 +73,10 @@
 
 #include <linux/uaccess.h>
 
+#if IS_ENABLED(CONFIG_MEMCG_RESERVATION_KUNIT_TEST)
+#include <kunit/static_stub.h>
+#endif
+
 #define CREATE_TRACE_POINTS
 #include <trace/events/memcg.h>
 #undef CREATE_TRACE_POINTS
@@ -3264,6 +3268,10 @@ static int mem_cgroup_reservation_charge(struct obj_cgroup *objcg,
 	struct mem_cgroup *memcg;
 	int ret = 0;
 
+#if IS_ENABLED(CONFIG_MEMCG_RESERVATION_KUNIT_TEST)
+	KUNIT_STATIC_STUB_REDIRECT(mem_cgroup_reservation_charge, objcg, pages,
+				   charged);
+#endif
 	memcg = get_mem_cgroup_from_objcg(objcg);
 	*charged = false;
 	/* Reparenting to root removes the limit, not previously held charges. */
@@ -3291,6 +3299,10 @@ static void mem_cgroup_reservation_uncharge_batch(struct mem_cgroup *memcg,
 
 static void mem_cgroup_reservation_uncharge(struct obj_cgroup *objcg, u64 pages)
 {
+#if IS_ENABLED(CONFIG_MEMCG_RESERVATION_KUNIT_TEST)
+	KUNIT_STATIC_STUB_REDIRECT(mem_cgroup_reservation_uncharge, objcg,
+				   pages);
+#endif
 	while (pages) {
 		unsigned int batch = min_t(u64, pages, MEMCG_RESERVATION_BATCH);
 		struct mem_cgroup *memcg;
@@ -6699,3 +6711,7 @@ void mem_cgroup_show_protected_memory(struct mem_cgroup *memcg)
 #if IS_ENABLED(CONFIG_MEMCG_HIGH_KUNIT_TEST)
 #include "memcontrol_high_test.c"
 #endif
+
+#if IS_ENABLED(CONFIG_MEMCG_RESERVATION_KUNIT_TEST)
+#include "memcontrol_reservation_test.c"
+#endif
diff --git a/mm/memcontrol_reservation_test.c b/mm/memcontrol_reservation_test.c
new file mode 100644
index 000000000000..5ce4f05431b3
--- /dev/null
+++ b/mm/memcontrol_reservation_test.c
@@ -0,0 +1,232 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include <kunit/test.h>
+#include <linux/stop_machine.h>
+
+struct memcg_reservation_test {
+	struct obj_cgroup owner;
+	struct mem_cgroup_reservation res;
+	u64 refunds;
+	unsigned int calls;
+	unsigned int fail_call;
+	bool uncharged;
+};
+
+static int memcg_reservation_test_charge(struct obj_cgroup *objcg,
+					 unsigned int pages, bool *charged)
+{
+	struct memcg_reservation_test *ctx = kunit_get_current_test()->priv;
+
+	*charged = !ctx->uncharged;
+	if (++ctx->calls == ctx->fail_call)
+		return -ENOMEM;
+	return 0;
+}
+
+static void memcg_reservation_test_uncharge(struct obj_cgroup *objcg, u64 pages)
+{
+	struct memcg_reservation_test *ctx = kunit_get_current_test()->priv;
+
+	ctx->refunds += pages;
+}
+
+static int memcg_reservation_test_init(struct kunit *test)
+{
+	struct memcg_reservation_test *ctx;
+
+	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	if (!ctx)
+		return -ENOMEM;
+	/* Transaction cases stub accounting; the root refund case calls the batch. */
+	ctx->owner.is_root = true;
+	ctx->res.objcg = &ctx->owner;
+	test->priv = ctx;
+	kunit_activate_static_stub(test, mem_cgroup_reservation_charge,
+				   memcg_reservation_test_charge);
+	kunit_activate_static_stub(test, mem_cgroup_reservation_uncharge,
+				   memcg_reservation_test_uncharge);
+	return 0;
+}
+
+static void memcg_reservation_test_rollback(struct kunit *test)
+{
+	struct memcg_reservation_test *ctx = test->priv;
+	u64 original = 7;
+
+	if (!IS_ENABLED(CONFIG_64BIT)) {
+		kunit_skip(test,
+			   "Charged reservations require 64-bit counters");
+		return;
+	}
+	KUNIT_ASSERT_EQ(test,
+			mem_cgroup_reservation_resize(&ctx->res, original), 0);
+	ctx->calls = 0;
+	ctx->fail_call = 2;
+	KUNIT_EXPECT_EQ(test,
+			mem_cgroup_reservation_resize(
+				&ctx->res,
+				original + MEMCG_RESERVATION_BATCH + 1),
+			-ENOMEM);
+	KUNIT_EXPECT_EQ(test, ctx->res.pages, original);
+	KUNIT_EXPECT_EQ(test, ctx->res.charged_pages, original);
+	KUNIT_EXPECT_EQ(test, ctx->refunds, (u64)MEMCG_RESERVATION_BATCH);
+	KUNIT_EXPECT_EQ(test, ctx->calls, 2U);
+	mem_cgroup_reservation_destroy(&ctx->res);
+	KUNIT_EXPECT_EQ(test, ctx->refunds, MEMCG_RESERVATION_BATCH + original);
+	KUNIT_EXPECT_PTR_EQ(test, ctx->res.objcg, NULL);
+}
+
+static void memcg_reservation_test_root_growth(struct kunit *test)
+{
+	struct memcg_reservation_test *ctx = test->priv;
+
+	if (!IS_ENABLED(CONFIG_64BIT)) {
+		kunit_skip(test,
+			   "Charged reservations require 64-bit counters");
+		return;
+	}
+	KUNIT_ASSERT_EQ(test, mem_cgroup_reservation_resize(&ctx->res, 8), 0);
+	/* Simulate the charge helper observing reparenting to root. */
+	ctx->uncharged = true;
+	KUNIT_ASSERT_EQ(test, mem_cgroup_reservation_resize(&ctx->res, 16), 0);
+	KUNIT_EXPECT_EQ(test, ctx->res.charged_pages, 8ULL);
+	KUNIT_ASSERT_EQ(test, mem_cgroup_reservation_resize(&ctx->res, 10), 0);
+	KUNIT_EXPECT_EQ(test, ctx->refunds, 0ULL);
+	KUNIT_ASSERT_EQ(test, mem_cgroup_reservation_resize(&ctx->res, 3), 0);
+	KUNIT_EXPECT_EQ(test, ctx->res.charged_pages, 3ULL);
+	KUNIT_EXPECT_EQ(test, ctx->refunds, 5ULL);
+	mem_cgroup_reservation_destroy(&ctx->res);
+	KUNIT_EXPECT_EQ(test, ctx->refunds, 8ULL);
+	KUNIT_EXPECT_EQ(test, ctx->res.pages, 0ULL);
+	KUNIT_EXPECT_EQ(test, ctx->res.charged_pages, 0ULL);
+}
+
+static void memcg_reservation_test_range(struct kunit *test)
+{
+	struct memcg_reservation_test *ctx = test->priv;
+
+	KUNIT_EXPECT_EQ(test,
+			mem_cgroup_reservation_resize(
+				&ctx->res, (u64)PAGE_COUNTER_MAX + 1),
+			-E2BIG);
+	KUNIT_EXPECT_EQ(test, ctx->calls, 0U);
+	KUNIT_EXPECT_EQ(test, ctx->res.pages, 0ULL);
+	mem_cgroup_reservation_destroy(&ctx->res);
+	/* Disabled/root ownership still records the logical reservation. */
+	KUNIT_EXPECT_EQ(test, mem_cgroup_reservation_resize(&ctx->res, 9), 0);
+	KUNIT_EXPECT_EQ(test, ctx->res.pages, 9ULL);
+	KUNIT_EXPECT_EQ(test, ctx->res.charged_pages, 0ULL);
+	mem_cgroup_reservation_destroy(&ctx->res);
+}
+
+static void memcg_reservation_test_arch_support(struct kunit *test)
+{
+	struct memcg_reservation_test *ctx = test->priv;
+	bool supported = IS_ENABLED(CONFIG_64BIT);
+
+	KUNIT_ASSERT_EQ(test, mem_cgroup_reservation_resize(&ctx->res, 0), 0);
+	KUNIT_EXPECT_EQ(test, ctx->calls, 0U);
+	KUNIT_EXPECT_EQ(test, mem_cgroup_reservation_resize(&ctx->res, 9),
+			supported ? 0 : -EOPNOTSUPP);
+	KUNIT_EXPECT_EQ(test, ctx->calls, supported ? 1U : 0U);
+	KUNIT_EXPECT_EQ(test, ctx->res.pages, supported ? 9ULL : 0ULL);
+	KUNIT_EXPECT_EQ(test, ctx->res.charged_pages, supported ? 9ULL : 0ULL);
+	KUNIT_EXPECT_EQ(test, ctx->refunds, 0ULL);
+	mem_cgroup_reservation_destroy(&ctx->res);
+	KUNIT_EXPECT_EQ(test, ctx->refunds, supported ? 9ULL : 0ULL);
+	KUNIT_EXPECT_PTR_EQ(test, ctx->res.objcg, NULL);
+
+	/* An uncharged reservation remains usable on either architecture. */
+	KUNIT_ASSERT_EQ(test, mem_cgroup_reservation_resize(&ctx->res, 9), 0);
+	KUNIT_EXPECT_EQ(test, ctx->res.pages, 9ULL);
+	KUNIT_EXPECT_EQ(test, ctx->res.charged_pages, 0ULL);
+	KUNIT_EXPECT_EQ(test, ctx->calls, supported ? 1U : 0U);
+	mem_cgroup_reservation_destroy(&ctx->res);
+	KUNIT_EXPECT_EQ(test, ctx->refunds, supported ? 9ULL : 0ULL);
+}
+
+struct memcg_reservation_root_refund {
+	unsigned long memory_before, memory_shrunk, memory_after;
+	unsigned long memsw_before, memsw_shrunk, memsw_after;
+	bool memsw;
+};
+
+static void memcg_reservation_test_restore_counter(struct page_counter *counter,
+						   unsigned long before)
+{
+	unsigned long after = page_counter_read(counter);
+
+	if (after > before)
+		page_counter_uncharge(counter, after - before);
+	else if (after < before)
+		page_counter_charge(counter, before - after);
+}
+
+static int memcg_reservation_test_root_refund_stopped(void *data)
+{
+	struct memcg_reservation_root_refund *result = data;
+	struct mem_cgroup *memcg = root_mem_cgroup;
+
+	/* Model charged capacity inherited from a removed child. */
+	result->memory_before = page_counter_read(&memcg->memory);
+	result->memsw_before = page_counter_read(&memcg->memsw);
+	page_counter_charge(&memcg->memory, 8);
+	if (result->memsw)
+		page_counter_charge(&memcg->memsw, 8);
+	account_kmem_nmi_safe(memcg, 8);
+	memcg1_account_kmem(memcg, 8);
+
+	mem_cgroup_reservation_uncharge_batch(memcg, 3);
+	result->memory_shrunk = page_counter_read(&memcg->memory);
+	result->memsw_shrunk = page_counter_read(&memcg->memsw);
+	mem_cgroup_reservation_uncharge_batch(memcg, 5);
+	result->memory_after = page_counter_read(&memcg->memory);
+	result->memsw_after = page_counter_read(&memcg->memsw);
+
+	/* Leave no counter imbalance behind if the refund regression returns. */
+	memcg_reservation_test_restore_counter(&memcg->memory,
+					       result->memory_before);
+	if (result->memsw)
+		memcg_reservation_test_restore_counter(&memcg->memsw,
+						       result->memsw_before);
+	return 0;
+}
+
+static void memcg_reservation_test_root_refund(struct kunit *test)
+{
+	struct memcg_reservation_root_refund result = {
+		.memsw = do_memsw_account(),
+	};
+
+	if (mem_cgroup_disabled() || mem_cgroup_kmem_disabled()) {
+		kunit_skip(test, "Memory cgroup accounting is disabled");
+		return;
+	}
+	/* Exclude background charges while checking the actual root counters. */
+	KUNIT_ASSERT_EQ(test,
+			stop_machine(memcg_reservation_test_root_refund_stopped,
+				     &result, NULL),
+			0);
+	KUNIT_EXPECT_EQ(test, result.memory_shrunk, result.memory_before + 5);
+	KUNIT_EXPECT_EQ(test, result.memory_after, result.memory_before);
+	KUNIT_EXPECT_EQ(test, result.memsw_shrunk,
+			result.memsw_before + (result.memsw ? 5 : 0));
+	KUNIT_EXPECT_EQ(test, result.memsw_after, result.memsw_before);
+}
+
+static struct kunit_case memcg_reservation_test_cases[] = {
+	KUNIT_CASE(memcg_reservation_test_rollback),
+	KUNIT_CASE(memcg_reservation_test_root_growth),
+	KUNIT_CASE(memcg_reservation_test_range),
+	KUNIT_CASE(memcg_reservation_test_arch_support),
+	KUNIT_CASE(memcg_reservation_test_root_refund),
+	{}
+};
+
+static struct kunit_suite memcg_reservation_test_suite = {
+	.name = "memcg_reservation",
+	.init = memcg_reservation_test_init,
+	.test_cases = memcg_reservation_test_cases,
+};
+
+kunit_test_suite(memcg_reservation_test_suite);

-- 
2.34.1
[PATCH RFC nf-next 6/9] netfilter: nfqueue: account saved skb bytes per queue
#16806
Author: Alireza Asgari via B4 Relay
Date: Sun, 15 Nov 2026 22:34
230 lines
19516 bytes
From: Alireza Asgari <alireza@asgari.net>

The packet-count limit does not bound how much skb memory a queue can
retain: packets with different truesize values consume the same one
entry. Add a local byte allowance alongside the existing packet limit.

Derive the allowance from queue_maxlen times an aligned skb shell plus
a nominal 2048-byte complete head. This is a proposed policy, not a
promise that every packet fitting a nominal payload size is admitted.
Page-backed receive heads can exceed the allowance of a small queue.

Record admission-time skb truesize only after insertion succeeds. Keep
that saved cost while verdict handlers detach entries, and subtract it
before reinjection, including early consume paths. Undo it if the
userspace notification fails. Later payload replacement does not change
the saved cost. Segmented packets account each inserted segment.

Use subtraction-based admission checks that remain safe after a live
limit reduction. Retain existing entries when shrinking and refuse new
ones until both limits permit admission. Byte refusal follows the
existing drop or FAIL_OPEN policy.

This implements the local accounting part of Florian Westphal's
suggestion; shared owner accounting follows in the next patch.

Link: https://lists.openwall.net/netdev/2026/11/06/366
Signed-off-by: Alireza Asgari <alireza@asgari.net>
---
 include/net/netfilter/nf_queue.h |  1 +
 net/netfilter/nfnetlink_queue.c  | 59 +++++++++++++++++++++++++++++++++++-----
 2 files changed, 53 insertions(+), 7 deletions(-)

diff --git a/include/net/netfilter/nf_queue.h b/include/net/netfilter/nf_queue.h
index 4a8cefd8398d..5644a1ad32d5 100644
--- a/include/net/netfilter/nf_queue.h
+++ b/include/net/netfilter/nf_queue.h
@@ -16,6 +16,7 @@ struct nf_queue_entry {
 	struct sk_buff		*skb;
 	struct net_device	*skb_dev;
 	unsigned int		id;
+	unsigned int truesize; /* saved NFQUEUE charge, zero if uncharged */
 	unsigned int		hook_index;	/* index in hook_entries->hook[] */
 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
 	struct net_device	*bridge_dev;
diff --git a/net/netfilter/nfnetlink_queue.c b/net/netfilter/nfnetlink_queue.c
index 862d2a762106..d1e6e02e144b 100644
--- a/net/netfilter/nfnetlink_queue.c
+++ b/net/netfilter/nfnetlink_queue.c
@@ -92,6 +92,8 @@ struct nfqnl_instance {
 	unsigned int	queue_total;
 	unsigned int	id_sequence;		/* 'sequence' of pkt ids */
 	struct list_head queue_list;		/* packets in queue */
+	u64 mem_limit;
+	u64 mem_used;
 };
 
 typedef int (*nfqnl_cmpfn)(struct nf_queue_entry *, unsigned long);
@@ -138,6 +140,28 @@ instance_lookup(struct nfnl_queue_net *q, u_int16_t queue_num)
 	return NULL;
 }
 
+static u64 nfqnl_mem_limit(unsigned int maxlen)
+{
+	/* Match the skb shell alignment included in skb->truesize. */
+	return (u64)maxlen * (SKB_DATA_ALIGN(sizeof(struct sk_buff)) + 2048);
+}
+
+static bool nfqnl_mem_full(const struct nfqnl_instance *queue,
+			   unsigned int truesize)
+{
+	return queue->mem_used > queue->mem_limit ||
+	       truesize > queue->mem_limit - queue->mem_used;
+}
+
+/* All release paths use the saved admission cost, including notification undo. */
+static void nfqnl_mem_uncharge(struct nfqnl_instance *queue,
+			       struct nf_queue_entry *entry)
+{
+	lockdep_assert_held(&queue->lock);
+	queue->mem_used -= entry->truesize;
+	entry->truesize = 0;
+}
+
 static struct nfqnl_instance *
 instance_create(struct nfnl_queue_net *q, u_int16_t queue_num, u32 portid)
 {
@@ -152,6 +176,7 @@ instance_create(struct nfnl_queue_net *q, u_int16_t queue_num, u32 portid)
 	inst->queue_num = queue_num;
 	inst->peer_portid = portid;
 	inst->queue_maxlen = NFQNL_QMAX_DEFAULT;
+	inst->mem_limit = nfqnl_mem_limit(NFQNL_QMAX_DEFAULT);
 	inst->copy_range = NFQNL_MAX_COPY_RANGE;
 	inst->copy_mode = NFQNL_COPY_NONE;
 	spin_lock_init(&inst->lock);
@@ -199,6 +224,7 @@ static void instance_destroy_work(struct work_struct *work)
 	rcu_read_lock();
 	nfqnl_flush(inst, NULL, 0);
 	rcu_read_unlock();
+	WARN_ON_ONCE(inst->mem_used);
 
 	rhashtable_destroy(&inst->nfqnl_packet_map);
 
@@ -235,6 +261,8 @@ __enqueue_entry(struct nfqnl_instance *queue, struct nf_queue_entry *entry)
 
 	list_add_tail(&entry->list, &queue->queue_list);
 	queue->queue_total++;
+	entry->truesize = entry->skb->truesize;
+	queue->mem_used += entry->truesize;
 
 	return 0;
 }
@@ -493,7 +521,7 @@ static bool nf_bridge_ports_valid(const struct nf_queue_entry *entry)
 	return true;
 }
 
-static void nfqnl_reinject(struct nf_queue_entry *entry, unsigned int verdict)
+static void __nfqnl_reinject(struct nf_queue_entry *entry, unsigned int verdict)
 {
 	const struct nf_ct_hook *ct_hook;
 
@@ -544,6 +572,15 @@ static void nfqnl_reinject(struct nf_queue_entry *entry, unsigned int verdict)
 	nf_reinject(entry, verdict);
 }
 
+static void nfqnl_reinject(struct nfqnl_instance *queue,
+			   struct nf_queue_entry *entry, unsigned int verdict)
+{
+	spin_lock_bh(&queue->lock);
+	nfqnl_mem_uncharge(queue, entry);
+	spin_unlock_bh(&queue->lock);
+	__nfqnl_reinject(entry, verdict);
+}
+
 static void
 nfqnl_flush(struct nfqnl_instance *queue, nfqnl_cmpfn cmpfn, unsigned long data)
 {
@@ -553,7 +590,8 @@ nfqnl_flush(struct nfqnl_instance *queue, nfqnl_cmpfn cmpfn, unsigned long data)
 	list_for_each_entry_safe(entry, next, &queue->queue_list, list) {
 		if (!cmpfn || cmpfn(entry, data)) {
 			__dequeue_entry(queue, entry);
-			nfqnl_reinject(entry, NF_DROP);
+			nfqnl_mem_uncharge(queue, entry);
+			__nfqnl_reinject(entry, NF_DROP);
 		}
 	}
 	spin_unlock_bh(&queue->lock);
@@ -1004,6 +1042,7 @@ __nfqnl_enqueue_packet(struct net *net, struct nfqnl_instance *queue,
 	__be32 *packet_id_ptr;
 	int failopen = 0;
 
+	entry->truesize = 0;
 	nskb = nfqnl_build_packet_message(net, queue, entry, &packet_id_ptr);
 	if (nskb == NULL) {
 		err = -ENOMEM;
@@ -1011,7 +1050,8 @@ __nfqnl_enqueue_packet(struct net *net, struct nfqnl_instance *queue,
 	}
 	spin_lock_bh(&queue->lock);
 
-	if (queue->queue_total >= queue->queue_maxlen)
+	if (queue->queue_total >= queue->queue_maxlen ||
+	    nfqnl_mem_full(queue, entry->skb->truesize))
 		goto err_out_queue_drop;
 
 	entry->id = ++queue->id_sequence;
@@ -1027,6 +1067,7 @@ __nfqnl_enqueue_packet(struct net *net, struct nfqnl_instance *queue,
 	if (err < 0) {
 		/* Unicast failed - remove entry we just inserted */
 		__dequeue_entry(queue, entry);
+		nfqnl_mem_uncharge(queue, entry);
 
 		if (queue->flags & NFQA_CFG_F_FAIL_OPEN) {
 			failopen = 1;
@@ -1050,6 +1091,9 @@ __nfqnl_enqueue_packet(struct net *net, struct nfqnl_instance *queue,
 		if (queue->queue_total >= queue->queue_maxlen)
 			net_warn_ratelimited("nf_queue: full at %d entries, dropping packets(s)\n",
 					     queue->queue_total);
+		else if (nfqnl_mem_full(queue, entry->skb->truesize))
+			net_warn_ratelimited(
+				"nf_queue: byte limit reached, dropping packet\n");
 		else
 			net_warn_ratelimited("nf_queue: hash insert failed: %d\n", err);
 	}
@@ -1057,7 +1101,7 @@ __nfqnl_enqueue_packet(struct net *net, struct nfqnl_instance *queue,
 err_out_unlock:
 	spin_unlock_bh(&queue->lock);
 	if (failopen)
-		nfqnl_reinject(entry, NF_ACCEPT);
+		nfqnl_reinject(queue, entry, NF_ACCEPT);
 err_out:
 	return err;
 }
@@ -1773,7 +1817,7 @@ static int nfqnl_recv_verdict_batch(struct sk_buff *skb,
 		if (nfqa[NFQA_PRIORITY])
 			entry->skb->priority = ntohl(nla_get_be32(nfqa[NFQA_PRIORITY]));
 
-		nfqnl_reinject(entry, verdict);
+		nfqnl_reinject(queue, entry, verdict);
 	}
 	return 0;
 }
@@ -1885,7 +1929,7 @@ static int nfqnl_recv_verdict(struct sk_buff *skb, const struct nfnl_info *info,
 	if (entry->state.pf == PF_BRIDGE) {
 		err = nfqa_parse_bridge(entry, nfqa);
 		if (err < 0) {
-			nfqnl_reinject(entry, NF_DROP);
+			nfqnl_reinject(queue, entry, NF_DROP);
 			return err;
 		}
 	}
@@ -1907,7 +1951,7 @@ static int nfqnl_recv_verdict(struct sk_buff *skb, const struct nfnl_info *info,
 	if (nfqa[NFQA_PRIORITY])
 		entry->skb->priority = ntohl(nla_get_be32(nfqa[NFQA_PRIORITY]));
 
-	nfqnl_reinject(entry, verdict);
+	nfqnl_reinject(queue, entry, verdict);
 	return 0;
 }
 
@@ -2037,6 +2081,7 @@ static int nfqnl_recv_config(struct sk_buff *skb, const struct nfnl_info *info,
 
 		spin_lock_bh(&queue->lock);
 		queue->queue_maxlen = ntohl(*queue_maxlen);
+		queue->mem_limit = nfqnl_mem_limit(queue->queue_maxlen);
 		spin_unlock_bh(&queue->lock);
 	}
 

-- 
2.34.1
Re: [PATCH RFC nf-next 6/9] netfilter: nfqueue: account saved skb bytes per queue
#17487
Author: Florian Westphal
Date: Mon, 16 Nov 2026 22:46
42 lines
9173 bytes
Alireza Asgari via B4 Relay <devnull+alireza.asgari.net@kernel.org> wrote:
> --- a/net/netfilter/nfnetlink_queue.c
> +++ b/net/netfilter/nfnetlink_queue.c
> @@ -92,6 +92,8 @@ struct nfqnl_instance {
>  	unsigned int	queue_total;
>  	unsigned int	id_sequence;		/* 'sequence' of pkt ids */
>  	struct list_head queue_list;		/* packets in queue */
> +	u64 mem_limit;
> +	u64 mem_used;

I think u32 is fine for those.  Or do you see a use case for 2**32 mbyte
worth of queued packets?

> +/* All release paths use the saved admission cost, including notification undo. */
> +static void nfqnl_mem_uncharge(struct nfqnl_instance *queue,
> +			       struct nf_queue_entry *entry)
> +{
> +	lockdep_assert_held(&queue->lock);
> +	queue->mem_used -= entry->truesize;
> +	entry->truesize = 0;
> +}
> +
>  static struct nfqnl_instance *
>  instance_create(struct nfnl_queue_net *q, u_int16_t queue_num, u32 portid)
>  {
> @@ -152,6 +176,7 @@ instance_create(struct nfnl_queue_net *q, u_int16_t queue_num, u32 portid)
>  	inst->queue_num = queue_num;
>  	inst->peer_portid = portid;
>  	inst->queue_maxlen = NFQNL_QMAX_DEFAULT;
> +	inst->mem_limit = nfqnl_mem_limit(NFQNL_QMAX_DEFAULT);
>  	inst->copy_range = NFQNL_MAX_COPY_RANGE;
>  	inst->copy_mode = NFQNL_COPY_NONE;
>  	spin_lock_init(&inst->lock);
> @@ -199,6 +224,7 @@ static void instance_destroy_work(struct work_struct *work)
>  	rcu_read_lock();
>  	nfqnl_flush(inst, NULL, 0);
>  	rcu_read_unlock();
> +	WARN_ON_ONCE(inst->mem_used);

I'd suggest DEBUG_NET_WARN_ONCE() here, unless you have a strong
preference/reason for a full splat here.
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads