data_type large_stringclasses 3
values | source large_stringclasses 29
values | code large_stringlengths 98 49.4M | filepath large_stringlengths 5 161 ⌀ | message large_stringclasses 234
values | commit large_stringclasses 234
values | subject large_stringclasses 418
values | critique large_stringlengths 101 1.26M ⌀ | metadata dict |
|---|---|---|---|---|---|---|---|---|
lkml_critique | lkml | Use dev_err_probe() consistently in the probe path of several ADI IIO
drivers. This simplifies error handling and ensures proper logging of
deferred probes.
Each driver is updated by introducing a local struct device variable to
simplify repeated &spi->dev / &client->dev references, and converting
error paths to use dev_err_probe().
Drivers updated:
- adrf6780
- admv1014
- admv1013
- adf4377
- ad7293
- admv8818
Changes in v3:
- Squash the struct device variable introduction and dev_err_probe()
conversion into a single patch per driver.
Antoniu Miclaus (6):
iio: frequency: adrf6780: add dev variable and use dev_err_probe
iio: frequency: admv1014: add dev variable and use dev_err_probe
iio: frequency: admv1013: add dev variable and use dev_err_probe
iio: frequency: adf4377: add dev variable and use dev_err_probe
iio: dac: ad7293: add dev variable and use dev_err_probe
iio: filter: admv8818: add dev variable and use dev_err_probe
drivers/iio/dac/ad7293.c | 32 +++++------
drivers/iio/filter/admv8818.c | 61 ++++++++++-----------
drivers/iio/frequency/adf4377.c | 57 +++++++++----------
drivers/iio/frequency/admv1013.c | 51 ++++++++---------
drivers/iio/frequency/admv1014.c | 94 +++++++++++++++-----------------
drivers/iio/frequency/adrf6780.c | 60 ++++++++++----------
6 files changed, 168 insertions(+), 187 deletions(-)
--
2.43.0
| null | null | null | [PATCH v3 0/6] iio: use dev_err_probe in probe path for ADI drivers | On Fri, Feb 27, 2026 at 11:23:10AM +0000, Miclaus, Antoniu wrote:
Whenever you use it first, there you introduce it. I believe in this case it
will in the first patch of each driver subseries. Whatever the first patch is.
--
With Best Regards,
Andy Shevchenko | {
"author": "Andy Shevchenko <andriy.shevchenko@intel.com>",
"date": "Fri, 27 Feb 2026 16:48:46 +0200",
"is_openbsd": false,
"thread_id": "aaGuzkHk6kCkcyiz@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | The indirection through the resources array is unnecessarily complicated
and resuling in using IS_ERR() and PTR_ERR() on a valid address. A local
variable for the devm_ioremap_resource() return value is both easier to
read and matches expectations when reading code.
Reported-by: Dan Carpenter <dan.carpenter@linaro.org>
Closes: https://lore.kernel.org/asahi/aYXvX1bYOXtYCgfC@stanley.mountain/
Suggested-by: Vladimir Oltean <olteanv@gmail.com>
Fixes: 8e98ca1e74db ("phy: apple: Add Apple Type-C PHY")
Signed-off-by: Janne Grunau <j@jannau.net>
---
Changes in v2:
- Use a local variable instead of the complex indirection with the
resources array
- Link to v1: https://lore.kernel.org/r/20260207-phy-apple-resource-err-ptr-v1-1-78735b07ed2d@jannau.net
---
drivers/phy/apple/atc.c | 8 +++++---
1 file changed, 5 insertions(+), 3 deletions(-)
diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c
index dc867f368b68748ea953e594ad998d7f965d8d1d..64d0c3dba1cbb95f867d338da706225ee0bf79f7 100644
--- a/drivers/phy/apple/atc.c
+++ b/drivers/phy/apple/atc.c
@@ -2202,14 +2202,16 @@ static int atcphy_map_resources(struct platform_device *pdev, struct apple_atcph
{ "pipehandler", &atcphy->regs.pipehandler, NULL },
};
struct resource *res;
+ void __iomem *addr;
for (int i = 0; i < ARRAY_SIZE(resources); i++) {
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, resources[i].name);
- *resources[i].addr = devm_ioremap_resource(&pdev->dev, res);
- if (IS_ERR(resources[i].addr))
- return dev_err_probe(atcphy->dev, PTR_ERR(resources[i].addr),
+ addr = devm_ioremap_resource(&pdev->dev, res);
+ if (IS_ERR(addr))
+ return dev_err_probe(atcphy->dev, PTR_ERR(addr),
"Unable to map %s regs", resources[i].name);
+ *resources[i].addr = addr;
if (resources[i].res)
*resources[i].res = res;
}
---
base-commit: dbeea86fecef7cf2b93aded4525d74f6277376ef
change-id: 20260207-phy-apple-resource-err-ptr-5923d1130465
Best regards,
--
Janne Grunau <j@jannau.net>
| null | null | null | [PATCH phy-next v2] phy: apple: apple: Use local variable for
ioremap return value | On 15.02.26 09:02, Janne Grunau wrote:
Reviewed-by: Sven Peter <sven@kernel.org>
This is much easier to understand. I missed return PTR_ERR(..) error in
the first version and introduced it originally due to the indirection as
well.
Best,
Sven | {
"author": "Sven Peter <sven@kernel.org>",
"date": "Sun, 15 Feb 2026 13:07:39 +0100",
"is_openbsd": false,
"thread_id": "177220616687.330302.14977409521915392205.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | The indirection through the resources array is unnecessarily complicated
and resuling in using IS_ERR() and PTR_ERR() on a valid address. A local
variable for the devm_ioremap_resource() return value is both easier to
read and matches expectations when reading code.
Reported-by: Dan Carpenter <dan.carpenter@linaro.org>
Closes: https://lore.kernel.org/asahi/aYXvX1bYOXtYCgfC@stanley.mountain/
Suggested-by: Vladimir Oltean <olteanv@gmail.com>
Fixes: 8e98ca1e74db ("phy: apple: Add Apple Type-C PHY")
Signed-off-by: Janne Grunau <j@jannau.net>
---
Changes in v2:
- Use a local variable instead of the complex indirection with the
resources array
- Link to v1: https://lore.kernel.org/r/20260207-phy-apple-resource-err-ptr-v1-1-78735b07ed2d@jannau.net
---
drivers/phy/apple/atc.c | 8 +++++---
1 file changed, 5 insertions(+), 3 deletions(-)
diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c
index dc867f368b68748ea953e594ad998d7f965d8d1d..64d0c3dba1cbb95f867d338da706225ee0bf79f7 100644
--- a/drivers/phy/apple/atc.c
+++ b/drivers/phy/apple/atc.c
@@ -2202,14 +2202,16 @@ static int atcphy_map_resources(struct platform_device *pdev, struct apple_atcph
{ "pipehandler", &atcphy->regs.pipehandler, NULL },
};
struct resource *res;
+ void __iomem *addr;
for (int i = 0; i < ARRAY_SIZE(resources); i++) {
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, resources[i].name);
- *resources[i].addr = devm_ioremap_resource(&pdev->dev, res);
- if (IS_ERR(resources[i].addr))
- return dev_err_probe(atcphy->dev, PTR_ERR(resources[i].addr),
+ addr = devm_ioremap_resource(&pdev->dev, res);
+ if (IS_ERR(addr))
+ return dev_err_probe(atcphy->dev, PTR_ERR(addr),
"Unable to map %s regs", resources[i].name);
+ *resources[i].addr = addr;
if (resources[i].res)
*resources[i].res = res;
}
---
base-commit: dbeea86fecef7cf2b93aded4525d74f6277376ef
change-id: 20260207-phy-apple-resource-err-ptr-5923d1130465
Best regards,
--
Janne Grunau <j@jannau.net>
| null | null | null | [PATCH phy-next v2] phy: apple: apple: Use local variable for
ioremap return value | On Sun, Feb 15, 2026 at 09:02:51AM +0100, Janne Grunau wrote:
Reviewed-by: Vladimir Oltean <olteanv@gmail.com>
I hope this can be picked up for the linux-phy PR. | {
"author": "Vladimir Oltean <olteanv@gmail.com>",
"date": "Mon, 16 Feb 2026 11:04:56 +0200",
"is_openbsd": false,
"thread_id": "177220616687.330302.14977409521915392205.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | The indirection through the resources array is unnecessarily complicated
and resuling in using IS_ERR() and PTR_ERR() on a valid address. A local
variable for the devm_ioremap_resource() return value is both easier to
read and matches expectations when reading code.
Reported-by: Dan Carpenter <dan.carpenter@linaro.org>
Closes: https://lore.kernel.org/asahi/aYXvX1bYOXtYCgfC@stanley.mountain/
Suggested-by: Vladimir Oltean <olteanv@gmail.com>
Fixes: 8e98ca1e74db ("phy: apple: Add Apple Type-C PHY")
Signed-off-by: Janne Grunau <j@jannau.net>
---
Changes in v2:
- Use a local variable instead of the complex indirection with the
resources array
- Link to v1: https://lore.kernel.org/r/20260207-phy-apple-resource-err-ptr-v1-1-78735b07ed2d@jannau.net
---
drivers/phy/apple/atc.c | 8 +++++---
1 file changed, 5 insertions(+), 3 deletions(-)
diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c
index dc867f368b68748ea953e594ad998d7f965d8d1d..64d0c3dba1cbb95f867d338da706225ee0bf79f7 100644
--- a/drivers/phy/apple/atc.c
+++ b/drivers/phy/apple/atc.c
@@ -2202,14 +2202,16 @@ static int atcphy_map_resources(struct platform_device *pdev, struct apple_atcph
{ "pipehandler", &atcphy->regs.pipehandler, NULL },
};
struct resource *res;
+ void __iomem *addr;
for (int i = 0; i < ARRAY_SIZE(resources); i++) {
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, resources[i].name);
- *resources[i].addr = devm_ioremap_resource(&pdev->dev, res);
- if (IS_ERR(resources[i].addr))
- return dev_err_probe(atcphy->dev, PTR_ERR(resources[i].addr),
+ addr = devm_ioremap_resource(&pdev->dev, res);
+ if (IS_ERR(addr))
+ return dev_err_probe(atcphy->dev, PTR_ERR(addr),
"Unable to map %s regs", resources[i].name);
+ *resources[i].addr = addr;
if (resources[i].res)
*resources[i].res = res;
}
---
base-commit: dbeea86fecef7cf2b93aded4525d74f6277376ef
change-id: 20260207-phy-apple-resource-err-ptr-5923d1130465
Best regards,
--
Janne Grunau <j@jannau.net>
| null | null | null | [PATCH phy-next v2] phy: apple: apple: Use local variable for
ioremap return value | On Sun, 15 Feb 2026 09:02:51 +0100, Janne Grunau wrote:
Applied, thanks!
[1/1] phy: apple: apple: Use local variable for ioremap return value
commit: 290a35756aaef85bbe0527eaf451f533a61b5f6c
Best regards,
--
~Vinod | {
"author": "Vinod Koul <vkoul@kernel.org>",
"date": "Fri, 27 Feb 2026 20:59:26 +0530",
"is_openbsd": false,
"thread_id": "177220616687.330302.14977409521915392205.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | Add the three namespace lifecycle hooks and make them available to bpf
lsm program types. This allows bpf to supervise namespace creation. I'm
in the process of adding various "universal truth" bpf programs to
systemd that will make use of this. This e.g., allows to lock in a
program into a given set of namespaces.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
include/linux/bpf_lsm.h | 21 +++++++++++++++++++++
kernel/bpf/bpf_lsm.c | 25 +++++++++++++++++++++++++
kernel/nscommon.c | 9 ++++++++-
kernel/nsproxy.c | 7 +++++++
4 files changed, 61 insertions(+), 1 deletion(-)
diff --git a/include/linux/bpf_lsm.h b/include/linux/bpf_lsm.h
index 643809cc78c3..5ae438fdf567 100644
--- a/include/linux/bpf_lsm.h
+++ b/include/linux/bpf_lsm.h
@@ -12,6 +12,9 @@
#include <linux/bpf_verifier.h>
#include <linux/lsm_hooks.h>
+struct ns_common;
+struct nsset;
+
#ifdef CONFIG_BPF_LSM
#define LSM_HOOK(RET, DEFAULT, NAME, ...) \
@@ -48,6 +51,11 @@ void bpf_lsm_find_cgroup_shim(const struct bpf_prog *prog, bpf_func_t *bpf_func)
int bpf_lsm_get_retval_range(const struct bpf_prog *prog,
struct bpf_retval_range *range);
+
+int bpf_lsm_namespace_alloc(struct ns_common *ns);
+void bpf_lsm_namespace_free(struct ns_common *ns);
+int bpf_lsm_namespace_install(struct nsset *nsset, struct ns_common *ns);
+
int bpf_set_dentry_xattr_locked(struct dentry *dentry, const char *name__str,
const struct bpf_dynptr *value_p, int flags);
int bpf_remove_dentry_xattr_locked(struct dentry *dentry, const char *name__str);
@@ -104,6 +112,19 @@ static inline bool bpf_lsm_has_d_inode_locked(const struct bpf_prog *prog)
{
return false;
}
+
+static inline int bpf_lsm_namespace_alloc(struct ns_common *ns)
+{
+ return 0;
+}
+static inline void bpf_lsm_namespace_free(struct ns_common *ns)
+{
+}
+static inline int bpf_lsm_namespace_install(struct nsset *nsset,
+ struct ns_common *ns)
+{
+ return 0;
+}
#endif /* CONFIG_BPF_LSM */
#endif /* _LINUX_BPF_LSM_H */
diff --git a/kernel/bpf/bpf_lsm.c b/kernel/bpf/bpf_lsm.c
index 0c4a0c8e6f70..f6378db46220 100644
--- a/kernel/bpf/bpf_lsm.c
+++ b/kernel/bpf/bpf_lsm.c
@@ -30,10 +30,32 @@ __weak noinline RET bpf_lsm_##NAME(__VA_ARGS__) \
#include <linux/lsm_hook_defs.h>
#undef LSM_HOOK
+__bpf_hook_start();
+
+__weak noinline int bpf_lsm_namespace_alloc(struct ns_common *ns)
+{
+ return 0;
+}
+
+__weak noinline void bpf_lsm_namespace_free(struct ns_common *ns)
+{
+}
+
+__weak noinline int bpf_lsm_namespace_install(struct nsset *nsset,
+ struct ns_common *ns)
+{
+ return 0;
+}
+
+__bpf_hook_end();
+
#define LSM_HOOK(RET, DEFAULT, NAME, ...) BTF_ID(func, bpf_lsm_##NAME)
BTF_SET_START(bpf_lsm_hooks)
#include <linux/lsm_hook_defs.h>
#undef LSM_HOOK
+BTF_ID(func, bpf_lsm_namespace_alloc)
+BTF_ID(func, bpf_lsm_namespace_free)
+BTF_ID(func, bpf_lsm_namespace_install)
BTF_SET_END(bpf_lsm_hooks)
BTF_SET_START(bpf_lsm_disabled_hooks)
@@ -383,6 +405,8 @@ BTF_ID(func, bpf_lsm_task_prctl)
BTF_ID(func, bpf_lsm_task_setscheduler)
BTF_ID(func, bpf_lsm_task_to_inode)
BTF_ID(func, bpf_lsm_userns_create)
+BTF_ID(func, bpf_lsm_namespace_alloc)
+BTF_ID(func, bpf_lsm_namespace_install)
BTF_SET_END(sleepable_lsm_hooks)
BTF_SET_START(untrusted_lsm_hooks)
@@ -395,6 +419,7 @@ BTF_ID(func, bpf_lsm_sk_alloc_security)
BTF_ID(func, bpf_lsm_sk_free_security)
#endif /* CONFIG_SECURITY_NETWORK */
BTF_ID(func, bpf_lsm_task_free)
+BTF_ID(func, bpf_lsm_namespace_free)
BTF_SET_END(untrusted_lsm_hooks)
bool bpf_lsm_is_sleepable_hook(u32 btf_id)
diff --git a/kernel/nscommon.c b/kernel/nscommon.c
index bdc3c86231d3..c3613cab3d41 100644
--- a/kernel/nscommon.c
+++ b/kernel/nscommon.c
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2025 Christian Brauner <brauner@kernel.org> */
+#include <linux/bpf_lsm.h>
#include <linux/ns_common.h>
#include <linux/nstree.h>
#include <linux/proc_ns.h>
@@ -77,6 +78,7 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope
ret = proc_alloc_inum(&ns->inum);
if (ret)
return ret;
+
/*
* Tree ref starts at 0. It's incremented when namespace enters
* active use (installed in nsproxy) and decremented when all
@@ -86,11 +88,16 @@ int __ns_common_init(struct ns_common *ns, u32 ns_type, const struct proc_ns_ope
atomic_set(&ns->__ns_ref_active, 1);
else
atomic_set(&ns->__ns_ref_active, 0);
- return 0;
+
+ ret = bpf_lsm_namespace_alloc(ns);
+ if (ret && !inum)
+ proc_free_inum(ns->inum);
+ return ret;
}
void __ns_common_free(struct ns_common *ns)
{
+ bpf_lsm_namespace_free(ns);
proc_free_inum(ns->inum);
}
diff --git a/kernel/nsproxy.c b/kernel/nsproxy.c
index 259c4b4f1eeb..5742f9664dbb 100644
--- a/kernel/nsproxy.c
+++ b/kernel/nsproxy.c
@@ -9,6 +9,7 @@
* Pavel Emelianov <xemul@openvz.org>
*/
+#include <linux/bpf_lsm.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/nsproxy.h>
@@ -379,6 +380,12 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)
static inline int validate_ns(struct nsset *nsset, struct ns_common *ns)
{
+ int ret;
+
+ ret = bpf_lsm_namespace_install(nsset, ns);
+ if (ret)
+ return ret;
+
return ns->ops->install(nsset, ns);
}
--
2.47.3 | {
"author": "Christian Brauner <brauner@kernel.org>",
"date": "Fri, 20 Feb 2026 01:38:29 +0100",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | Add a hook to manage attaching tasks to cgroup. I'm in the process of
adding various "universal truth" bpf programs to systemd that will make
use of this.
This has been a long-standing request (cf. [1] and [2]). It will allow us to
enforce cgroup migrations and ensure that services can never escape their
cgroups. This is just one of many use-cases.
Link: https://github.com/systemd/systemd/issues/6356 [1]
Link: https://github.com/systemd/systemd/issues/22874 [2]
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
include/linux/bpf_lsm.h | 15 +++++++++++++++
kernel/bpf/bpf_lsm.c | 12 ++++++++++++
kernel/cgroup/cgroup.c | 18 +++++++++++-------
3 files changed, 38 insertions(+), 7 deletions(-)
diff --git a/include/linux/bpf_lsm.h b/include/linux/bpf_lsm.h
index 5ae438fdf567..bc1d35b271f5 100644
--- a/include/linux/bpf_lsm.h
+++ b/include/linux/bpf_lsm.h
@@ -12,8 +12,11 @@
#include <linux/bpf_verifier.h>
#include <linux/lsm_hooks.h>
+struct cgroup;
+struct cgroup_namespace;
struct ns_common;
struct nsset;
+struct super_block;
#ifdef CONFIG_BPF_LSM
@@ -55,6 +58,9 @@ int bpf_lsm_get_retval_range(const struct bpf_prog *prog,
int bpf_lsm_namespace_alloc(struct ns_common *ns);
void bpf_lsm_namespace_free(struct ns_common *ns);
int bpf_lsm_namespace_install(struct nsset *nsset, struct ns_common *ns);
+int bpf_lsm_cgroup_attach(struct task_struct *task, struct cgroup *src_cgrp,
+ struct cgroup *dst_cgrp, struct super_block *sb,
+ bool threadgroup, struct cgroup_namespace *ns);
int bpf_set_dentry_xattr_locked(struct dentry *dentry, const char *name__str,
const struct bpf_dynptr *value_p, int flags);
@@ -125,6 +131,15 @@ static inline int bpf_lsm_namespace_install(struct nsset *nsset,
{
return 0;
}
+static inline int bpf_lsm_cgroup_attach(struct task_struct *task,
+ struct cgroup *src_cgrp,
+ struct cgroup *dst_cgrp,
+ struct super_block *sb,
+ bool threadgroup,
+ struct cgroup_namespace *ns)
+{
+ return 0;
+}
#endif /* CONFIG_BPF_LSM */
#endif /* _LINUX_BPF_LSM_H */
diff --git a/kernel/bpf/bpf_lsm.c b/kernel/bpf/bpf_lsm.c
index f6378db46220..1da5585082fa 100644
--- a/kernel/bpf/bpf_lsm.c
+++ b/kernel/bpf/bpf_lsm.c
@@ -47,6 +47,16 @@ __weak noinline int bpf_lsm_namespace_install(struct nsset *nsset,
return 0;
}
+__weak noinline int bpf_lsm_cgroup_attach(struct task_struct *task,
+ struct cgroup *src_cgrp,
+ struct cgroup *dst_cgrp,
+ struct super_block *sb,
+ bool threadgroup,
+ struct cgroup_namespace *ns)
+{
+ return 0;
+}
+
__bpf_hook_end();
#define LSM_HOOK(RET, DEFAULT, NAME, ...) BTF_ID(func, bpf_lsm_##NAME)
@@ -56,6 +66,7 @@ BTF_SET_START(bpf_lsm_hooks)
BTF_ID(func, bpf_lsm_namespace_alloc)
BTF_ID(func, bpf_lsm_namespace_free)
BTF_ID(func, bpf_lsm_namespace_install)
+BTF_ID(func, bpf_lsm_cgroup_attach)
BTF_SET_END(bpf_lsm_hooks)
BTF_SET_START(bpf_lsm_disabled_hooks)
@@ -407,6 +418,7 @@ BTF_ID(func, bpf_lsm_task_to_inode)
BTF_ID(func, bpf_lsm_userns_create)
BTF_ID(func, bpf_lsm_namespace_alloc)
BTF_ID(func, bpf_lsm_namespace_install)
+BTF_ID(func, bpf_lsm_cgroup_attach)
BTF_SET_END(sleepable_lsm_hooks)
BTF_SET_START(untrusted_lsm_hooks)
diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c
index 8af4351536cf..16535349b22f 100644
--- a/kernel/cgroup/cgroup.c
+++ b/kernel/cgroup/cgroup.c
@@ -28,6 +28,7 @@
#include "cgroup-internal.h"
#include <linux/bpf-cgroup.h>
+#include <linux/bpf_lsm.h>
#include <linux/cred.h>
#include <linux/errno.h>
#include <linux/init_task.h>
@@ -5334,7 +5335,8 @@ static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
return 0;
}
-static int cgroup_attach_permissions(struct cgroup *src_cgrp,
+static int cgroup_attach_permissions(struct task_struct *task,
+ struct cgroup *src_cgrp,
struct cgroup *dst_cgrp,
struct super_block *sb, bool threadgroup,
struct cgroup_namespace *ns)
@@ -5350,9 +5352,9 @@ static int cgroup_attach_permissions(struct cgroup *src_cgrp,
return ret;
if (!threadgroup && (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp))
- ret = -EOPNOTSUPP;
+ return -EOPNOTSUPP;
- return ret;
+ return bpf_lsm_cgroup_attach(task, src_cgrp, dst_cgrp, sb, threadgroup, ns);
}
static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
@@ -5384,7 +5386,7 @@ static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
* inherited fd attacks.
*/
scoped_with_creds(of->file->f_cred)
- ret = cgroup_attach_permissions(src_cgrp, dst_cgrp,
+ ret = cgroup_attach_permissions(task, src_cgrp, dst_cgrp,
of->file->f_path.dentry->d_sb,
threadgroup, ctx->ns);
if (ret)
@@ -6669,6 +6671,7 @@ static struct cgroup *cgroup_get_from_file(struct file *f)
/**
* cgroup_css_set_fork - find or create a css_set for a child process
+ * @task: the task to be attached
* @kargs: the arguments passed to create the child process
*
* This functions finds or creates a new css_set which the child
@@ -6683,7 +6686,8 @@ static struct cgroup *cgroup_get_from_file(struct file *f)
* before grabbing cgroup_threadgroup_rwsem and will hold a reference
* to the target cgroup.
*/
-static int cgroup_css_set_fork(struct kernel_clone_args *kargs)
+static int cgroup_css_set_fork(struct task_struct *task,
+ struct kernel_clone_args *kargs)
__acquires(&cgroup_mutex) __acquires(&cgroup_threadgroup_rwsem)
{
int ret;
@@ -6752,7 +6756,7 @@ static int cgroup_css_set_fork(struct kernel_clone_args *kargs)
* cgroup.procs of the cgroup indicated by @dfd_cgroup. This allows us
* to always use the caller's credentials.
*/
- ret = cgroup_attach_permissions(cset->dfl_cgrp, dst_cgrp, sb,
+ ret = cgroup_attach_permissions(task, cset->dfl_cgrp, dst_cgrp, sb,
!(kargs->flags & CLONE_THREAD),
current->nsproxy->cgroup_ns);
if (ret)
@@ -6824,7 +6828,7 @@ int cgroup_can_fork(struct task_struct *child, struct kernel_clone_args *kargs)
struct cgroup_subsys *ss;
int i, j, ret;
- ret = cgroup_css_set_fork(kargs);
+ ret = cgroup_css_set_fork(child, kargs);
if (ret)
return ret;
--
2.47.3 | {
"author": "Christian Brauner <brauner@kernel.org>",
"date": "Fri, 20 Feb 2026 01:38:30 +0100",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | Add a BPF LSM selftest that implements a "lock on entry" namespace
sandbox policy.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++++++++++++++++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++++++++++++++++
2 files changed, 190 insertions(+)
diff --git a/tools/testing/selftests/bpf/prog_tests/ns_sandbox.c b/tools/testing/selftests/bpf/prog_tests/ns_sandbox.c
new file mode 100644
index 000000000000..0ac2acfb6365
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/ns_sandbox.c
@@ -0,0 +1,99 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Christian Brauner <brauner@kernel.org> */
+
+/*
+ * Test BPF LSM namespace sandbox: once you enter, you stay.
+ *
+ * The parent creates a tracked namespace, then forks a child.
+ * The child enters the tracked namespace (allowed) and is then locked
+ * out of any further setns().
+ */
+
+#define _GNU_SOURCE
+#include <test_progs.h>
+#include <sched.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/wait.h>
+#include "test_ns_sandbox.skel.h"
+
+void test_ns_sandbox(void)
+{
+ int orig_utsns = -1, new_utsns = -1;
+ struct test_ns_sandbox *skel = NULL;
+ int err, status;
+ pid_t child;
+
+ /* Save FD to current (host) namespace */
+ orig_utsns = open("/proc/self/ns/uts", O_RDONLY);
+ if (!ASSERT_OK_FD(orig_utsns, "open orig utsns"))
+ goto close_fds;
+
+ skel = test_ns_sandbox__open_and_load();
+ if (!ASSERT_OK_PTR(skel, "skel open_and_load"))
+ goto close_fds;
+
+ err = test_ns_sandbox__attach(skel);
+ if (!ASSERT_OK(err, "skel attach"))
+ goto destroy;
+
+ skel->bss->monitor_pid = getpid();
+
+ /*
+ * Create a sandbox namespace. The alloc hook records its
+ * inum because this task's pid matches monitor_pid.
+ */
+ err = unshare(CLONE_NEWUTS);
+ if (!ASSERT_OK(err, "unshare sandbox"))
+ goto destroy;
+
+ new_utsns = open("/proc/self/ns/uts", O_RDONLY);
+ if (!ASSERT_OK_FD(new_utsns, "open sandbox utsns"))
+ goto restore;
+
+ /*
+ * Return parent to host namespace. The host namespace is not
+ * in the map so the install hook lets us through.
+ */
+ err = setns(orig_utsns, CLONE_NEWUTS);
+ if (!ASSERT_OK(err, "parent setns host utsns"))
+ goto restore;
+
+ /*
+ * Fork a child that:
+ * 1. Enters the sandbox UTS namespace — succeeds and locks it.
+ * 2. Tries to switch to host UTS — denied (locked).
+ */
+ child = fork();
+ if (child == 0) {
+ /* Enter tracked namespace — allowed, we get locked */
+ if (setns(new_utsns, CLONE_NEWUTS) != 0)
+ _exit(1);
+
+ /* Locked: switching to host must fail */
+ if (setns(orig_utsns, CLONE_NEWUTS) != -1 ||
+ errno != EPERM)
+ _exit(2);
+
+ _exit(0);
+ }
+ if (!ASSERT_GE(child, 0, "fork child"))
+ goto restore;
+
+ err = waitpid(child, &status, 0);
+ ASSERT_GT(err, 0, "waitpid child");
+ ASSERT_TRUE(WIFEXITED(status), "child exited");
+ ASSERT_EQ(WEXITSTATUS(status), 0, "child locked in");
+
+ goto destroy;
+
+restore:
+ setns(orig_utsns, CLONE_NEWUTS);
+destroy:
+ test_ns_sandbox__destroy(skel);
+close_fds:
+ if (new_utsns >= 0)
+ close(new_utsns);
+ if (orig_utsns >= 0)
+ close(orig_utsns);
+}
diff --git a/tools/testing/selftests/bpf/progs/test_ns_sandbox.c b/tools/testing/selftests/bpf/progs/test_ns_sandbox.c
new file mode 100644
index 000000000000..75c3493932a1
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/test_ns_sandbox.c
@@ -0,0 +1,91 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Christian Brauner <brauner@kernel.org> */
+
+/*
+ * BPF LSM namespace sandbox: once you enter, you stay.
+ *
+ * A designated process creates namespaces (tracked via alloc). When
+ * any other process joins one of those namespaces it gets recorded in
+ * locked_tasks. From that point on that process cannot setns() into
+ * any other namespace — it is locked in. Task local storage is
+ * automatically freed when the task exits.
+ */
+
+#include "vmlinux.h"
+#include <errno.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+/*
+ * Namespaces created by the monitored process.
+ * Key: namespace inode number.
+ * Value: namespace type (CLONE_NEW* flag).
+ */
+struct {
+ __uint(type, BPF_MAP_TYPE_HASH);
+ __uint(max_entries, 64);
+ __type(key, __u32);
+ __type(value, __u32);
+} known_namespaces SEC(".maps");
+
+/* PID of the process whose namespace creations are tracked. */
+int monitor_pid;
+
+/*
+ * Task local storage: marks tasks that have entered a tracked namespace
+ * and are now locked.
+ */
+struct {
+ __uint(type, BPF_MAP_TYPE_TASK_STORAGE);
+ __uint(map_flags, BPF_F_NO_PREALLOC);
+ __type(key, int);
+ __type(value, __u8);
+} locked_tasks SEC(".maps");
+
+char _license[] SEC("license") = "GPL";
+
+/* Only the monitored process's namespace creations are tracked. */
+SEC("lsm.s/namespace_alloc")
+int BPF_PROG(ns_alloc, struct ns_common *ns)
+{
+ __u32 inum, ns_type;
+
+ if ((bpf_get_current_pid_tgid() >> 32) != monitor_pid)
+ return 0;
+
+ inum = ns->inum;
+ ns_type = ns->ns_type;
+ bpf_map_update_elem(&known_namespaces, &inum, &ns_type, BPF_ANY);
+
+ return 0;
+}
+
+/*
+ * Enforce the lock-in policy for all tasks:
+ * - Already locked? Deny any setns.
+ * - Entering a tracked namespace? Lock the task and allow.
+ * - Everything else passes through.
+ */
+SEC("lsm.s/namespace_install")
+int BPF_PROG(ns_install, struct nsset *nsset, struct ns_common *ns)
+{
+ struct task_struct *task = bpf_get_current_task_btf();
+ __u32 inum = ns->inum;
+
+ if (bpf_task_storage_get(&locked_tasks, task, 0, 0))
+ return -EPERM;
+
+ if (bpf_map_lookup_elem(&known_namespaces, &inum))
+ bpf_task_storage_get(&locked_tasks, task, 0,
+ BPF_LOCAL_STORAGE_GET_F_CREATE);
+
+ return 0;
+}
+
+SEC("lsm/namespace_free")
+void BPF_PROG(ns_free, struct ns_common *ns)
+{
+ __u32 inum = ns->inum;
+
+ bpf_map_delete_elem(&known_namespaces, &inum);
+}
--
2.47.3 | {
"author": "Christian Brauner <brauner@kernel.org>",
"date": "Fri, 20 Feb 2026 01:38:31 +0100",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | Signed-off-by: Christian Brauner <brauner@kernel.org>
---
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
2 files changed, 447 insertions(+)
diff --git a/tools/testing/selftests/bpf/prog_tests/cgroup_attach.c b/tools/testing/selftests/bpf/prog_tests/cgroup_attach.c
new file mode 100644
index 000000000000..05addf93af46
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/cgroup_attach.c
@@ -0,0 +1,362 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Christian Brauner <brauner@kernel.org> */
+
+/*
+ * Test the bpf_lsm_cgroup_attach hook.
+ *
+ * Verifies that a BPF LSM program can supervise cgroup migration
+ * through both the cgroup.procs write path and the clone3 +
+ * CLONE_INTO_CGROUP path.
+ */
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/sched.h>
+#include <linux/types.h>
+#include <sched.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <syscall.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include <test_progs.h>
+#include "cgroup_helpers.h"
+#include "test_cgroup_attach.skel.h"
+
+/* Must match the definition in progs/test_cgroup_attach.c */
+struct attach_event {
+ __u32 task_pid;
+ __u64 src_cgrp_id;
+ __u64 dst_cgrp_id;
+ __u8 threadgroup;
+ __u32 hook_count;
+};
+
+#ifndef CLONE_INTO_CGROUP
+#define CLONE_INTO_CGROUP 0x200000000ULL
+#endif
+
+#ifndef __NR_clone3
+#define __NR_clone3 435
+#endif
+
+struct __clone_args {
+ __aligned_u64 flags;
+ __aligned_u64 pidfd;
+ __aligned_u64 child_tid;
+ __aligned_u64 parent_tid;
+ __aligned_u64 exit_signal;
+ __aligned_u64 stack;
+ __aligned_u64 stack_size;
+ __aligned_u64 tls;
+ __aligned_u64 set_tid;
+ __aligned_u64 set_tid_size;
+ __aligned_u64 cgroup;
+};
+
+static pid_t do_clone3(int cgroup_fd)
+{
+ struct __clone_args args = {
+ .flags = CLONE_INTO_CGROUP,
+ .exit_signal = SIGCHLD,
+ .cgroup = cgroup_fd,
+ };
+
+ return syscall(__NR_clone3, &args, sizeof(args));
+}
+
+/*
+ * Subtest: deny_migration
+ *
+ * Verify that the BPF hook can deny cgroup migration through cgroup.procs
+ * and that detaching the BPF program removes enforcement.
+ */
+static void test_deny_migration(void)
+{
+ struct test_cgroup_attach *skel = NULL;
+ int allowed_fd = -1, denied_fd = -1;
+ unsigned long long denied_cgid;
+ int err, status;
+ __u64 key;
+ __u8 val = 1;
+ pid_t child;
+
+ if (!ASSERT_OK(setup_cgroup_environment(), "setup_cgroup_env"))
+ return;
+
+ allowed_fd = create_and_get_cgroup("/allowed");
+ if (!ASSERT_GE(allowed_fd, 0, "create /allowed"))
+ goto cleanup;
+
+ denied_fd = create_and_get_cgroup("/denied");
+ if (!ASSERT_GE(denied_fd, 0, "create /denied"))
+ goto cleanup;
+
+ skel = test_cgroup_attach__open_and_load();
+ if (!ASSERT_OK_PTR(skel, "skel open_and_load"))
+ goto cleanup;
+
+ err = test_cgroup_attach__attach(skel);
+ if (!ASSERT_OK(err, "skel attach"))
+ goto cleanup;
+
+ skel->bss->monitored_pid = getpid();
+
+ denied_cgid = get_cgroup_id("/denied");
+ if (!ASSERT_NEQ(denied_cgid, 0ULL, "get denied cgroup id"))
+ goto cleanup;
+
+ key = denied_cgid;
+ err = bpf_map__update_elem(skel->maps.denied_cgroups,
+ &key, sizeof(key), &val, sizeof(val), 0);
+ if (!ASSERT_OK(err, "add denied cgroup"))
+ goto cleanup;
+
+ /*
+ * Forked children must use join_parent_cgroup() because the
+ * cgroup workdir was created under the parent's PID and
+ * join_cgroup() constructs paths using getpid().
+ */
+
+ /* Child migrating to /allowed should succeed */
+ child = fork();
+ if (!ASSERT_GE(child, 0, "fork child allowed"))
+ goto cleanup;
+ if (child == 0) {
+ if (join_parent_cgroup("/allowed"))
+ _exit(1);
+ _exit(0);
+ }
+ err = waitpid(child, &status, 0);
+ ASSERT_GT(err, 0, "waitpid allowed");
+ ASSERT_TRUE(WIFEXITED(status), "allowed child exited");
+ ASSERT_EQ(WEXITSTATUS(status), 0, "allowed migration succeeds");
+
+ /* Child migrating to /denied should fail */
+ child = fork();
+ if (!ASSERT_GE(child, 0, "fork child denied"))
+ goto cleanup;
+ if (child == 0) {
+ if (join_parent_cgroup("/denied") == 0)
+ _exit(1); /* Should have failed */
+ if (errno != EPERM)
+ _exit(2); /* Wrong errno */
+ _exit(0);
+ }
+ err = waitpid(child, &status, 0);
+ ASSERT_GT(err, 0, "waitpid denied");
+ ASSERT_TRUE(WIFEXITED(status), "denied child exited");
+ ASSERT_EQ(WEXITSTATUS(status), 0, "denied migration blocked");
+
+ /* Detach BPF — /denied should now be accessible */
+ test_cgroup_attach__detach(skel);
+
+ child = fork();
+ if (!ASSERT_GE(child, 0, "fork child post-detach"))
+ goto cleanup;
+ if (child == 0) {
+ if (join_parent_cgroup("/denied"))
+ _exit(1);
+ _exit(0);
+ }
+ err = waitpid(child, &status, 0);
+ ASSERT_GT(err, 0, "waitpid post-detach");
+ ASSERT_TRUE(WIFEXITED(status), "post-detach child exited");
+ ASSERT_EQ(WEXITSTATUS(status), 0, "post-detach migration free");
+
+cleanup:
+ if (skel)
+ test_cgroup_attach__destroy(skel);
+ if (allowed_fd >= 0)
+ close(allowed_fd);
+ if (denied_fd >= 0)
+ close(denied_fd);
+ cleanup_cgroup_environment();
+}
+
+/*
+ * Subtest: verify_hook_args
+ *
+ * Verify that the hook receives correct src_cgrp, dst_cgrp, task pid,
+ * and threadgroup values.
+ */
+static void test_verify_hook_args(void)
+{
+ struct test_cgroup_attach *skel = NULL;
+ struct attach_event evt = {};
+ unsigned long long src_cgid, dst_cgid;
+ int src_fd = -1, dst_fd = -1;
+ __u32 map_key = 0;
+ char pid_str[32];
+ int err;
+
+ if (!ASSERT_OK(setup_cgroup_environment(), "setup_cgroup_env"))
+ return;
+
+ src_fd = create_and_get_cgroup("/src");
+ if (!ASSERT_GE(src_fd, 0, "create /src"))
+ goto cleanup;
+
+ dst_fd = create_and_get_cgroup("/dst");
+ if (!ASSERT_GE(dst_fd, 0, "create /dst"))
+ goto cleanup;
+
+ /* Move ourselves to /src first */
+ if (!ASSERT_OK(join_cgroup("/src"), "join /src"))
+ goto cleanup;
+
+ skel = test_cgroup_attach__open_and_load();
+ if (!ASSERT_OK_PTR(skel, "skel open_and_load"))
+ goto cleanup;
+
+ err = test_cgroup_attach__attach(skel);
+ if (!ASSERT_OK(err, "skel attach"))
+ goto cleanup;
+
+ skel->bss->monitored_pid = getpid();
+
+ src_cgid = get_cgroup_id("/src");
+ dst_cgid = get_cgroup_id("/dst");
+ if (!ASSERT_NEQ(src_cgid, 0ULL, "get src cgroup id"))
+ goto cleanup;
+ if (!ASSERT_NEQ(dst_cgid, 0ULL, "get dst cgroup id"))
+ goto cleanup;
+
+ /* Migrate self to /dst via cgroup.procs (threadgroup=true) */
+ snprintf(pid_str, sizeof(pid_str), "%d", getpid());
+ if (!ASSERT_OK(write_cgroup_file("/dst", "cgroup.procs", pid_str),
+ "migrate to /dst"))
+ goto cleanup;
+
+ /* Read the recorded event */
+ err = bpf_map__lookup_elem(skel->maps.last_event,
+ &map_key, sizeof(map_key),
+ &evt, sizeof(evt), 0);
+ if (!ASSERT_OK(err, "read last_event"))
+ goto cleanup;
+
+ ASSERT_EQ(evt.src_cgrp_id, src_cgid, "src_cgrp_id matches");
+ ASSERT_EQ(evt.dst_cgrp_id, dst_cgid, "dst_cgrp_id matches");
+ ASSERT_EQ(evt.task_pid, (__u32)getpid(), "task_pid matches");
+ ASSERT_EQ(evt.threadgroup, 1, "threadgroup is true for cgroup.procs");
+ ASSERT_GE(evt.hook_count, (__u32)1, "hook fired at least once");
+
+cleanup:
+ if (skel)
+ test_cgroup_attach__destroy(skel);
+ if (src_fd >= 0)
+ close(src_fd);
+ if (dst_fd >= 0)
+ close(dst_fd);
+ cleanup_cgroup_environment();
+}
+
+/*
+ * Subtest: clone_into_cgroup
+ *
+ * Verify the hook fires on the clone3(CLONE_INTO_CGROUP) path and can
+ * deny spawning a child directly into a cgroup.
+ */
+static void test_clone_into_cgroup(void)
+{
+ struct test_cgroup_attach *skel = NULL;
+ int allowed_fd = -1, denied_fd = -1;
+ unsigned long long denied_cgid, allowed_cgid;
+ struct attach_event evt = {};
+ __u32 map_key = 0;
+ __u64 key;
+ __u8 val = 1;
+ int err, status;
+ pid_t child;
+
+ if (!ASSERT_OK(setup_cgroup_environment(), "setup_cgroup_env"))
+ return;
+
+ allowed_fd = create_and_get_cgroup("/clone_allowed");
+ if (!ASSERT_GE(allowed_fd, 0, "create /clone_allowed"))
+ goto cleanup;
+
+ denied_fd = create_and_get_cgroup("/clone_denied");
+ if (!ASSERT_GE(denied_fd, 0, "create /clone_denied"))
+ goto cleanup;
+
+ skel = test_cgroup_attach__open_and_load();
+ if (!ASSERT_OK_PTR(skel, "skel open_and_load"))
+ goto cleanup;
+
+ err = test_cgroup_attach__attach(skel);
+ if (!ASSERT_OK(err, "skel attach"))
+ goto cleanup;
+
+ skel->bss->monitored_pid = getpid();
+
+ denied_cgid = get_cgroup_id("/clone_denied");
+ allowed_cgid = get_cgroup_id("/clone_allowed");
+ if (!ASSERT_NEQ(denied_cgid, 0ULL, "get denied cgroup id"))
+ goto cleanup;
+ if (!ASSERT_NEQ(allowed_cgid, 0ULL, "get allowed cgroup id"))
+ goto cleanup;
+
+ key = denied_cgid;
+ err = bpf_map__update_elem(skel->maps.denied_cgroups,
+ &key, sizeof(key), &val, sizeof(val), 0);
+ if (!ASSERT_OK(err, "add denied cgroup"))
+ goto cleanup;
+
+ /* clone3 into denied cgroup should fail */
+ child = do_clone3(denied_fd);
+ if (child >= 0) {
+ waitpid(child, NULL, 0);
+ ASSERT_LT(child, 0, "clone3 into denied should fail");
+ goto cleanup;
+ }
+ if (errno == ENOSYS || errno == E2BIG) {
+ test__skip();
+ goto cleanup;
+ }
+ ASSERT_EQ(errno, EPERM, "clone3 denied errno");
+
+ /* clone3 into allowed cgroup should succeed */
+ child = do_clone3(allowed_fd);
+ if (!ASSERT_GE(child, 0, "clone3 into allowed"))
+ goto cleanup;
+ if (child == 0)
+ _exit(0);
+
+ err = waitpid(child, &status, 0);
+ ASSERT_GT(err, 0, "waitpid clone3 allowed");
+ ASSERT_TRUE(WIFEXITED(status), "clone3 child exited");
+ ASSERT_EQ(WEXITSTATUS(status), 0, "clone3 child ok");
+
+ /* Verify the hook recorded the allowed clone */
+ err = bpf_map__lookup_elem(skel->maps.last_event,
+ &map_key, sizeof(map_key),
+ &evt, sizeof(evt), 0);
+ if (!ASSERT_OK(err, "read last_event"))
+ goto cleanup;
+
+ ASSERT_EQ(evt.dst_cgrp_id, allowed_cgid, "clone3 dst_cgrp_id");
+
+cleanup:
+ if (skel)
+ test_cgroup_attach__destroy(skel);
+ if (allowed_fd >= 0)
+ close(allowed_fd);
+ if (denied_fd >= 0)
+ close(denied_fd);
+ cleanup_cgroup_environment();
+}
+
+void test_cgroup_attach(void)
+{
+ if (test__start_subtest("deny_migration"))
+ test_deny_migration();
+ if (test__start_subtest("verify_hook_args"))
+ test_verify_hook_args();
+ if (test__start_subtest("clone_into_cgroup"))
+ test_clone_into_cgroup();
+}
diff --git a/tools/testing/selftests/bpf/progs/test_cgroup_attach.c b/tools/testing/selftests/bpf/progs/test_cgroup_attach.c
new file mode 100644
index 000000000000..90915d1d7d64
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/test_cgroup_attach.c
@@ -0,0 +1,85 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Christian Brauner <brauner@kernel.org> */
+
+/*
+ * BPF LSM cgroup attach policy: supervise cgroup migration.
+ *
+ * A designated process populates a denied_cgroups map with cgroup IDs
+ * that should reject migration. The cgroup_attach hook checks every
+ * migration and returns -EPERM when the destination cgroup is denied.
+ * It also records the last hook invocation into last_event for the
+ * userspace test to verify arguments.
+ */
+
+#include "vmlinux.h"
+#include <errno.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+#include <bpf/bpf_core_read.h>
+
+struct attach_event {
+ __u32 task_pid;
+ __u64 src_cgrp_id;
+ __u64 dst_cgrp_id;
+ __u8 threadgroup;
+ __u32 hook_count;
+};
+
+/*
+ * Cgroups that should reject migration.
+ * Key: cgroup kn->id (u64).
+ * Value: unused marker.
+ */
+struct {
+ __uint(type, BPF_MAP_TYPE_HASH);
+ __uint(max_entries, 16);
+ __type(key, __u64);
+ __type(value, __u8);
+} denied_cgroups SEC(".maps");
+
+/*
+ * Record the last hook invocation for argument verification.
+ * Key: 0.
+ * Value: struct attach_event.
+ */
+struct {
+ __uint(type, BPF_MAP_TYPE_ARRAY);
+ __uint(max_entries, 1);
+ __type(key, __u32);
+ __type(value, struct attach_event);
+} last_event SEC(".maps");
+
+__u32 monitored_pid;
+
+char _license[] SEC("license") = "GPL";
+
+SEC("lsm.s/cgroup_attach")
+int BPF_PROG(cgroup_attach, struct task_struct *task,
+ struct cgroup *src_cgrp, struct cgroup *dst_cgrp,
+ struct super_block *sb, bool threadgroup,
+ struct cgroup_namespace *ns)
+{
+ struct task_struct *current = bpf_get_current_task_btf();
+ struct attach_event *evt;
+ __u64 dst_id;
+ __u32 key = 0;
+
+ dst_id = BPF_CORE_READ(dst_cgrp, kn, id);
+
+ if (bpf_map_lookup_elem(&denied_cgroups, &dst_id))
+ return -EPERM;
+
+ if (!monitored_pid || current->tgid != monitored_pid)
+ return 0;
+
+ evt = bpf_map_lookup_elem(&last_event, &key);
+ if (evt) {
+ evt->task_pid = task->pid;
+ evt->src_cgrp_id = BPF_CORE_READ(src_cgrp, kn, id);
+ evt->dst_cgrp_id = dst_id;
+ evt->threadgroup = threadgroup ? 1 : 0;
+ evt->hook_count++;
+ }
+
+ return 0;
+}
--
2.47.3 | {
"author": "Christian Brauner <brauner@kernel.org>",
"date": "Fri, 20 Feb 2026 01:38:32 +0100",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | Hello,
On Fri, Feb 20, 2026 at 01:38:30AM +0100, Christian Brauner wrote:
dumber would also work. With CLONE_INTO_CGROUP, cgroup migration isn't
necessary at all. Would something dumber like a mount option disabling
cgroup migrations completely work too or would that be too restrictive?
Thanks.
--
tejun | {
"author": "Tejun Heo <tj@kernel.org>",
"date": "Fri, 20 Feb 2026 05:16:13 -1000",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | On Fri, Feb 20, 2026 at 05:16:13AM -1000, Tejun Heo wrote:
It would be too restrictive. I've played with various policies. For
example, a small set of tasks (like PID 1 or the session manager) are
allowed to move processes between cgroups (detectable via e.g., xattrs).
No other task is allowd. But that's already too restrictive because it
fscks over delegated subcgroups were tasks need to be moved around
(container managers etc.). IOW, any policy must be quite modular and
dynamic so a simple mount option wouldn't cover it.
As a sidenote, there would be other mount options that would be useful
but that currently aren't that easy to support/implement because of the
way cgroupfs (for historical reasons ofc) is architected where it shares
a single superblock.
I have a series (from quite some time ago) that makes cgroupfs truly
multi-instance. It would effectively behave just like tmpfs does. A new
mount gets you a new superblock. But once you have that you can e.g.,
simplify cgroup namespaces as well. I've done that work originally to
support idmapped mounts with cgroupfs but I can't find that branch
anymore. | {
"author": "Christian Brauner <brauner@kernel.org>",
"date": "Sat, 21 Feb 2026 18:57:24 +0100",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | On Fri, Feb 20, 2026 at 01:38:29AM +0100, Christian Brauner wrote:
What's the reason for not adding these new hook points to the generic
set of hooks that are currently being exposed directly by the LSM
framework? Honestly, it seems a little odd to be providing
declarations/definitions for a set of new hook points which are to be
exclusively siloed to BPF LSM implementations only. I'd argue that
some other LSM implementations could very well find namespace
lifecycle events possibly interesting. | {
"author": "Matt Bobrowski <mattbobrowski@google.com>",
"date": "Mon, 23 Feb 2026 10:36:19 +0000",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | On Mon, Feb 23, 2026 at 10:36:19AM +0000, Matt Bobrowski wrote:
The LSM layer is of the opinion that adding new security hooks is only
acceptable if an implementation for an in-tree LSM is provided alongside
it (cf. [1]). IOW, your bpf lsm needs are not sufficient justification
for adding new security hooks. So if you want to add security hooks that
a bpf lsm makes use of then you need to come up with an implementation
for another in-tree LSM.
However, a subsystem is free to add as much bpf support as it wants:
none, some, flamethrower mode. Cgroupfs has traditionally been very bpf
friendly. I maintain namespaces and rewrote the infra allowing me to
manage them uniformly now. bpf literally just needs an attach point. I
could also just add fmodret tracepoints and achieve the same result.
The same way you add bpf kfuncs to support access to functionality that
put you way past what an in-tree use would be able do. The question is
whether you want such capabilities to be bounded by in-tree users as
well.
Either a bpf lsm is an inextensible fixture bound to the scope of
security_* or you allow subsystems open to it to add functionality just
like adding a kfuncs is.
[1]: https://patch.msgid.link/20260216-work-security-namespace-v1-1-075c28758e1f@kernel.org | {
"author": "Christian Brauner <brauner@kernel.org>",
"date": "Mon, 23 Feb 2026 12:12:28 +0100",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | On 2/20/26 01:38, Christian Brauner wrote:
Thank you Christian, so if this feature is added we will also
use it.
The commit log says lock in a given set of namespaces where I see
only setns path am I right? would it make sense to also have the
check around some callers of create_new_namespaces() where
appropriate befor nsproxy switch if we don't want to go deep, but
allow a bit of control or easy checks around
CLONE_NEWNS/mount/pivot_root fs combinations?
Or defering the combination checks to userspace makes more sense?
The other clone flags are presumably nested so safe, for userns
there is already a check, and cgroup+sb you added in the other
patch is great!
Thank you! | {
"author": "Djalal Harouni <tixxdz@gmail.com>",
"date": "Mon, 23 Feb 2026 13:44:23 +0100",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | Hi.
On Fri, Feb 20, 2026 at 01:38:30AM +0100, Christian Brauner <brauner@kernel.org> wrote:
These two issues are misconfigured/misunderstood PAM configs. I don't
think those warrant introduction of another permissions mechanism,
furthermore they're relatively old and I estimate many of such configs
must have been fixed in the course of time.
As for services escaping their cgroups -- they needn't run as root, do
they? And if you seek a mechanism how to prevent even root from
migrations, there are cgroupnses for that. (BTW what would prevent a
root detaching/disabling these hook progs anyway?)
I think that the cgroup file permissions are sufficient for many use
cases and this BPF hook is too tempting in unnecessary cases (like
masking other issues).
Could you please expand more about some other reasonable use cases not
covered by those?
(BTW I notice there's already a very similar BPF hook in sched_ext's
cgroup_prep_move. It'd be nicer to have only one generic approach to
these checks.)
Regards,
Michal | {
"author": "Michal =?utf-8?Q?Koutn=C3=BD?= <mkoutny@suse.com>",
"date": "Mon, 23 Feb 2026 16:47:11 +0100",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | On Mon, Feb 23, 2026 at 12:12:28PM +0100, Christian Brauner wrote:
I apologize. I didn't realize that adding these as new generic LSM
hooks points had already been proposed and discussed with the LSM
maintainers. I just wanted to make sure that we weren't
unintentionally side-stepping.
Adding these dedicated BPF LSM hooks is OK with me, especially knowing
that I have agreement from you that you'll also be maintaining their
call sites. | {
"author": "Matt Bobrowski <mattbobrowski@google.com>",
"date": "Tue, 24 Feb 2026 00:15:10 +0000",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | On Fri, Feb 20, 2026 at 01:38:29AM +0100, Christian Brauner wrote:
Is the usage of __bpf_hook_start()/__bpf_hook_end() strictly necessary
here? If so, why is that? My understanding was that they're only
needed in situations where public function prototypes don't exist
(e.g., BPF kfuncs). | {
"author": "Matt Bobrowski <mattbobrowski@google.com>",
"date": "Tue, 24 Feb 2026 01:16:01 +0000",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | On Fri, Feb 20, 2026 at 01:38:29AM +0100, Christian Brauner wrote:
I'm wondering how you foresee this hook functioning in a scenario
where the BPF LSM program is attached to this new hook point, although
with its attachment type being set to BPF_LSM_CGROUP instead of
BPF_LSM_MAC? You probably wouldn't want to utilize something like
BPF_LSM_CGROUP for your specific use case, but as things stand
currently I don't believe there's anyhthing preventing you from using
BPF_LSM_CGROUP with a hook like bpf_lsm_namespace_free().
Notably, the BPF_LSM_CGROUP infrastructure is designed to execute BPF
programs based on the cgroup of the currently executing task. There
could be some surprises if the bpf_lsm_namespace_free() hook were to
ever be called from a context (e.g, kworker) other than the one
specified whilst attaching the BPF LSM program with type
BPF_LSM_CGROUP. | {
"author": "Matt Bobrowski <mattbobrowski@google.com>",
"date": "Tue, 24 Feb 2026 13:35:11 +0000",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | On Thu, Feb 19, 2026 at 4:38 PM Christian Brauner <brauner@kernel.org> wrote:
[...]
If we change the hook as
bpf_lsm_namespace_alloc(ns, inum);
We can move it to the beginning of __ns_common_init().
This change allows blocking __ns_common_init() before
it makes any changes to the ns. Is this a better approach?
Thanks,
Song
[...] | {
"author": "Song Liu <song@kernel.org>",
"date": "Tue, 24 Feb 2026 15:04:43 -0800",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | On Tue, Feb 24, 2026 at 03:04:43PM -0800, Song Liu wrote:
I don't think it matters tbh. We have no control when exactly
__ns_common_init() is called. That's up to the containing namespace. We
can't rely on the namespace to have been correctly set up at this time.
My main goal was to have struct ns_common to be fully initialized
already so that direct access to it's field already makes sense.
The containing namespace my already have to rollback a bunch of stuff
anyway. | {
"author": "Christian Brauner <brauner@kernel.org>",
"date": "Fri, 27 Feb 2026 11:28:44 +0100",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | On Tue, Feb 24, 2026 at 01:16:01AM +0000, Matt Bobrowski wrote:
I don't know. I just went by other sites that added bpf specific
functions. Seems like bpf specific functions I'm adding so I used the
hook annotation. If unneeded I happily drop it. I just need someone to
tell whether that's right and I can't infer from your "my understanding
[...]" phrasing whether that's an authoritative statement or an
expression of doubt. | {
"author": "Christian Brauner <brauner@kernel.org>",
"date": "Fri, 27 Feb 2026 11:33:56 +0100",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | On Mon, Feb 23, 2026 at 01:44:23PM +0100, Djalal Harouni wrote:
Yes.
Yes, I have planned that but we will massage that codepath quite a bit
this cycle to deal with some races so I'd rather push this out for this
reason and also...
... I need to think about how exactly we should hook into that. Probably
when we already have assembled the new namespace set but then I want to
pass it to the hook in a way that I can guarantee KF_TRUSTED_ARGS so
callers can use the macros I have to cast from struct ns_common to
actual namespace type.
We will need additional per-ns type hooks in the future as well. Like,
One would very likely want to supervise writes of idmappings to a userns
and so we need to add hooks for that into /proc/<pid>/{g,u}id_map as
well... and setgroups now come to think of it.
An fwiw, I'm replacing pivot_root() this cycle and I expect userspace to
fade it out eventually. It's an insane system call that holds tasklist
lock to walk _all task_ on the system each time you switch the
container's rootfs just to mess with the pwd and root. That creates all
kinds of races and no container setup actually needs to do the pwd/root
replacement.
So it's really unneeded unless you do weird stuff like switching out the
rootfs in init_mnt_ns post early boot. Which is insane and can't work
for a lot of other reasons and the pwd/root rewrite doesn't solve
pinning via fds anyway so really that all needs to be Michael Myers'ed.
Next release MOVE_MOUNT_BENEATH will take over that job by making it
work with locked mounts and the rootfs. | {
"author": "Christian Brauner <brauner@kernel.org>",
"date": "Fri, 27 Feb 2026 12:04:25 +0100",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | On Mon, Feb 23, 2026 at 04:47:11PM +0100, Michal Koutný wrote:
logind has to allow cgroup migrations but for say Docker this shouldn't
be allowed. So calling this misconfiguration is like taking a shortcut
by simply pointing to a different destination. But fine, let's say you
insist on this not being valid.
A bunch of tools that do cgroup migrations don't use cgroup namespaces
and there's no requirement or way to enforce that they do. Plus, there's
no requirement to only do cgroup management via systemd or its APIs.
Frankly, I can't even blame userspace for not having widely adopted
cgroup namespaces. The implementation atop of a single superblock like
cgroupfs is questionable.
But in general the point is that there's no mechanism to enforce cgroup
tree policy currently in a sufficiently flexible manner.
I cannot help but read this as you asking me "What if you're too dumb to
write a security policy that isn't self-defeating?" :)
bpf has security hooks for itself including security_bpf(). First thing
that comes to mind is to have security.bpf.* or trusted.* xattrs on
selected processes like PID 1 that mark it as eligible for modifying BPF
state or BPF LSM programs supervising link/prog detach, update etc and
then designating only PID 1 as handing out those magical xattrs. Can be
as fine-grained as needed and that tells everyone else to go away and do
something else.
There's more fine-grained mechanisms to deal with this. IOW, it's a
solvable problem.
systemd will gain the ability to implement policy to control cgroup tree
modifications in as much details as it needs without having the kernel
in need to be aware of it. This can take various forms by marking only
select processes as being eligible for managing cgroup migrations or
even just locking down specific cgroups.
The policy needs to be flexible so it can be live-updated, switched into
auditing mode, and losened, tightened on-demand as needed.
This feels a bit like a wild goose chase. But fine, I'll look at it.
/me goes off
Ok, let's start with cgroup_can_fork(). The sched ext hook isn't a
generic permission check. It's called way after
cgroup_attach_permissions() and is a per cgroup controller check that is
only called for some cgroup controllers. So effectively useless to pull
up (Notice also, how some controllers like cpuset call additional
security hooks already.).
The same problem applies to writes for cgroup.procs and for subtree
control. The sched ext hook are per cgroup controller not generically
called.
And they happen to be called in cgroup_migrate_execute() which is way
deep in the callchain. When cgroup_attach_permissions() fails it's
effectively free. If migrate_execute() fails it must put/free css sets,
it must splice back task on mg_tasks, it must call cancel_attach()
callbacks, thus it must call the sched-ext cancel callbacks for each
already prepped task, it must uncharge pids for each already prepped
task, it needs to unlock a bunch of stuff.
On top of that this looks like a category mistake imho. The callbacks
are a dac-like permission mechanism whereas the hooks is actual mac
permission checking. I'm not sure lumping this together with
per-cgroup-controller migration preparations will be very clean. I think
it will end up looking rather confusing. But that's best left to you
cgroup maintainers, I think. | {
"author": "Christian Brauner <brauner@kernel.org>",
"date": "Fri, 27 Feb 2026 14:44:27 +0100",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Hey,
I'm in the process of adding "universal truths" bpf lsm programs to
systemd that implement and enforce core system assumptions.
One aspect of this will be advanced namespace management so we can have
things like systemd-nsresourced tightly manage namespaces it allocates
and implement advanced access policies for them. We already do parts of
that but it's rather limited and relies on some workarounds as well
because we don't have the infrastructure for it. We also currently need
to rely on ugly workarounds such as attaching to very arcane tracing
hooks to be notified when namespaces go away.
The second aspect is managing cgroup attaches. This is a core feature
that has been demanded for a long time in systemd. We want to be able to
ensure that some services cannot ever escape their cgroups.
The new hooks are available to bpf lsm programs. Selftests included.
Signed-off-by: Christian Brauner <brauner@kernel.org>
---
Christian Brauner (4):
ns: add bpf hooks
cgroup: add bpf hook for attach
selftests/bpf: add ns hook selftest
selftests/bpf: add cgroup attach selftests
include/linux/bpf_lsm.h | 36 ++
kernel/bpf/bpf_lsm.c | 37 +++
kernel/cgroup/cgroup.c | 18 +-
kernel/nscommon.c | 9 +-
kernel/nsproxy.c | 7 +
.../selftests/bpf/prog_tests/cgroup_attach.c | 362 +++++++++++++++++++++
.../testing/selftests/bpf/prog_tests/ns_sandbox.c | 99 ++++++
.../selftests/bpf/progs/test_cgroup_attach.c | 85 +++++
.../testing/selftests/bpf/progs/test_ns_sandbox.c | 91 ++++++
9 files changed, 736 insertions(+), 8 deletions(-)
---
base-commit: 01582681b1e6881b49d848f1a6e200eace6aac0c
change-id: 20260219-work-bpf-namespace-b5699fad250e
| null | null | null | [PATCH 0/4] bpf: add a few hooks for sandboxing | On Tue, Feb 24, 2026 at 01:35:11PM +0000, Matt Bobrowski wrote:
Oh, I very much would like this to be attachable to cgroups.
But isn't this then a generic problem? What about:
# RCU callbacks
security_cred_free
security_task_free
security_inode_free_security_rcu
security_bpf_prog_free
security_xfrm_policy_free_security
security_msg_queue_free_security
security_shm_free_security
security_sem_free_security
security_audit_rule_free
security_bdev_free_security
security_sk_free_security
# Workqueues
security_bpf_map_free
security_bpf_token_free
security_sb_free_security
security_file_free_security
security_file_release
security_xfrm_state_free_security
ignoring sofirq/hardirq for now.
So the only real problem I can see is that someone wants to do something
from a *_free() hook that isn't actually freeing but actual policy based
on the cgroup of @current? I find that hard to believe tbh. Fwiw,
bpf_lsm_namespace_free() is classified as untrusted because at that
point the outer namespace might already be blown away partially.
Effectively alloc() and free() hooks are mostly notification mechanisms
of creation/destructions. If you want to do actual policy you might have
to defer it until an actual operation is done. | {
"author": "Christian Brauner <brauner@kernel.org>",
"date": "Fri, 27 Feb 2026 15:33:21 +0100",
"is_openbsd": false,
"thread_id": "20260220-work-bpf-namespace-v1-0-866207db7b83@kernel.org.mbox.gz"
} |
lkml_critique | lkml | A disconnect status BIT of USB2 PHY need to be cleared, otherwise
it will fail to work properly during next connection when devices
connect to roothub directly.
Fixes: fe4bc1a08638 ("phy: spacemit: support K1 USB2.0 PHY controller")
Signed-off-by: Yixun Lan <dlan@kernel.org>
---
To: Vinod Koul <vkoul@kernel.org>
To: Neil Armstrong <neil.armstrong@linaro.org>
To: Ze Huang <huang.ze@linux.dev>
Cc: Vladimir Oltean <olteanv@gmail.com>
Cc: Junzhong Pan <panjunzhong@linux.spacemit.com>
Cc: spacemit@lists.linux.dev
Cc: linux-phy@lists.infradead.org
Cc: linux-riscv@lists.infradead.org
Cc: linux-kernel@vger.kernel.org
Change in v3:
- split from v2 as bug fix
- fix alignment to open parenthesis
- http://lore.kernel.org/r/20260216090112.n5jjpui3luqsybb5@skbuf
- Link to v2: https://lore.kernel.org/r/20260214-11-k3-usb2-phy-v2-0-6ed31e031ab4@kernel.org
---
drivers/phy/spacemit/phy-k1-usb2.c | 14 ++++++++++++++
1 file changed, 14 insertions(+)
diff --git a/drivers/phy/spacemit/phy-k1-usb2.c b/drivers/phy/spacemit/phy-k1-usb2.c
index 342061380012..9215d0b223b2 100644
--- a/drivers/phy/spacemit/phy-k1-usb2.c
+++ b/drivers/phy/spacemit/phy-k1-usb2.c
@@ -48,6 +48,9 @@
#define PHY_CLK_HSTXP_EN BIT(3) /* clock hstxp enable */
#define PHY_HSTXP_MODE BIT(4) /* 0: force en_txp to be 1; 1: no force */
+#define PHY_K1_HS_HOST_DISC 0x40
+#define PHY_K1_HS_HOST_DISC_CLR BIT(0)
+
#define PHY_PLL_DIV_CFG 0x98
#define PHY_FDIV_FRACT_8_15 GENMASK(7, 0)
#define PHY_FDIV_FRACT_16_19 GENMASK(11, 8)
@@ -142,9 +145,20 @@ static int spacemit_usb2phy_exit(struct phy *phy)
return 0;
}
+static int spacemit_usb2phy_disconnect(struct phy *phy, int port)
+{
+ struct spacemit_usb2phy *sphy = phy_get_drvdata(phy);
+
+ regmap_update_bits(sphy->regmap_base, PHY_K1_HS_HOST_DISC,
+ PHY_K1_HS_HOST_DISC_CLR, PHY_K1_HS_HOST_DISC_CLR);
+
+ return 0;
+}
+
static const struct phy_ops spacemit_usb2phy_ops = {
.init = spacemit_usb2phy_init,
.exit = spacemit_usb2phy_exit,
+ .disconnect = spacemit_usb2phy_disconnect,
.owner = THIS_MODULE,
};
--
2.52.0
| null | null | null | [PATCH v3] phy: k1-usb: add disconnect function support | On Mon, Feb 16, 2026 at 11:26:53PM +0800, Yixun Lan wrote:
Reviewed-by: Vladimir Oltean <olteanv@gmail.com> | {
"author": "Vladimir Oltean <olteanv@gmail.com>",
"date": "Tue, 17 Feb 2026 00:12:54 +0200",
"is_openbsd": false,
"thread_id": "177220591203.320398.3042297469534840289.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | A disconnect status BIT of USB2 PHY need to be cleared, otherwise
it will fail to work properly during next connection when devices
connect to roothub directly.
Fixes: fe4bc1a08638 ("phy: spacemit: support K1 USB2.0 PHY controller")
Signed-off-by: Yixun Lan <dlan@kernel.org>
---
To: Vinod Koul <vkoul@kernel.org>
To: Neil Armstrong <neil.armstrong@linaro.org>
To: Ze Huang <huang.ze@linux.dev>
Cc: Vladimir Oltean <olteanv@gmail.com>
Cc: Junzhong Pan <panjunzhong@linux.spacemit.com>
Cc: spacemit@lists.linux.dev
Cc: linux-phy@lists.infradead.org
Cc: linux-riscv@lists.infradead.org
Cc: linux-kernel@vger.kernel.org
Change in v3:
- split from v2 as bug fix
- fix alignment to open parenthesis
- http://lore.kernel.org/r/20260216090112.n5jjpui3luqsybb5@skbuf
- Link to v2: https://lore.kernel.org/r/20260214-11-k3-usb2-phy-v2-0-6ed31e031ab4@kernel.org
---
drivers/phy/spacemit/phy-k1-usb2.c | 14 ++++++++++++++
1 file changed, 14 insertions(+)
diff --git a/drivers/phy/spacemit/phy-k1-usb2.c b/drivers/phy/spacemit/phy-k1-usb2.c
index 342061380012..9215d0b223b2 100644
--- a/drivers/phy/spacemit/phy-k1-usb2.c
+++ b/drivers/phy/spacemit/phy-k1-usb2.c
@@ -48,6 +48,9 @@
#define PHY_CLK_HSTXP_EN BIT(3) /* clock hstxp enable */
#define PHY_HSTXP_MODE BIT(4) /* 0: force en_txp to be 1; 1: no force */
+#define PHY_K1_HS_HOST_DISC 0x40
+#define PHY_K1_HS_HOST_DISC_CLR BIT(0)
+
#define PHY_PLL_DIV_CFG 0x98
#define PHY_FDIV_FRACT_8_15 GENMASK(7, 0)
#define PHY_FDIV_FRACT_16_19 GENMASK(11, 8)
@@ -142,9 +145,20 @@ static int spacemit_usb2phy_exit(struct phy *phy)
return 0;
}
+static int spacemit_usb2phy_disconnect(struct phy *phy, int port)
+{
+ struct spacemit_usb2phy *sphy = phy_get_drvdata(phy);
+
+ regmap_update_bits(sphy->regmap_base, PHY_K1_HS_HOST_DISC,
+ PHY_K1_HS_HOST_DISC_CLR, PHY_K1_HS_HOST_DISC_CLR);
+
+ return 0;
+}
+
static const struct phy_ops spacemit_usb2phy_ops = {
.init = spacemit_usb2phy_init,
.exit = spacemit_usb2phy_exit,
+ .disconnect = spacemit_usb2phy_disconnect,
.owner = THIS_MODULE,
};
--
2.52.0
| null | null | null | [PATCH v3] phy: k1-usb: add disconnect function support | On Mon, 16 Feb 2026 23:26:53 +0800, Yixun Lan wrote:
Applied, thanks!
[1/1] phy: k1-usb: add disconnect function support
commit: f0cf0a882a02dcf28547f32264f6fd37e9a7b147
Best regards,
--
~Vinod | {
"author": "Vinod Koul <vkoul@kernel.org>",
"date": "Fri, 27 Feb 2026 20:55:12 +0530",
"is_openbsd": false,
"thread_id": "177220591203.320398.3042297469534840289.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Convert various legacy .txt bindings for Microchip (formerly Atmel) AT91/SAMA
family system peripherals to proper YAML schemas. This includes:
- CHIPID (SoC ID register block)
- PIT (Period Interval Timer, old style)
- PIT64B (64-bit Period Interval Timer, newer parts)
- ST (System Timer, including watchdog subnode)
- RAMC/SDRAMC/DDRAMC/UDDRC (SDRAM/DDR memory controller
Signed-off-by: Akhila YS <akhilayalmati@gmail.com>
---
Changes in v3:
- Change email for maintainers.
- atmel,at91rm9200-st: redefine watchdog node as a pattern property.
- Remove corresponding binding node from txt document for every yaml patch.
- Link to v2: https://lore.kernel.org/r/20260224-arm-microchip-v2-0-8bedacd2cdcb@gmail.com
Changes in v2:
- Change email for maintainers.
- microchip,sam9x60-pit64b: modify compatible and clock-names in properties.
- Link to v1: https://lore.kernel.org/r/20260217-arm-microchip-v1-0-ae5d907e10e3@gmail.com
---
Akhila YS (5):
dt-bindings: arm: microchip,sama7g5-chipid : convert to DT schema
dt-bindings: arm: atmel,at91sam9260-pit: convert to DT schema
dt-bindings: arm: microchip,sam9x60-pit64b : convert to DT schema
dt-bindings: arm: atmel,at91rm9200-st: convert to DT schema
dt-bindings: arm: atmel,at91rm9200-sdramc: convert to DT schema
.../bindings/arm/atmel,at91rm9200-sdramc.yaml | 67 +++++++++++++++++++++
.../bindings/arm/atmel,at91rm9200-st.yaml | 69 ++++++++++++++++++++++
.../bindings/arm/atmel,at91sam9260-pit.yaml | 49 +++++++++++++++
.../devicetree/bindings/arm/atmel-sysregs.txt | 48 ---------------
.../bindings/arm/microchip,sam9x60-pit64b.yaml | 68 +++++++++++++++++++++
.../bindings/arm/microchip,sama7g5-chipid.yaml | 41 +++++++++++++
6 files changed, 294 insertions(+), 48 deletions(-)
---
base-commit: ca3a02fda4da8e2c1cb6baee5d72352e9e2cfaea
change-id: 20260128-arm-microchip-c0c0515024e6
Best regards,
--
Akhila YS <akhilayalmati@gmail.com>
| null | null | null | [PATCH v3 0/5] dt-bindings: Microchip/Atmel AT91/SAMA system
peripherals: convert to YAML | Convert Atmel system registers binding to YAML format.
Signed-off-by: Akhila YS <akhilayalmati@gmail.com>
---
.../devicetree/bindings/arm/atmel-sysregs.txt | 5 ---
.../bindings/arm/microchip,sama7g5-chipid.yaml | 41 ++++++++++++++++++++++
2 files changed, 41 insertions(+), 5 deletions(-)
diff --git a/Documentation/devicetree/bindings/arm/atmel-sysregs.txt b/Documentation/devicetree/bindings/arm/atmel-sysregs.txt
index 5ce54f9befe6..4ee18112586d 100644
--- a/Documentation/devicetree/bindings/arm/atmel-sysregs.txt
+++ b/Documentation/devicetree/bindings/arm/atmel-sysregs.txt
@@ -1,10 +1,5 @@
Atmel system registers
-Chipid required properties:
-- compatible: Should be "atmel,sama5d2-chipid" or "microchip,sama7g5-chipid"
- "microchip,sama7d65-chipid"
-- reg : Should contain registers location and length
-
PIT Timer required properties:
- compatible: Should be "atmel,at91sam9260-pit"
- reg: Should contain registers location and length
diff --git a/Documentation/devicetree/bindings/arm/microchip,sama7g5-chipid.yaml b/Documentation/devicetree/bindings/arm/microchip,sama7g5-chipid.yaml
new file mode 100644
index 000000000000..4fdb068be929
--- /dev/null
+++ b/Documentation/devicetree/bindings/arm/microchip,sama7g5-chipid.yaml
@@ -0,0 +1,41 @@
+# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/arm/microchip,sama7g5-chipid.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Atmel/Microchip RAMC SDRAM/DDR Controller
+
+maintainers:
+ - Nicolas Ferre <nicolas.ferre@microchip.com>
+ - Claudiu Beznea <claudiu.beznea@tuxon.dev>
+
+description:
+ This binding describes the Atmel/Microchip Chip ID register block used
+ for SoC identification and revision information. It requires compatible
+ strings matching specific SoC families and a reg property defining the
+ register address and size.
+
+properties:
+ compatible:
+ enum:
+ - atmel,sama5d2-chipid
+ - microchip,sama7g5-chipid
+ - microchip,sama7d65-chipid
+
+ reg:
+ maxItems: 1
+
+required:
+ - compatible
+ - reg
+
+unevaluatedProperties: false
+
+examples:
+ - |
+ chipid@fc069000 {
+ compatible = "atmel,sama5d2-chipid";
+ reg = <0xfc069000 0x8>;
+ };
+...
--
2.43.0 | {
"author": "Akhila YS <akhilayalmati@gmail.com>",
"date": "Thu, 26 Feb 2026 16:13:33 +0000",
"is_openbsd": false,
"thread_id": "20260226-arm-microchip-v3-0-0bda15abd922@gmail.com.mbox.gz"
} |
lkml_critique | lkml | Convert various legacy .txt bindings for Microchip (formerly Atmel) AT91/SAMA
family system peripherals to proper YAML schemas. This includes:
- CHIPID (SoC ID register block)
- PIT (Period Interval Timer, old style)
- PIT64B (64-bit Period Interval Timer, newer parts)
- ST (System Timer, including watchdog subnode)
- RAMC/SDRAMC/DDRAMC/UDDRC (SDRAM/DDR memory controller
Signed-off-by: Akhila YS <akhilayalmati@gmail.com>
---
Changes in v3:
- Change email for maintainers.
- atmel,at91rm9200-st: redefine watchdog node as a pattern property.
- Remove corresponding binding node from txt document for every yaml patch.
- Link to v2: https://lore.kernel.org/r/20260224-arm-microchip-v2-0-8bedacd2cdcb@gmail.com
Changes in v2:
- Change email for maintainers.
- microchip,sam9x60-pit64b: modify compatible and clock-names in properties.
- Link to v1: https://lore.kernel.org/r/20260217-arm-microchip-v1-0-ae5d907e10e3@gmail.com
---
Akhila YS (5):
dt-bindings: arm: microchip,sama7g5-chipid : convert to DT schema
dt-bindings: arm: atmel,at91sam9260-pit: convert to DT schema
dt-bindings: arm: microchip,sam9x60-pit64b : convert to DT schema
dt-bindings: arm: atmel,at91rm9200-st: convert to DT schema
dt-bindings: arm: atmel,at91rm9200-sdramc: convert to DT schema
.../bindings/arm/atmel,at91rm9200-sdramc.yaml | 67 +++++++++++++++++++++
.../bindings/arm/atmel,at91rm9200-st.yaml | 69 ++++++++++++++++++++++
.../bindings/arm/atmel,at91sam9260-pit.yaml | 49 +++++++++++++++
.../devicetree/bindings/arm/atmel-sysregs.txt | 48 ---------------
.../bindings/arm/microchip,sam9x60-pit64b.yaml | 68 +++++++++++++++++++++
.../bindings/arm/microchip,sama7g5-chipid.yaml | 41 +++++++++++++
6 files changed, 294 insertions(+), 48 deletions(-)
---
base-commit: ca3a02fda4da8e2c1cb6baee5d72352e9e2cfaea
change-id: 20260128-arm-microchip-c0c0515024e6
Best regards,
--
Akhila YS <akhilayalmati@gmail.com>
| null | null | null | [PATCH v3 0/5] dt-bindings: Microchip/Atmel AT91/SAMA system
peripherals: convert to YAML | Convert Atmel Periodic interval timer (PIT) binding to YAML format.
Signed-off-by: Akhila YS <akhilayalmati@gmail.com>
---
.../bindings/arm/atmel,at91sam9260-pit.yaml | 49 ++++++++++++++++++++++
.../devicetree/bindings/arm/atmel-sysregs.txt | 6 ---
2 files changed, 49 insertions(+), 6 deletions(-)
diff --git a/Documentation/devicetree/bindings/arm/atmel,at91sam9260-pit.yaml b/Documentation/devicetree/bindings/arm/atmel,at91sam9260-pit.yaml
new file mode 100644
index 000000000000..d1bdc4a4f9e0
--- /dev/null
+++ b/Documentation/devicetree/bindings/arm/atmel,at91sam9260-pit.yaml
@@ -0,0 +1,49 @@
+# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/arm/atmel,at91sam9260-pit.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Atmel AT91SAM9260 Periodic Interval Timer (PIT)
+
+maintainers:
+ - Nicolas Ferre <nicolas.ferre@microchip.com>
+ - Claudiu Beznea <claudiu.beznea@tuxon.dev>
+
+description:
+ The Periodic Interval Timer (PIT) is part of the System Controller of
+ various Microchip 32-bit ARM-based SoCs (formerly Atmel AT91 series).
+ It is a simple down-counter timer used mainly as the kernel tick source.
+ The PIT is clocked from the slow clock and shares a single IRQ line with
+ other System Controller peripherals.
+
+properties:
+ compatible:
+ const: atmel,at91sam9260-pit
+
+ reg:
+ maxItems: 1
+
+ interrupts:
+ maxItems: 1
+
+ clocks:
+ maxItems: 1
+
+required:
+ - compatible
+ - reg
+ - interrupts
+
+unevaluatedProperties: false
+
+examples:
+ - |
+ #include <dt-bindings/interrupt-controller/irq.h>
+ timer@fffffd30 {
+ compatible = "atmel,at91sam9260-pit";
+ reg = <0xfffffd30 0x10>;
+ interrupts = <1 IRQ_TYPE_LEVEL_HIGH>;
+ clocks = <&clk32k>;
+ };
+...
diff --git a/Documentation/devicetree/bindings/arm/atmel-sysregs.txt b/Documentation/devicetree/bindings/arm/atmel-sysregs.txt
index 4ee18112586d..70059f66f2b4 100644
--- a/Documentation/devicetree/bindings/arm/atmel-sysregs.txt
+++ b/Documentation/devicetree/bindings/arm/atmel-sysregs.txt
@@ -1,11 +1,5 @@
Atmel system registers
-PIT Timer required properties:
-- compatible: Should be "atmel,at91sam9260-pit"
-- reg: Should contain registers location and length
-- interrupts: Should contain interrupt for the PIT which is the IRQ line
- shared across all System Controller members.
-
PIT64B Timer required properties:
- compatible: Should be "microchip,sam9x60-pit64b" or
"microchip,sam9x7-pit64b", "microchip,sam9x60-pit64b"
--
2.43.0 | {
"author": "Akhila YS <akhilayalmati@gmail.com>",
"date": "Thu, 26 Feb 2026 16:13:34 +0000",
"is_openbsd": false,
"thread_id": "20260226-arm-microchip-v3-0-0bda15abd922@gmail.com.mbox.gz"
} |
lkml_critique | lkml | Convert various legacy .txt bindings for Microchip (formerly Atmel) AT91/SAMA
family system peripherals to proper YAML schemas. This includes:
- CHIPID (SoC ID register block)
- PIT (Period Interval Timer, old style)
- PIT64B (64-bit Period Interval Timer, newer parts)
- ST (System Timer, including watchdog subnode)
- RAMC/SDRAMC/DDRAMC/UDDRC (SDRAM/DDR memory controller
Signed-off-by: Akhila YS <akhilayalmati@gmail.com>
---
Changes in v3:
- Change email for maintainers.
- atmel,at91rm9200-st: redefine watchdog node as a pattern property.
- Remove corresponding binding node from txt document for every yaml patch.
- Link to v2: https://lore.kernel.org/r/20260224-arm-microchip-v2-0-8bedacd2cdcb@gmail.com
Changes in v2:
- Change email for maintainers.
- microchip,sam9x60-pit64b: modify compatible and clock-names in properties.
- Link to v1: https://lore.kernel.org/r/20260217-arm-microchip-v1-0-ae5d907e10e3@gmail.com
---
Akhila YS (5):
dt-bindings: arm: microchip,sama7g5-chipid : convert to DT schema
dt-bindings: arm: atmel,at91sam9260-pit: convert to DT schema
dt-bindings: arm: microchip,sam9x60-pit64b : convert to DT schema
dt-bindings: arm: atmel,at91rm9200-st: convert to DT schema
dt-bindings: arm: atmel,at91rm9200-sdramc: convert to DT schema
.../bindings/arm/atmel,at91rm9200-sdramc.yaml | 67 +++++++++++++++++++++
.../bindings/arm/atmel,at91rm9200-st.yaml | 69 ++++++++++++++++++++++
.../bindings/arm/atmel,at91sam9260-pit.yaml | 49 +++++++++++++++
.../devicetree/bindings/arm/atmel-sysregs.txt | 48 ---------------
.../bindings/arm/microchip,sam9x60-pit64b.yaml | 68 +++++++++++++++++++++
.../bindings/arm/microchip,sama7g5-chipid.yaml | 41 +++++++++++++
6 files changed, 294 insertions(+), 48 deletions(-)
---
base-commit: ca3a02fda4da8e2c1cb6baee5d72352e9e2cfaea
change-id: 20260128-arm-microchip-c0c0515024e6
Best regards,
--
Akhila YS <akhilayalmati@gmail.com>
| null | null | null | [PATCH v3 0/5] dt-bindings: Microchip/Atmel AT91/SAMA system
peripherals: convert to YAML | Convert Atmel Periodic interval timer of 64bit (PIT64b) binding to YAML
format.
Changes during conversion:
- Add missing compatible "microchip,sama7g5-pit64b" along with a fallback
compatible "microchip,sam9x60-pit64b".
Signed-off-by: Akhila YS <akhilayalmati@gmail.com>
---
.../devicetree/bindings/arm/atmel-sysregs.txt | 8 ---
.../bindings/arm/microchip,sam9x60-pit64b.yaml | 68 ++++++++++++++++++++++
2 files changed, 68 insertions(+), 8 deletions(-)
diff --git a/Documentation/devicetree/bindings/arm/atmel-sysregs.txt b/Documentation/devicetree/bindings/arm/atmel-sysregs.txt
index 70059f66f2b4..d0561f7f465c 100644
--- a/Documentation/devicetree/bindings/arm/atmel-sysregs.txt
+++ b/Documentation/devicetree/bindings/arm/atmel-sysregs.txt
@@ -1,13 +1,5 @@
Atmel system registers
-PIT64B Timer required properties:
-- compatible: Should be "microchip,sam9x60-pit64b" or
- "microchip,sam9x7-pit64b", "microchip,sam9x60-pit64b"
- "microchip,sama7d65-pit64b", "microchip,sam9x60-pit64b"
-- reg: Should contain registers location and length
-- interrupts: Should contain interrupt for PIT64B timer
-- clocks: Should contain the available clock sources for PIT64B timer.
-
System Timer (ST) required properties:
- compatible: Should be "atmel,at91rm9200-st", "syscon", "simple-mfd"
- reg: Should contain registers location and length
diff --git a/Documentation/devicetree/bindings/arm/microchip,sam9x60-pit64b.yaml b/Documentation/devicetree/bindings/arm/microchip,sam9x60-pit64b.yaml
new file mode 100644
index 000000000000..f00ac7e858d9
--- /dev/null
+++ b/Documentation/devicetree/bindings/arm/microchip,sam9x60-pit64b.yaml
@@ -0,0 +1,68 @@
+# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/arm/microchip,sam9x60-pit64b.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Microchip PIT64B 64-bit Periodic Interval Timer
+
+maintainers:
+ - Nicolas Ferre <nicolas.ferre@microchip.com>
+ - Claudiu Beznea <claudiu.beznea@tuxon.dev>
+
+description:
+ The Microchip PIT64B is a 64-bit periodic interval timer used in
+ several modern Microchip ARM SoCs including SAM9X60, SAM9X7 and
+ SAMA7D65 families. It provides extended timing range, flexible
+ clock selection and supports both periodic and one-shot interrupt
+ generation modes.
+
+properties:
+ compatible:
+ oneOf:
+ - const: microchip,sam9x60-pit64b
+ - items:
+ - enum:
+ - microchip,sama7d65-pit64b
+ - microchip,sama7g5-pit64b
+ - microchip,sam9x7-pit64b
+ - const: microchip,sam9x60-pit64b
+
+ reg:
+ maxItems: 1
+
+ interrupts:
+ maxItems: 1
+
+ clocks:
+ minItems: 1
+ maxItems: 2
+
+ clock-names:
+ minItems: 1
+ maxItems: 2
+ items:
+ enum:
+ - pclk
+ - gclk
+
+required:
+ - compatible
+ - reg
+ - interrupts
+ - clocks
+
+unevaluatedProperties: false
+
+examples:
+ - |
+ #include <dt-bindings/interrupt-controller/irq.h>
+ #include <dt-bindings/clock/at91.h>
+ timer@f0028000 {
+ compatible = "microchip,sama7g5-pit64b", "microchip,sam9x60-pit64b";
+ reg = <0xf0028000 0x100>;
+ interrupts = <37 IRQ_TYPE_LEVEL_HIGH 7>;
+ clocks = <&pmc PMC_TYPE_PERIPHERAL 37>, <&pmc PMC_TYPE_GCK 37>;
+ clock-names = "pclk", "gclk";
+ };
+...
--
2.43.0 | {
"author": "Akhila YS <akhilayalmati@gmail.com>",
"date": "Thu, 26 Feb 2026 16:13:35 +0000",
"is_openbsd": false,
"thread_id": "20260226-arm-microchip-v3-0-0bda15abd922@gmail.com.mbox.gz"
} |
lkml_critique | lkml | Convert various legacy .txt bindings for Microchip (formerly Atmel) AT91/SAMA
family system peripherals to proper YAML schemas. This includes:
- CHIPID (SoC ID register block)
- PIT (Period Interval Timer, old style)
- PIT64B (64-bit Period Interval Timer, newer parts)
- ST (System Timer, including watchdog subnode)
- RAMC/SDRAMC/DDRAMC/UDDRC (SDRAM/DDR memory controller
Signed-off-by: Akhila YS <akhilayalmati@gmail.com>
---
Changes in v3:
- Change email for maintainers.
- atmel,at91rm9200-st: redefine watchdog node as a pattern property.
- Remove corresponding binding node from txt document for every yaml patch.
- Link to v2: https://lore.kernel.org/r/20260224-arm-microchip-v2-0-8bedacd2cdcb@gmail.com
Changes in v2:
- Change email for maintainers.
- microchip,sam9x60-pit64b: modify compatible and clock-names in properties.
- Link to v1: https://lore.kernel.org/r/20260217-arm-microchip-v1-0-ae5d907e10e3@gmail.com
---
Akhila YS (5):
dt-bindings: arm: microchip,sama7g5-chipid : convert to DT schema
dt-bindings: arm: atmel,at91sam9260-pit: convert to DT schema
dt-bindings: arm: microchip,sam9x60-pit64b : convert to DT schema
dt-bindings: arm: atmel,at91rm9200-st: convert to DT schema
dt-bindings: arm: atmel,at91rm9200-sdramc: convert to DT schema
.../bindings/arm/atmel,at91rm9200-sdramc.yaml | 67 +++++++++++++++++++++
.../bindings/arm/atmel,at91rm9200-st.yaml | 69 ++++++++++++++++++++++
.../bindings/arm/atmel,at91sam9260-pit.yaml | 49 +++++++++++++++
.../devicetree/bindings/arm/atmel-sysregs.txt | 48 ---------------
.../bindings/arm/microchip,sam9x60-pit64b.yaml | 68 +++++++++++++++++++++
.../bindings/arm/microchip,sama7g5-chipid.yaml | 41 +++++++++++++
6 files changed, 294 insertions(+), 48 deletions(-)
---
base-commit: ca3a02fda4da8e2c1cb6baee5d72352e9e2cfaea
change-id: 20260128-arm-microchip-c0c0515024e6
Best regards,
--
Akhila YS <akhilayalmati@gmail.com>
| null | null | null | [PATCH v3 0/5] dt-bindings: Microchip/Atmel AT91/SAMA system
peripherals: convert to YAML | Convert System Timer binding to YAML format.
Changes during conversion:
- Add "#address-cells" and "#size-cells" to the properties and required as
watchdog is defined as a child node to the timer parent node.
- Define watchdog as a pattern property along with unit address in
examples.
Signed-off-by: Akhila YS <akhilayalmati@gmail.com>
---
.../bindings/arm/atmel,at91rm9200-st.yaml | 69 ++++++++++++++++++++++
.../devicetree/bindings/arm/atmel-sysregs.txt | 9 ---
2 files changed, 69 insertions(+), 9 deletions(-)
diff --git a/Documentation/devicetree/bindings/arm/atmel,at91rm9200-st.yaml b/Documentation/devicetree/bindings/arm/atmel,at91rm9200-st.yaml
new file mode 100644
index 000000000000..3f6a934a2a69
--- /dev/null
+++ b/Documentation/devicetree/bindings/arm/atmel,at91rm9200-st.yaml
@@ -0,0 +1,69 @@
+# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/arm/atmel,at91rm9200-st.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Atmel System Timer
+
+maintainers:
+ - Nicolas Ferre <nicolas.ferre@microchip.com>
+ - Claudiu Beznea <claudiu.beznea@tuxon.dev>
+
+description:
+ The System Timer (ST) module in AT91RM9200 provides periodic tick and
+ alarm capabilities. It is exposed as a simple multi-function device
+ (simple-mfd + syscon) because it shares its register space and interrupt
+ with other System Controller blocks.
+
+properties:
+ compatible:
+ items:
+ - const: atmel,at91rm9200-st
+ - const: syscon
+ - const: simple-mfd
+
+ reg:
+ maxItems: 1
+
+ interrupts:
+ maxItems: 1
+
+ clocks:
+ maxItems: 1
+
+ "#address-cells":
+ const: 1
+
+ "#size-cells":
+ const: 1
+
+patternProperties:
+ "^watchdog@[0-9a-f]+$":
+ $ref: /schemas/watchdog/atmel,at91rm9200-wdt.yaml#
+
+required:
+ - compatible
+ - reg
+ - interrupts
+ - clocks
+
+unevaluatedProperties: false
+
+examples:
+ - |
+ #include <dt-bindings/interrupt-controller/irq.h>
+ timer@fffffd00 {
+ compatible = "atmel,at91rm9200-st", "syscon", "simple-mfd";
+ reg = <0xfffffd00 0x100>;
+ interrupts = <1 IRQ_TYPE_LEVEL_HIGH 7>;
+ clocks = <&slow_xtal>;
+ #address-cells = <1>;
+ #size-cells = <1>;
+
+ watchdog@fffffd40 {
+ compatible = "atmel,at91rm9200-wdt";
+ reg = <0xfffffd40 0x40>;
+ };
+ };
+...
diff --git a/Documentation/devicetree/bindings/arm/atmel-sysregs.txt b/Documentation/devicetree/bindings/arm/atmel-sysregs.txt
index d0561f7f465c..14642384bc87 100644
--- a/Documentation/devicetree/bindings/arm/atmel-sysregs.txt
+++ b/Documentation/devicetree/bindings/arm/atmel-sysregs.txt
@@ -1,14 +1,5 @@
Atmel system registers
-System Timer (ST) required properties:
-- compatible: Should be "atmel,at91rm9200-st", "syscon", "simple-mfd"
-- reg: Should contain registers location and length
-- interrupts: Should contain interrupt for the ST which is the IRQ line
- shared across all System Controller members.
-- clocks: phandle to input clock.
-Its subnodes can be:
-- watchdog: compatible should be "atmel,at91rm9200-wdt"
-
RAMC SDRAM/DDR Controller required properties:
- compatible: Should be "atmel,at91rm9200-sdramc", "syscon" or
"atmel,at91sam9260-sdramc" or
--
2.43.0 | {
"author": "Akhila YS <akhilayalmati@gmail.com>",
"date": "Thu, 26 Feb 2026 16:13:36 +0000",
"is_openbsd": false,
"thread_id": "20260226-arm-microchip-v3-0-0bda15abd922@gmail.com.mbox.gz"
} |
lkml_critique | lkml | Convert various legacy .txt bindings for Microchip (formerly Atmel) AT91/SAMA
family system peripherals to proper YAML schemas. This includes:
- CHIPID (SoC ID register block)
- PIT (Period Interval Timer, old style)
- PIT64B (64-bit Period Interval Timer, newer parts)
- ST (System Timer, including watchdog subnode)
- RAMC/SDRAMC/DDRAMC/UDDRC (SDRAM/DDR memory controller
Signed-off-by: Akhila YS <akhilayalmati@gmail.com>
---
Changes in v3:
- Change email for maintainers.
- atmel,at91rm9200-st: redefine watchdog node as a pattern property.
- Remove corresponding binding node from txt document for every yaml patch.
- Link to v2: https://lore.kernel.org/r/20260224-arm-microchip-v2-0-8bedacd2cdcb@gmail.com
Changes in v2:
- Change email for maintainers.
- microchip,sam9x60-pit64b: modify compatible and clock-names in properties.
- Link to v1: https://lore.kernel.org/r/20260217-arm-microchip-v1-0-ae5d907e10e3@gmail.com
---
Akhila YS (5):
dt-bindings: arm: microchip,sama7g5-chipid : convert to DT schema
dt-bindings: arm: atmel,at91sam9260-pit: convert to DT schema
dt-bindings: arm: microchip,sam9x60-pit64b : convert to DT schema
dt-bindings: arm: atmel,at91rm9200-st: convert to DT schema
dt-bindings: arm: atmel,at91rm9200-sdramc: convert to DT schema
.../bindings/arm/atmel,at91rm9200-sdramc.yaml | 67 +++++++++++++++++++++
.../bindings/arm/atmel,at91rm9200-st.yaml | 69 ++++++++++++++++++++++
.../bindings/arm/atmel,at91sam9260-pit.yaml | 49 +++++++++++++++
.../devicetree/bindings/arm/atmel-sysregs.txt | 48 ---------------
.../bindings/arm/microchip,sam9x60-pit64b.yaml | 68 +++++++++++++++++++++
.../bindings/arm/microchip,sama7g5-chipid.yaml | 41 +++++++++++++
6 files changed, 294 insertions(+), 48 deletions(-)
---
base-commit: ca3a02fda4da8e2c1cb6baee5d72352e9e2cfaea
change-id: 20260128-arm-microchip-c0c0515024e6
Best regards,
--
Akhila YS <akhilayalmati@gmail.com>
| null | null | null | [PATCH v3 0/5] dt-bindings: Microchip/Atmel AT91/SAMA system
peripherals: convert to YAML | Convert RAMC SDRAM/DDR controller binding to YAML format.
Signed-off-by: Akhila YS <akhilayalmati@gmail.com>
---
.../bindings/arm/atmel,at91rm9200-sdramc.yaml | 67 ++++++++++++++++++++++
.../devicetree/bindings/arm/atmel-sysregs.txt | 20 -------
2 files changed, 67 insertions(+), 20 deletions(-)
diff --git a/Documentation/devicetree/bindings/arm/atmel,at91rm9200-sdramc.yaml b/Documentation/devicetree/bindings/arm/atmel,at91rm9200-sdramc.yaml
new file mode 100644
index 000000000000..1516fc8e09e1
--- /dev/null
+++ b/Documentation/devicetree/bindings/arm/atmel,at91rm9200-sdramc.yaml
@@ -0,0 +1,67 @@
+# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/arm/atmel,at91rm9200-sdramc.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Microchip (Atmel) SDRAM / DDR Controller (RAMC / DDRAMC / UDDRC)
+
+maintainers:
+ - Nicolas Ferre <nicolas.ferre@microchip.com>
+ - Claudiu Beznea <claudiu.beznea@tuxon.dev>
+
+description:
+ The SDRAM/DDR Controller (often called RAMC or DDRAMC) in various
+ Atmel/Microchip ARM9 and Cortex-A5/A7 SoCs manages external
+ SDRAM / DDR memory. It is typically exposed as a syscon node for
+ register access from other drivers (e.g. for initialization or mode
+ configuration). No interrupts or clocks are usually required in the
+ binding.
+
+properties:
+ compatible:
+ oneOf:
+ - items:
+ - const: atmel,at91rm9200-sdramc
+ - const: syscon
+ - items:
+ - const: microchip,sama7d65-uddrc
+ - const: microchip,sama7g5-uddrc
+ - items:
+ enum:
+ - atmel,at91sam9260-sdramc
+ - atmel,at91sam9g45-ddramc
+ - atmel,sama5d3-ddramc
+ - microchip,sam9x60-ddramc
+ - microchip,sam9x7-ddramc
+ - microchip,sama7g5-uddrc
+
+ reg:
+ maxItems: 1
+
+ clocks:
+ minItems: 1
+ maxItems: 2
+
+ clock-names:
+ minItems: 1
+ items:
+ - const: ddrck
+ - const: mpddr
+
+required:
+ - compatible
+ - reg
+
+unevaluatedProperties: false
+
+examples:
+ - |
+ #include <dt-bindings/clock/at91.h>
+ ramc@ffffe400 {
+ compatible = "atmel,at91sam9g45-ddramc";
+ reg = <0xffffe400 0x200>;
+ clocks = <&pmc PMC_TYPE_SYSTEM 2>;
+ clock-names = "ddrck";
+ };
+...
diff --git a/Documentation/devicetree/bindings/arm/atmel-sysregs.txt b/Documentation/devicetree/bindings/arm/atmel-sysregs.txt
deleted file mode 100644
index 14642384bc87..000000000000
--- a/Documentation/devicetree/bindings/arm/atmel-sysregs.txt
+++ /dev/null
@@ -1,20 +0,0 @@
-Atmel system registers
-
-RAMC SDRAM/DDR Controller required properties:
-- compatible: Should be "atmel,at91rm9200-sdramc", "syscon" or
- "atmel,at91sam9260-sdramc" or
- "atmel,at91sam9g45-ddramc" or
- "atmel,sama5d3-ddramc" or
- "microchip,sam9x60-ddramc" or
- "microchip,sama7g5-uddrc" or
- "microchip,sama7d65-uddrc", "microchip,sama7g5-uddrc" or
- "microchip,sam9x7-ddramc", "atmel,sama5d3-ddramc".
-- reg: Should contain registers location and length
-
-Examples:
-
- ramc0: ramc@ffffe800 {
- compatible = "atmel,at91sam9g45-ddramc";
- reg = <0xffffe800 0x200>;
- };
-
--
2.43.0 | {
"author": "Akhila YS <akhilayalmati@gmail.com>",
"date": "Thu, 26 Feb 2026 16:13:37 +0000",
"is_openbsd": false,
"thread_id": "20260226-arm-microchip-v3-0-0bda15abd922@gmail.com.mbox.gz"
} |
lkml_critique | lkml | Convert various legacy .txt bindings for Microchip (formerly Atmel) AT91/SAMA
family system peripherals to proper YAML schemas. This includes:
- CHIPID (SoC ID register block)
- PIT (Period Interval Timer, old style)
- PIT64B (64-bit Period Interval Timer, newer parts)
- ST (System Timer, including watchdog subnode)
- RAMC/SDRAMC/DDRAMC/UDDRC (SDRAM/DDR memory controller
Signed-off-by: Akhila YS <akhilayalmati@gmail.com>
---
Changes in v3:
- Change email for maintainers.
- atmel,at91rm9200-st: redefine watchdog node as a pattern property.
- Remove corresponding binding node from txt document for every yaml patch.
- Link to v2: https://lore.kernel.org/r/20260224-arm-microchip-v2-0-8bedacd2cdcb@gmail.com
Changes in v2:
- Change email for maintainers.
- microchip,sam9x60-pit64b: modify compatible and clock-names in properties.
- Link to v1: https://lore.kernel.org/r/20260217-arm-microchip-v1-0-ae5d907e10e3@gmail.com
---
Akhila YS (5):
dt-bindings: arm: microchip,sama7g5-chipid : convert to DT schema
dt-bindings: arm: atmel,at91sam9260-pit: convert to DT schema
dt-bindings: arm: microchip,sam9x60-pit64b : convert to DT schema
dt-bindings: arm: atmel,at91rm9200-st: convert to DT schema
dt-bindings: arm: atmel,at91rm9200-sdramc: convert to DT schema
.../bindings/arm/atmel,at91rm9200-sdramc.yaml | 67 +++++++++++++++++++++
.../bindings/arm/atmel,at91rm9200-st.yaml | 69 ++++++++++++++++++++++
.../bindings/arm/atmel,at91sam9260-pit.yaml | 49 +++++++++++++++
.../devicetree/bindings/arm/atmel-sysregs.txt | 48 ---------------
.../bindings/arm/microchip,sam9x60-pit64b.yaml | 68 +++++++++++++++++++++
.../bindings/arm/microchip,sama7g5-chipid.yaml | 41 +++++++++++++
6 files changed, 294 insertions(+), 48 deletions(-)
---
base-commit: ca3a02fda4da8e2c1cb6baee5d72352e9e2cfaea
change-id: 20260128-arm-microchip-c0c0515024e6
Best regards,
--
Akhila YS <akhilayalmati@gmail.com>
| null | null | null | [PATCH v3 0/5] dt-bindings: Microchip/Atmel AT91/SAMA system
peripherals: convert to YAML | On Thu, Feb 26, 2026 at 04:13:37PM +0000, Akhila YS wrote:
Whoops, sorry for not noticing this earlier, but an items list with one
entry can be reduced to that one entry. For you here that means that
"- items enum:" becomes "- enum:". | {
"author": "Conor Dooley <conor@kernel.org>",
"date": "Thu, 26 Feb 2026 18:12:19 +0000",
"is_openbsd": false,
"thread_id": "20260226-arm-microchip-v3-0-0bda15abd922@gmail.com.mbox.gz"
} |
lkml_critique | lkml | Convert various legacy .txt bindings for Microchip (formerly Atmel) AT91/SAMA
family system peripherals to proper YAML schemas. This includes:
- CHIPID (SoC ID register block)
- PIT (Period Interval Timer, old style)
- PIT64B (64-bit Period Interval Timer, newer parts)
- ST (System Timer, including watchdog subnode)
- RAMC/SDRAMC/DDRAMC/UDDRC (SDRAM/DDR memory controller
Signed-off-by: Akhila YS <akhilayalmati@gmail.com>
---
Changes in v3:
- Change email for maintainers.
- atmel,at91rm9200-st: redefine watchdog node as a pattern property.
- Remove corresponding binding node from txt document for every yaml patch.
- Link to v2: https://lore.kernel.org/r/20260224-arm-microchip-v2-0-8bedacd2cdcb@gmail.com
Changes in v2:
- Change email for maintainers.
- microchip,sam9x60-pit64b: modify compatible and clock-names in properties.
- Link to v1: https://lore.kernel.org/r/20260217-arm-microchip-v1-0-ae5d907e10e3@gmail.com
---
Akhila YS (5):
dt-bindings: arm: microchip,sama7g5-chipid : convert to DT schema
dt-bindings: arm: atmel,at91sam9260-pit: convert to DT schema
dt-bindings: arm: microchip,sam9x60-pit64b : convert to DT schema
dt-bindings: arm: atmel,at91rm9200-st: convert to DT schema
dt-bindings: arm: atmel,at91rm9200-sdramc: convert to DT schema
.../bindings/arm/atmel,at91rm9200-sdramc.yaml | 67 +++++++++++++++++++++
.../bindings/arm/atmel,at91rm9200-st.yaml | 69 ++++++++++++++++++++++
.../bindings/arm/atmel,at91sam9260-pit.yaml | 49 +++++++++++++++
.../devicetree/bindings/arm/atmel-sysregs.txt | 48 ---------------
.../bindings/arm/microchip,sam9x60-pit64b.yaml | 68 +++++++++++++++++++++
.../bindings/arm/microchip,sama7g5-chipid.yaml | 41 +++++++++++++
6 files changed, 294 insertions(+), 48 deletions(-)
---
base-commit: ca3a02fda4da8e2c1cb6baee5d72352e9e2cfaea
change-id: 20260128-arm-microchip-c0c0515024e6
Best regards,
--
Akhila YS <akhilayalmati@gmail.com>
| null | null | null | [PATCH v3 0/5] dt-bindings: Microchip/Atmel AT91/SAMA system
peripherals: convert to YAML | On Thu, Feb 26, 2026 at 04:13:32PM +0000, Akhila YS wrote:
These first four patches are
Acked-by: Conor Dooley <conor.dooley@microchip.com> | {
"author": "Conor Dooley <conor@kernel.org>",
"date": "Thu, 26 Feb 2026 18:12:49 +0000",
"is_openbsd": false,
"thread_id": "20260226-arm-microchip-v3-0-0bda15abd922@gmail.com.mbox.gz"
} |
lkml_critique | lkml | Convert various legacy .txt bindings for Microchip (formerly Atmel) AT91/SAMA
family system peripherals to proper YAML schemas. This includes:
- CHIPID (SoC ID register block)
- PIT (Period Interval Timer, old style)
- PIT64B (64-bit Period Interval Timer, newer parts)
- ST (System Timer, including watchdog subnode)
- RAMC/SDRAMC/DDRAMC/UDDRC (SDRAM/DDR memory controller
Signed-off-by: Akhila YS <akhilayalmati@gmail.com>
---
Changes in v3:
- Change email for maintainers.
- atmel,at91rm9200-st: redefine watchdog node as a pattern property.
- Remove corresponding binding node from txt document for every yaml patch.
- Link to v2: https://lore.kernel.org/r/20260224-arm-microchip-v2-0-8bedacd2cdcb@gmail.com
Changes in v2:
- Change email for maintainers.
- microchip,sam9x60-pit64b: modify compatible and clock-names in properties.
- Link to v1: https://lore.kernel.org/r/20260217-arm-microchip-v1-0-ae5d907e10e3@gmail.com
---
Akhila YS (5):
dt-bindings: arm: microchip,sama7g5-chipid : convert to DT schema
dt-bindings: arm: atmel,at91sam9260-pit: convert to DT schema
dt-bindings: arm: microchip,sam9x60-pit64b : convert to DT schema
dt-bindings: arm: atmel,at91rm9200-st: convert to DT schema
dt-bindings: arm: atmel,at91rm9200-sdramc: convert to DT schema
.../bindings/arm/atmel,at91rm9200-sdramc.yaml | 67 +++++++++++++++++++++
.../bindings/arm/atmel,at91rm9200-st.yaml | 69 ++++++++++++++++++++++
.../bindings/arm/atmel,at91sam9260-pit.yaml | 49 +++++++++++++++
.../devicetree/bindings/arm/atmel-sysregs.txt | 48 ---------------
.../bindings/arm/microchip,sam9x60-pit64b.yaml | 68 +++++++++++++++++++++
.../bindings/arm/microchip,sama7g5-chipid.yaml | 41 +++++++++++++
6 files changed, 294 insertions(+), 48 deletions(-)
---
base-commit: ca3a02fda4da8e2c1cb6baee5d72352e9e2cfaea
change-id: 20260128-arm-microchip-c0c0515024e6
Best regards,
--
Akhila YS <akhilayalmati@gmail.com>
| null | null | null | [PATCH v3 0/5] dt-bindings: Microchip/Atmel AT91/SAMA system
peripherals: convert to YAML | On 26-02-2026 23:42, Conor Dooley wrote:
Hi, i changed patch as per your suggestion, but i found some errors
with dtbs_check, anyway i sent a v4 patch.
let me know if any changes required.
--
Best Regards,
Akhila. | {
"author": "Akhila YS <akhilayalmati@gmail.com>",
"date": "Fri, 27 Feb 2026 21:06:15 +0530",
"is_openbsd": false,
"thread_id": "20260226-arm-microchip-v3-0-0bda15abd922@gmail.com.mbox.gz"
} |
lkml_critique | lkml | When resctrl is unmounted, MPAM components should be reset to default
configurations to avoid impacting system performance. However, after
a user updates MPAM configuration via mpam_apply_config(), the
in_reset_state flag remains true, causing mpam_reset_ris() to skip
the actual register restoration on subsequent resets.
For example, after mounting resctrl and modifying the root group's
schemata (e.g., changing MBMAX/MBMIN values), unmounting resctrl
would leave the modified MPAM settings in hardware registers since
mpam_reset_ris() returns early due to in_reset_state still being true.
This results in persistent performance restrictions even after resctrl
is umounted.
Fix by clearing in_reset_state to false immediately after successful
configuration application, ensuring that the next reset operation
properly restores MPAM register defaults.
Fixes: f188a36ca241 ("arm_mpam: Reset MSC controls from cpuhp callbacks")
Signed-off-by: Zeng Heng <zengheng4@huawei.com>
---
The in_reset_state state machine has been carefully reviewed, particularly
the handling in mpam_cpu_online() where the flag is checked before
applying configurations. in_reset_state indicates whether the RIS is
currently using default configurations. This change aligns with the
original design intent and does not introduce semantic breakage to
existing state transitions.
---
drivers/resctrl/mpam_devices.c | 1 +
1 file changed, 1 insertion(+)
diff --git a/drivers/resctrl/mpam_devices.c b/drivers/resctrl/mpam_devices.c
index 460ea98a1c92..044227ee033f 100644
--- a/drivers/resctrl/mpam_devices.c
+++ b/drivers/resctrl/mpam_devices.c
@@ -2932,6 +2932,7 @@ int mpam_apply_config(struct mpam_component *comp, u16 partid,
srcu_read_lock_held(&mpam_srcu)) {
arg.ris = ris;
mpam_touch_msc(msc, __write_config, &arg);
+ ris->in_reset_state = false;
}
mutex_unlock(&msc->cfg_lock);
}
--
2.25.1
| null | null | null | [PATCH] arm_mpam: Fix MPAM reset on resctrl unmount by clearing in_reset_state | Hi Zeng,
On 2/13/26 07:50, Zeng Heng wrote:
nit: MBMIN isn't currently supported in resctrl. I'd just drop the
part in brackets.
mpam_apply_config() doesn't exist in this commit. I would have expected:
Fixes: 09b89d2a72f3 ("arm_mpam: Allow configuration to be applied and restored during cpu online")
The change and justification looks good to me.
Acked-by: Ben Horgan <ben.horgan@arm.com>
Thanks,
Ben | {
"author": "Ben Horgan <ben.horgan@arm.com>",
"date": "Tue, 17 Feb 2026 15:59:40 +0000",
"is_openbsd": false,
"thread_id": "5071eea1-97f6-45d7-aad0-b109080f3032@arm.com.mbox.gz"
} |
lkml_critique | lkml | When resctrl is unmounted, MPAM components should be reset to default
configurations to avoid impacting system performance. However, after
a user updates MPAM configuration via mpam_apply_config(), the
in_reset_state flag remains true, causing mpam_reset_ris() to skip
the actual register restoration on subsequent resets.
For example, after mounting resctrl and modifying the root group's
schemata (e.g., changing MBMAX/MBMIN values), unmounting resctrl
would leave the modified MPAM settings in hardware registers since
mpam_reset_ris() returns early due to in_reset_state still being true.
This results in persistent performance restrictions even after resctrl
is umounted.
Fix by clearing in_reset_state to false immediately after successful
configuration application, ensuring that the next reset operation
properly restores MPAM register defaults.
Fixes: f188a36ca241 ("arm_mpam: Reset MSC controls from cpuhp callbacks")
Signed-off-by: Zeng Heng <zengheng4@huawei.com>
---
The in_reset_state state machine has been carefully reviewed, particularly
the handling in mpam_cpu_online() where the flag is checked before
applying configurations. in_reset_state indicates whether the RIS is
currently using default configurations. This change aligns with the
original design intent and does not introduce semantic breakage to
existing state transitions.
---
drivers/resctrl/mpam_devices.c | 1 +
1 file changed, 1 insertion(+)
diff --git a/drivers/resctrl/mpam_devices.c b/drivers/resctrl/mpam_devices.c
index 460ea98a1c92..044227ee033f 100644
--- a/drivers/resctrl/mpam_devices.c
+++ b/drivers/resctrl/mpam_devices.c
@@ -2932,6 +2932,7 @@ int mpam_apply_config(struct mpam_component *comp, u16 partid,
srcu_read_lock_held(&mpam_srcu)) {
arg.ris = ris;
mpam_touch_msc(msc, __write_config, &arg);
+ ris->in_reset_state = false;
}
mutex_unlock(&msc->cfg_lock);
}
--
2.25.1
| null | null | null | [PATCH] arm_mpam: Fix MPAM reset on resctrl unmount by clearing in_reset_state | On 2/17/26 15:59, Ben Horgan wrote:
I'll add this on to the start of the current mpam resctrl series as even
though this is squashing an existing bug it can't be hit until mpam has
a user interface and so doesn't need to go as a fix.
Thanks,
Ben | {
"author": "Ben Horgan <ben.horgan@arm.com>",
"date": "Fri, 27 Feb 2026 14:16:36 +0000",
"is_openbsd": false,
"thread_id": "5071eea1-97f6-45d7-aad0-b109080f3032@arm.com.mbox.gz"
} |
lkml_critique | lkml | Add support for the USB PHY and DWC2 IP which is used by Canaan K230,
and made relevant changes to the DTS.
This series is based on the initial 100ask K230 DshanPi series [1] which
is based on the clock and pinctrl series. Check the details in the link.
Link: https://lore.kernel.org/all/20260115060801.16819-1-jiayu.riscv@isrc.iscas.ac.cn/ [1]
Changes in v5:
- Changed the year of Copyright to 2026.
- Add blank line after the declaration of variables
- Fix wrong alignment.
- Link to v4: https://lore.kernel.org/all/20260120143243.71937-1-jiayu.riscv@isrc.iscas.ac.cn/
Changes in v4:
- Shrink reg length to match the address/size-cells in k230-usb-phy yaml.
- Move all PHY instance creation and initialization from xlate to probe.
- Modify xlate function to only perform index lookup for PHY instances.
- Define all register base offsets macros at the top of file instead of
hard-coding magic numbers directly in probe.
- Link to v2: https://lore.kernel.org/all/20260115064223.21926-1-jiayu.riscv@isrc.iscas.ac.cn/
Changes in v3:
- Please ignore v3.
Changes in v2:
- Fold the child into the parent in dtsi.
- Define one usbphy with phy-cells=1.
- Delete the clock of the usbphy as it is not needed.
- Link to v1: https://lore.kernel.org/all/20251230023725.15966-1-jiayu.riscv@isrc.iscas.ac.cn/
Jiayu Du (4):
dt-bindings: phy: Add Canaan K230 USB PHY
dt-bindings: usb: dwc2: Add support for Canaan K230 SoC
phy: usb: Add driver for Canaan K230 USB 2.0 PHY
riscv: dts: canaan: Add syscon and USB nodes for K230
.../bindings/phy/canaan,k230-usb-phy.yaml | 35 +++
.../devicetree/bindings/usb/dwc2.yaml | 3 +
.../boot/dts/canaan/k230-canmv-dshanpi.dts | 17 ++
arch/riscv/boot/dts/canaan/k230.dtsi | 35 +++
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/canaan/Kconfig | 14 +
drivers/phy/canaan/Makefile | 2 +
drivers/phy/canaan/phy-k230-usb.c | 284 ++++++++++++++++++
9 files changed, 392 insertions(+)
create mode 100644 Documentation/devicetree/bindings/phy/canaan,k230-usb-phy.yaml
create mode 100644 drivers/phy/canaan/Kconfig
create mode 100644 drivers/phy/canaan/Makefile
create mode 100644 drivers/phy/canaan/phy-k230-usb.c
--
2.52.0
| null | null | null | [PATCH v5 0/4] Add USB support for Canaan K230 | Add 'canaan,k230-usb' compatible string with 'snps,dwc2' as fallback
for the DWC2 IP which is used by Canaan K230.
Reviewed-by: Rob Herring (Arm) <robh@kernel.org>
Signed-off-by: Jiayu Du <jiayu.riscv@isrc.iscas.ac.cn>
---
Documentation/devicetree/bindings/usb/dwc2.yaml | 3 +++
1 file changed, 3 insertions(+)
diff --git a/Documentation/devicetree/bindings/usb/dwc2.yaml b/Documentation/devicetree/bindings/usb/dwc2.yaml
index 6c3a10991b8b..352487c6392a 100644
--- a/Documentation/devicetree/bindings/usb/dwc2.yaml
+++ b/Documentation/devicetree/bindings/usb/dwc2.yaml
@@ -17,6 +17,9 @@ properties:
compatible:
oneOf:
- const: brcm,bcm2835-usb
+ - items:
+ - const: canaan,k230-usb
+ - const: snps,dwc2
- const: hisilicon,hi6220-usb
- const: ingenic,jz4775-otg
- const: ingenic,jz4780-otg
--
2.52.0 | {
"author": "Jiayu Du <jiayu.riscv@isrc.iscas.ac.cn>",
"date": "Wed, 21 Jan 2026 22:55:23 +0800",
"is_openbsd": false,
"thread_id": "177220615264.330302.188095105582835535.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Add support for the USB PHY and DWC2 IP which is used by Canaan K230,
and made relevant changes to the DTS.
This series is based on the initial 100ask K230 DshanPi series [1] which
is based on the clock and pinctrl series. Check the details in the link.
Link: https://lore.kernel.org/all/20260115060801.16819-1-jiayu.riscv@isrc.iscas.ac.cn/ [1]
Changes in v5:
- Changed the year of Copyright to 2026.
- Add blank line after the declaration of variables
- Fix wrong alignment.
- Link to v4: https://lore.kernel.org/all/20260120143243.71937-1-jiayu.riscv@isrc.iscas.ac.cn/
Changes in v4:
- Shrink reg length to match the address/size-cells in k230-usb-phy yaml.
- Move all PHY instance creation and initialization from xlate to probe.
- Modify xlate function to only perform index lookup for PHY instances.
- Define all register base offsets macros at the top of file instead of
hard-coding magic numbers directly in probe.
- Link to v2: https://lore.kernel.org/all/20260115064223.21926-1-jiayu.riscv@isrc.iscas.ac.cn/
Changes in v3:
- Please ignore v3.
Changes in v2:
- Fold the child into the parent in dtsi.
- Define one usbphy with phy-cells=1.
- Delete the clock of the usbphy as it is not needed.
- Link to v1: https://lore.kernel.org/all/20251230023725.15966-1-jiayu.riscv@isrc.iscas.ac.cn/
Jiayu Du (4):
dt-bindings: phy: Add Canaan K230 USB PHY
dt-bindings: usb: dwc2: Add support for Canaan K230 SoC
phy: usb: Add driver for Canaan K230 USB 2.0 PHY
riscv: dts: canaan: Add syscon and USB nodes for K230
.../bindings/phy/canaan,k230-usb-phy.yaml | 35 +++
.../devicetree/bindings/usb/dwc2.yaml | 3 +
.../boot/dts/canaan/k230-canmv-dshanpi.dts | 17 ++
arch/riscv/boot/dts/canaan/k230.dtsi | 35 +++
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/canaan/Kconfig | 14 +
drivers/phy/canaan/Makefile | 2 +
drivers/phy/canaan/phy-k230-usb.c | 284 ++++++++++++++++++
9 files changed, 392 insertions(+)
create mode 100644 Documentation/devicetree/bindings/phy/canaan,k230-usb-phy.yaml
create mode 100644 drivers/phy/canaan/Kconfig
create mode 100644 drivers/phy/canaan/Makefile
create mode 100644 drivers/phy/canaan/phy-k230-usb.c
--
2.52.0
| null | null | null | [PATCH v5 0/4] Add USB support for Canaan K230 | K230 SoC USB PHY requires configuring registers for control and
configuration. Add USB phy bindings for K230 SoC.
Reviewed-by: Rob Herring (Arm) <robh@kernel.org>
Signed-off-by: Jiayu Du <jiayu.riscv@isrc.iscas.ac.cn>
---
.../bindings/phy/canaan,k230-usb-phy.yaml | 35 +++++++++++++++++++
1 file changed, 35 insertions(+)
create mode 100644 Documentation/devicetree/bindings/phy/canaan,k230-usb-phy.yaml
diff --git a/Documentation/devicetree/bindings/phy/canaan,k230-usb-phy.yaml b/Documentation/devicetree/bindings/phy/canaan,k230-usb-phy.yaml
new file mode 100644
index 000000000000..b959b381c44c
--- /dev/null
+++ b/Documentation/devicetree/bindings/phy/canaan,k230-usb-phy.yaml
@@ -0,0 +1,35 @@
+# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/phy/canaan,k230-usb-phy.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Canaan K230 USB2.0 PHY
+
+maintainers:
+ - Jiayu Du <jiayu.riscv@isrc.iscas.ac.cn>
+
+properties:
+ compatible:
+ const: canaan,k230-usb-phy
+
+ reg:
+ maxItems: 1
+
+ "#phy-cells":
+ const: 1
+
+required:
+ - compatible
+ - reg
+ - "#phy-cells"
+
+additionalProperties: false
+
+examples:
+ - |
+ usbphy: usb-phy@91585000 {
+ compatible = "canaan,k230-usb-phy";
+ reg = <0x91585000 0x400>;
+ #phy-cells = <1>;
+ };
--
2.52.0 | {
"author": "Jiayu Du <jiayu.riscv@isrc.iscas.ac.cn>",
"date": "Wed, 21 Jan 2026 22:55:22 +0800",
"is_openbsd": false,
"thread_id": "177220615264.330302.188095105582835535.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Add support for the USB PHY and DWC2 IP which is used by Canaan K230,
and made relevant changes to the DTS.
This series is based on the initial 100ask K230 DshanPi series [1] which
is based on the clock and pinctrl series. Check the details in the link.
Link: https://lore.kernel.org/all/20260115060801.16819-1-jiayu.riscv@isrc.iscas.ac.cn/ [1]
Changes in v5:
- Changed the year of Copyright to 2026.
- Add blank line after the declaration of variables
- Fix wrong alignment.
- Link to v4: https://lore.kernel.org/all/20260120143243.71937-1-jiayu.riscv@isrc.iscas.ac.cn/
Changes in v4:
- Shrink reg length to match the address/size-cells in k230-usb-phy yaml.
- Move all PHY instance creation and initialization from xlate to probe.
- Modify xlate function to only perform index lookup for PHY instances.
- Define all register base offsets macros at the top of file instead of
hard-coding magic numbers directly in probe.
- Link to v2: https://lore.kernel.org/all/20260115064223.21926-1-jiayu.riscv@isrc.iscas.ac.cn/
Changes in v3:
- Please ignore v3.
Changes in v2:
- Fold the child into the parent in dtsi.
- Define one usbphy with phy-cells=1.
- Delete the clock of the usbphy as it is not needed.
- Link to v1: https://lore.kernel.org/all/20251230023725.15966-1-jiayu.riscv@isrc.iscas.ac.cn/
Jiayu Du (4):
dt-bindings: phy: Add Canaan K230 USB PHY
dt-bindings: usb: dwc2: Add support for Canaan K230 SoC
phy: usb: Add driver for Canaan K230 USB 2.0 PHY
riscv: dts: canaan: Add syscon and USB nodes for K230
.../bindings/phy/canaan,k230-usb-phy.yaml | 35 +++
.../devicetree/bindings/usb/dwc2.yaml | 3 +
.../boot/dts/canaan/k230-canmv-dshanpi.dts | 17 ++
arch/riscv/boot/dts/canaan/k230.dtsi | 35 +++
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/canaan/Kconfig | 14 +
drivers/phy/canaan/Makefile | 2 +
drivers/phy/canaan/phy-k230-usb.c | 284 ++++++++++++++++++
9 files changed, 392 insertions(+)
create mode 100644 Documentation/devicetree/bindings/phy/canaan,k230-usb-phy.yaml
create mode 100644 drivers/phy/canaan/Kconfig
create mode 100644 drivers/phy/canaan/Makefile
create mode 100644 drivers/phy/canaan/phy-k230-usb.c
--
2.52.0
| null | null | null | [PATCH v5 0/4] Add USB support for Canaan K230 | Add top syscon and USB PHY subdevice nodes, USB0/USB1 dwc2 controller
to K230 DTSI, and enable UART0 and USB0/USB1 in DshanPI DT.
Signed-off-by: Jiayu Du <jiayu.riscv@isrc.iscas.ac.cn>
---
.../boot/dts/canaan/k230-canmv-dshanpi.dts | 17 +++++++++
arch/riscv/boot/dts/canaan/k230.dtsi | 35 +++++++++++++++++++
2 files changed, 52 insertions(+)
diff --git a/arch/riscv/boot/dts/canaan/k230-canmv-dshanpi.dts b/arch/riscv/boot/dts/canaan/k230-canmv-dshanpi.dts
index 4f95b534ee87..55197cfc25b4 100644
--- a/arch/riscv/boot/dts/canaan/k230-canmv-dshanpi.dts
+++ b/arch/riscv/boot/dts/canaan/k230-canmv-dshanpi.dts
@@ -80,3 +80,20 @@ &uart0 {
pinctrl-0 = <&uart0_pins>;
status = "okay";
};
+
+&usb0 {
+ vusb_d-supply = <&vdd_3v3>;
+ vusb_a-supply = <&vdd_1v8>;
+ status = "okay";
+};
+
+&usb1 {
+ dr_mode = "host";
+ vusb_d-supply = <&vdd_3v3>;
+ vusb_a-supply = <&vdd_1v8>;
+ status = "okay";
+};
+
+&usbphy {
+ status = "okay";
+};
diff --git a/arch/riscv/boot/dts/canaan/k230.dtsi b/arch/riscv/boot/dts/canaan/k230.dtsi
index 8ca5c7dee427..b369b7d8dc83 100644
--- a/arch/riscv/boot/dts/canaan/k230.dtsi
+++ b/arch/riscv/boot/dts/canaan/k230.dtsi
@@ -148,5 +148,40 @@ uart4: serial@91404000 {
reg-shift = <2>;
status = "disabled";
};
+
+ usb0: usb@91500000 {
+ compatible = "canaan,k230-usb", "snps,dwc2";
+ reg = <0x0 0x91500000 0x0 0x40000>;
+ interrupts = <173 IRQ_TYPE_LEVEL_HIGH>;
+ clocks = <&sysclk K230_HS_USB0_AHB_GATE>;
+ clock-names = "otg";
+ g-rx-fifo-size = <512>;
+ g-np-tx-fifo-size = <64>;
+ g-tx-fifo-size = <512 1024 64 64 64 64>;
+ phys = <&usbphy 0>;
+ phy-names = "usb2-phy";
+ status = "disabled";
+ };
+
+ usb1: usb@91540000 {
+ compatible = "canaan,k230-usb", "snps,dwc2";
+ reg = <0x0 0x91540000 0x0 0x40000>;
+ interrupts = <174 IRQ_TYPE_LEVEL_HIGH>;
+ clocks = <&sysclk K230_HS_USB1_AHB_GATE>;
+ clock-names = "otg";
+ g-rx-fifo-size = <512>;
+ g-np-tx-fifo-size = <64>;
+ g-tx-fifo-size = <512 1024 64 64 64 64>;
+ phys = <&usbphy 1>;
+ phy-names = "usb2-phy";
+ status = "disabled";
+ };
+
+ usbphy: usb-phy@91585000 {
+ compatible = "canaan,k230-usb-phy";
+ reg = <0x0 0x91585000 0x0 0x400>;
+ #phy-cells = <1>;
+ status = "disabled";
+ };
};
};
--
2.52.0 | {
"author": "Jiayu Du <jiayu.riscv@isrc.iscas.ac.cn>",
"date": "Wed, 21 Jan 2026 22:55:25 +0800",
"is_openbsd": false,
"thread_id": "177220615264.330302.188095105582835535.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Add support for the USB PHY and DWC2 IP which is used by Canaan K230,
and made relevant changes to the DTS.
This series is based on the initial 100ask K230 DshanPi series [1] which
is based on the clock and pinctrl series. Check the details in the link.
Link: https://lore.kernel.org/all/20260115060801.16819-1-jiayu.riscv@isrc.iscas.ac.cn/ [1]
Changes in v5:
- Changed the year of Copyright to 2026.
- Add blank line after the declaration of variables
- Fix wrong alignment.
- Link to v4: https://lore.kernel.org/all/20260120143243.71937-1-jiayu.riscv@isrc.iscas.ac.cn/
Changes in v4:
- Shrink reg length to match the address/size-cells in k230-usb-phy yaml.
- Move all PHY instance creation and initialization from xlate to probe.
- Modify xlate function to only perform index lookup for PHY instances.
- Define all register base offsets macros at the top of file instead of
hard-coding magic numbers directly in probe.
- Link to v2: https://lore.kernel.org/all/20260115064223.21926-1-jiayu.riscv@isrc.iscas.ac.cn/
Changes in v3:
- Please ignore v3.
Changes in v2:
- Fold the child into the parent in dtsi.
- Define one usbphy with phy-cells=1.
- Delete the clock of the usbphy as it is not needed.
- Link to v1: https://lore.kernel.org/all/20251230023725.15966-1-jiayu.riscv@isrc.iscas.ac.cn/
Jiayu Du (4):
dt-bindings: phy: Add Canaan K230 USB PHY
dt-bindings: usb: dwc2: Add support for Canaan K230 SoC
phy: usb: Add driver for Canaan K230 USB 2.0 PHY
riscv: dts: canaan: Add syscon and USB nodes for K230
.../bindings/phy/canaan,k230-usb-phy.yaml | 35 +++
.../devicetree/bindings/usb/dwc2.yaml | 3 +
.../boot/dts/canaan/k230-canmv-dshanpi.dts | 17 ++
arch/riscv/boot/dts/canaan/k230.dtsi | 35 +++
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/canaan/Kconfig | 14 +
drivers/phy/canaan/Makefile | 2 +
drivers/phy/canaan/phy-k230-usb.c | 284 ++++++++++++++++++
9 files changed, 392 insertions(+)
create mode 100644 Documentation/devicetree/bindings/phy/canaan,k230-usb-phy.yaml
create mode 100644 drivers/phy/canaan/Kconfig
create mode 100644 drivers/phy/canaan/Makefile
create mode 100644 drivers/phy/canaan/phy-k230-usb.c
--
2.52.0
| null | null | null | [PATCH v5 0/4] Add USB support for Canaan K230 | Add driver for the USB 2.0 PHY in Canaan K230 SoC, which supports PHY
initialization and power management.
Add Kconfig/Makefile under drivers/phy/canaan/.
Signed-off-by: Jiayu Du <jiayu.riscv@isrc.iscas.ac.cn>
---
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/canaan/Kconfig | 14 ++
drivers/phy/canaan/Makefile | 2 +
drivers/phy/canaan/phy-k230-usb.c | 284 ++++++++++++++++++++++++++++++
5 files changed, 302 insertions(+)
create mode 100644 drivers/phy/canaan/Kconfig
create mode 100644 drivers/phy/canaan/Makefile
create mode 100644 drivers/phy/canaan/phy-k230-usb.c
diff --git a/drivers/phy/Kconfig b/drivers/phy/Kconfig
index 142e7b0ef2ef..e37bcceef65a 100644
--- a/drivers/phy/Kconfig
+++ b/drivers/phy/Kconfig
@@ -150,6 +150,7 @@ source "drivers/phy/amlogic/Kconfig"
source "drivers/phy/apple/Kconfig"
source "drivers/phy/broadcom/Kconfig"
source "drivers/phy/cadence/Kconfig"
+source "drivers/phy/canaan/Kconfig"
source "drivers/phy/freescale/Kconfig"
source "drivers/phy/hisilicon/Kconfig"
source "drivers/phy/ingenic/Kconfig"
diff --git a/drivers/phy/Makefile b/drivers/phy/Makefile
index dcbb060c8207..8cef0a447986 100644
--- a/drivers/phy/Makefile
+++ b/drivers/phy/Makefile
@@ -22,6 +22,7 @@ obj-y += allwinner/ \
apple/ \
broadcom/ \
cadence/ \
+ canaan/ \
freescale/ \
hisilicon/ \
ingenic/ \
diff --git a/drivers/phy/canaan/Kconfig b/drivers/phy/canaan/Kconfig
new file mode 100644
index 000000000000..1ff8831846d5
--- /dev/null
+++ b/drivers/phy/canaan/Kconfig
@@ -0,0 +1,14 @@
+# SPDX-License-Identifier: GPL-2.0-only
+#
+# Phy drivers for Canaan platforms
+#
+config PHY_CANAAN_USB
+ tristate "Canaan USB2 PHY Driver"
+ depends on (ARCH_CANAAN || COMPILE_TEST) && OF
+ select GENERIC_PHY
+ help
+ Enable this driver to support the USB 2.0 PHY controller
+ on Canaan K230 RISC-V SoCs. This PHY controller
+ provides physical layer functionality for USB 2.0 devices.
+ If you have a Canaan K230 board and need USB 2.0 support,
+ say Y or M here.
diff --git a/drivers/phy/canaan/Makefile b/drivers/phy/canaan/Makefile
new file mode 100644
index 000000000000..d73857ba284e
--- /dev/null
+++ b/drivers/phy/canaan/Makefile
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0
+obj-$(CONFIG_PHY_CANAAN_USB) += phy-k230-usb.o
diff --git a/drivers/phy/canaan/phy-k230-usb.c b/drivers/phy/canaan/phy-k230-usb.c
new file mode 100644
index 000000000000..52dad35fc6cf
--- /dev/null
+++ b/drivers/phy/canaan/phy-k230-usb.c
@@ -0,0 +1,284 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Canaan usb PHY driver
+ *
+ * Copyright (C) 2026 Jiayu Du <jiayu.riscv@isrc.iscas.ac.cn>
+ */
+
+#include <linux/bitfield.h>
+#include <linux/io.h>
+#include <linux/of_address.h>
+#include <linux/phy/phy.h>
+#include <linux/platform_device.h>
+
+#define MAX_PHYS 2
+
+/* Register offsets within the HiSysConfig system controller */
+#define K230_USB0_TEST_REG_BASE 0x70
+#define K230_USB0_CTL_REG_BASE 0xb0
+#define K230_USB1_TEST_REG_BASE 0x90
+#define K230_USB1_CTL_REG_BASE 0xb8
+
+/* Relative offsets within each PHY's control/test block */
+#define CTL0_OFFSET 0x00
+#define CTL1_OFFSET 0x04
+#define TEST_CTL3_OFFSET 0x0c
+
+/* Bit definitions for TEST_CTL3 */
+#define USB_IDPULLUP0 BIT(4)
+#define USB_DMPULLDOWN0 BIT(8)
+#define USB_DPPULLDOWN0 BIT(9)
+
+/* USB control register 0 in HiSysConfig system controller */
+/* PLL Integral Path Tune */
+#define USB_CTL0_PLLITUNE_MASK GENMASK(23, 22)
+
+/* PLL Proportional Path Tune */
+#define USB_CTL0_PLLPTUNE_MASK GENMASK(21, 18)
+
+/* PLL Bandwidth Adjustment */
+#define USB_CTL0_PLLBTUNE_MASK GENMASK(17, 17)
+
+/* VReg18 Bypass Control */
+#define USB_CTL0_VREGBYPASS_MASK GENMASK(16, 16)
+
+/* Retention Mode Enable */
+#define USB_CTL0_RETENABLEN_MASK GENMASK(15, 15)
+
+/* Reserved Request Input */
+#define USB_CTL0_RESREQIN_MASK GENMASK(14, 14)
+
+/* External VBUS Valid Select */
+#define USB_CTL0_VBUSVLDEXTSEL0_MASK GENMASK(13, 13)
+
+/* OTG Block Disable Control */
+#define USB_CTL0_OTGDISABLE0_MASK GENMASK(12, 12)
+
+/* Drive VBUS Enable */
+#define USB_CTL0_DRVVBUS0_MASK GENMASK(11, 11)
+
+/* Autoresume Mode Enable */
+#define USB_CTL0_AUTORSMENB0_MASK GENMASK(10, 10)
+
+/* HS Transceiver Asynchronous Control */
+#define USB_CTL0_HSXCVREXTCTL0_MASK GENMASK(9, 9)
+
+/* USB 1.1 Transmit Data */
+#define USB_CTL0_FSDATAEXT0_MASK GENMASK(8, 8)
+
+/* USB 1.1 SE0 Generation */
+#define USB_CTL0_FSSE0EXT0_MASK GENMASK(7, 7)
+
+/* USB 1.1 Data Enable */
+#define USB_CTL0_TXENABLEN0_MASK GENMASK(6, 6)
+
+/* Disconnect Threshold */
+#define USB_CTL0_COMPDISTUNE0_MASK GENMASK(5, 3)
+
+/* Squelch Threshold */
+#define USB_CTL0_SQRXTUNE0_MASK GENMASK(2, 0)
+
+/* USB control register 1 in HiSysConfig system controller */
+/* Data Detect Voltage */
+#define USB_CTL1_VDATREFTUNE0_MASK GENMASK(23, 22)
+
+/* VBUS Valid Threshold */
+#define USB_CTL1_OTGTUNE0_MASK GENMASK(21, 19)
+
+/* Transmitter High-Speed Crossover */
+#define USB_CTL1_TXHSXVTUNE0_MASK GENMASK(18, 17)
+
+/* FS/LS Source Impedance */
+#define USB_CTL1_TXFSLSTUNE0_MASK GENMASK(16, 13)
+
+/* HS DC Voltage Level */
+#define USB_CTL1_TXVREFTUNE0_MASK GENMASK(12, 9)
+
+/* HS Transmitter Rise/Fall Time */
+#define USB_CTL1_TXRISETUNE0_MASK GENMASK(8, 7)
+
+/* USB Source Impedance */
+#define USB_CTL1_TXRESTUNE0_MASK GENMASK(6, 5)
+
+/* HS Transmitter Pre-Emphasis Current Control */
+#define USB_CTL1_TXPREEMPAMPTUNE0_MASK GENMASK(4, 3)
+
+/* HS Transmitter Pre-Emphasis Duration Control */
+#define USB_CTL1_TXPREEMPPULSETUNE0_MASK GENMASK(2, 2)
+
+/* charging detection */
+#define USB_CTL1_CHRGSRCPUENB0_MASK GENMASK(1, 0)
+
+#define K230_PHY_CTL0_VAL \
+( \
+ FIELD_PREP(USB_CTL0_PLLITUNE_MASK, 0x0) | \
+ FIELD_PREP(USB_CTL0_PLLPTUNE_MASK, 0xc) | \
+ FIELD_PREP(USB_CTL0_PLLBTUNE_MASK, 0x1) | \
+ FIELD_PREP(USB_CTL0_VREGBYPASS_MASK, 0x1) | \
+ FIELD_PREP(USB_CTL0_RETENABLEN_MASK, 0x1) | \
+ FIELD_PREP(USB_CTL0_RESREQIN_MASK, 0x0) | \
+ FIELD_PREP(USB_CTL0_VBUSVLDEXTSEL0_MASK, 0x0) | \
+ FIELD_PREP(USB_CTL0_OTGDISABLE0_MASK, 0x0) | \
+ FIELD_PREP(USB_CTL0_DRVVBUS0_MASK, 0x1) | \
+ FIELD_PREP(USB_CTL0_AUTORSMENB0_MASK, 0x0) | \
+ FIELD_PREP(USB_CTL0_HSXCVREXTCTL0_MASK, 0x0) | \
+ FIELD_PREP(USB_CTL0_FSDATAEXT0_MASK, 0x0) | \
+ FIELD_PREP(USB_CTL0_FSSE0EXT0_MASK, 0x0) | \
+ FIELD_PREP(USB_CTL0_TXENABLEN0_MASK, 0x0) | \
+ FIELD_PREP(USB_CTL0_COMPDISTUNE0_MASK, 0x3) | \
+ FIELD_PREP(USB_CTL0_SQRXTUNE0_MASK, 0x3) \
+)
+
+#define K230_PHY_CTL1_VAL \
+( \
+ FIELD_PREP(USB_CTL1_VDATREFTUNE0_MASK, 0x1) | \
+ FIELD_PREP(USB_CTL1_OTGTUNE0_MASK, 0x3) | \
+ FIELD_PREP(USB_CTL1_TXHSXVTUNE0_MASK, 0x3) | \
+ FIELD_PREP(USB_CTL1_TXFSLSTUNE0_MASK, 0x3) | \
+ FIELD_PREP(USB_CTL1_TXVREFTUNE0_MASK, 0x3) | \
+ FIELD_PREP(USB_CTL1_TXRISETUNE0_MASK, 0x1) | \
+ FIELD_PREP(USB_CTL1_TXRESTUNE0_MASK, 0x1) | \
+ FIELD_PREP(USB_CTL1_TXPREEMPAMPTUNE0_MASK, 0x0) | \
+ FIELD_PREP(USB_CTL1_TXPREEMPPULSETUNE0_MASK, 0x0) | \
+ FIELD_PREP(USB_CTL1_CHRGSRCPUENB0_MASK, 0x0) \
+)
+
+struct k230_usb_phy_instance {
+ struct k230_usb_phy_global *global;
+ struct phy *phy;
+ u32 test_offset;
+ u32 ctl_offset;
+ int index;
+};
+
+struct k230_usb_phy_global {
+ struct k230_usb_phy_instance phys[MAX_PHYS];
+ void __iomem *base;
+};
+
+static int k230_usb_phy_power_on(struct phy *phy)
+{
+ struct k230_usb_phy_instance *inst = phy_get_drvdata(phy);
+ struct k230_usb_phy_global *global = inst->global;
+ void __iomem *base = global->base;
+ u32 val;
+
+ /* Apply recommended settings */
+ writel(K230_PHY_CTL0_VAL, base + inst->ctl_offset + CTL0_OFFSET);
+ writel(K230_PHY_CTL1_VAL, base + inst->ctl_offset + CTL1_OFFSET);
+
+ /* Configure test register (pull-ups/pull-downs) */
+ val = readl(base + inst->test_offset + TEST_CTL3_OFFSET);
+ val |= USB_IDPULLUP0;
+
+ if (inst->index == 1)
+ val |= (USB_DMPULLDOWN0 | USB_DPPULLDOWN0);
+ else
+ val &= ~(USB_DMPULLDOWN0 | USB_DPPULLDOWN0);
+
+ writel(val, base + inst->test_offset + TEST_CTL3_OFFSET);
+
+ return 0;
+}
+
+static int k230_usb_phy_power_off(struct phy *phy)
+{
+ struct k230_usb_phy_instance *inst = phy_get_drvdata(phy);
+ struct k230_usb_phy_global *global = inst->global;
+ void __iomem *base = global->base;
+ u32 val;
+
+ val = readl(base + inst->test_offset + TEST_CTL3_OFFSET);
+ val &= ~(USB_DMPULLDOWN0 | USB_DPPULLDOWN0);
+ writel(val, base + inst->test_offset + TEST_CTL3_OFFSET);
+
+ return 0;
+}
+
+static const struct phy_ops k230_usb_phy_ops = {
+ .power_on = k230_usb_phy_power_on,
+ .power_off = k230_usb_phy_power_off,
+ .owner = THIS_MODULE,
+};
+
+static struct phy *k230_usb_phy_xlate(struct device *dev,
+ const struct of_phandle_args *args)
+{
+ struct k230_usb_phy_global *global = dev_get_drvdata(dev);
+ unsigned int idx = args->args[0];
+
+ if (idx >= MAX_PHYS)
+ return ERR_PTR(-EINVAL);
+
+ return global->phys[idx].phy;
+}
+
+static int k230_usb_phy_probe(struct platform_device *pdev)
+{
+ struct k230_usb_phy_global *global;
+ struct device *dev = &pdev->dev;
+ struct phy_provider *provider;
+ int i;
+
+ global = devm_kzalloc(dev, sizeof(*global), GFP_KERNEL);
+ if (!global)
+ return -ENOMEM;
+ dev_set_drvdata(dev, global);
+
+ global->base = devm_platform_ioremap_resource(pdev, 0);
+ if (IS_ERR(global->base))
+ return dev_err_probe(dev, PTR_ERR(global->base),
+ "failed to map registers\n");
+
+ static const struct {
+ u32 test_offset;
+ u32 ctl_offset;
+ } phy_reg_info[MAX_PHYS] = {
+ [0] = { K230_USB0_TEST_REG_BASE, K230_USB0_CTL_REG_BASE },
+ [1] = { K230_USB1_TEST_REG_BASE, K230_USB1_CTL_REG_BASE },
+ };
+
+ for (i = 0; i < MAX_PHYS; i++) {
+ struct k230_usb_phy_instance *inst = &global->phys[i];
+ struct phy *phy;
+
+ inst->global = global;
+ inst->index = i;
+ inst->test_offset = phy_reg_info[i].test_offset;
+ inst->ctl_offset = phy_reg_info[i].ctl_offset;
+
+ phy = devm_phy_create(dev, NULL, &k230_usb_phy_ops);
+ if (IS_ERR(phy)) {
+ dev_err(dev, "failed to create phy%d\n", i);
+ return PTR_ERR(phy);
+ }
+
+ phy_set_drvdata(phy, inst);
+ inst->phy = phy;
+ }
+
+ provider = devm_of_phy_provider_register(dev, k230_usb_phy_xlate);
+ if (IS_ERR(provider))
+ return PTR_ERR(provider);
+
+ return 0;
+}
+
+static const struct of_device_id k230_usb_phy_of_match[] = {
+ { .compatible = "canaan,k230-usb-phy" },
+ {}
+};
+MODULE_DEVICE_TABLE(of, k230_usb_phy_of_match);
+
+static struct platform_driver k230_usb_phy_driver = {
+ .probe = k230_usb_phy_probe,
+ .driver = {
+ .name = "k230-usb-phy",
+ .of_match_table = k230_usb_phy_of_match,
+ },
+};
+module_platform_driver(k230_usb_phy_driver);
+
+MODULE_DESCRIPTION("Canaan Kendryte K230 USB 2.0 PHY driver");
+MODULE_AUTHOR("Jiayu Du <jiayu.riscv@isrc.iscas.ac.cn>");
+MODULE_LICENSE("GPL");
--
2.52.0 | {
"author": "Jiayu Du <jiayu.riscv@isrc.iscas.ac.cn>",
"date": "Wed, 21 Jan 2026 22:55:24 +0800",
"is_openbsd": false,
"thread_id": "177220615264.330302.188095105582835535.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Add support for the USB PHY and DWC2 IP which is used by Canaan K230,
and made relevant changes to the DTS.
This series is based on the initial 100ask K230 DshanPi series [1] which
is based on the clock and pinctrl series. Check the details in the link.
Link: https://lore.kernel.org/all/20260115060801.16819-1-jiayu.riscv@isrc.iscas.ac.cn/ [1]
Changes in v5:
- Changed the year of Copyright to 2026.
- Add blank line after the declaration of variables
- Fix wrong alignment.
- Link to v4: https://lore.kernel.org/all/20260120143243.71937-1-jiayu.riscv@isrc.iscas.ac.cn/
Changes in v4:
- Shrink reg length to match the address/size-cells in k230-usb-phy yaml.
- Move all PHY instance creation and initialization from xlate to probe.
- Modify xlate function to only perform index lookup for PHY instances.
- Define all register base offsets macros at the top of file instead of
hard-coding magic numbers directly in probe.
- Link to v2: https://lore.kernel.org/all/20260115064223.21926-1-jiayu.riscv@isrc.iscas.ac.cn/
Changes in v3:
- Please ignore v3.
Changes in v2:
- Fold the child into the parent in dtsi.
- Define one usbphy with phy-cells=1.
- Delete the clock of the usbphy as it is not needed.
- Link to v1: https://lore.kernel.org/all/20251230023725.15966-1-jiayu.riscv@isrc.iscas.ac.cn/
Jiayu Du (4):
dt-bindings: phy: Add Canaan K230 USB PHY
dt-bindings: usb: dwc2: Add support for Canaan K230 SoC
phy: usb: Add driver for Canaan K230 USB 2.0 PHY
riscv: dts: canaan: Add syscon and USB nodes for K230
.../bindings/phy/canaan,k230-usb-phy.yaml | 35 +++
.../devicetree/bindings/usb/dwc2.yaml | 3 +
.../boot/dts/canaan/k230-canmv-dshanpi.dts | 17 ++
arch/riscv/boot/dts/canaan/k230.dtsi | 35 +++
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/canaan/Kconfig | 14 +
drivers/phy/canaan/Makefile | 2 +
drivers/phy/canaan/phy-k230-usb.c | 284 ++++++++++++++++++
9 files changed, 392 insertions(+)
create mode 100644 Documentation/devicetree/bindings/phy/canaan,k230-usb-phy.yaml
create mode 100644 drivers/phy/canaan/Kconfig
create mode 100644 drivers/phy/canaan/Makefile
create mode 100644 drivers/phy/canaan/phy-k230-usb.c
--
2.52.0
| null | null | null | [PATCH v5 0/4] Add USB support for Canaan K230 | On Wed, Jan 21, 2026 at 10:55:21PM +0800, Jiayu Du wrote:
Hello Vinod, could you please take a look at this patch? Thank you!
Regards,
Jiayu Du | {
"author": "Jiayu Du <jiayu.riscv@isrc.iscas.ac.cn>",
"date": "Mon, 2 Feb 2026 19:31:36 +0800",
"is_openbsd": false,
"thread_id": "177220615264.330302.188095105582835535.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Add support for the USB PHY and DWC2 IP which is used by Canaan K230,
and made relevant changes to the DTS.
This series is based on the initial 100ask K230 DshanPi series [1] which
is based on the clock and pinctrl series. Check the details in the link.
Link: https://lore.kernel.org/all/20260115060801.16819-1-jiayu.riscv@isrc.iscas.ac.cn/ [1]
Changes in v5:
- Changed the year of Copyright to 2026.
- Add blank line after the declaration of variables
- Fix wrong alignment.
- Link to v4: https://lore.kernel.org/all/20260120143243.71937-1-jiayu.riscv@isrc.iscas.ac.cn/
Changes in v4:
- Shrink reg length to match the address/size-cells in k230-usb-phy yaml.
- Move all PHY instance creation and initialization from xlate to probe.
- Modify xlate function to only perform index lookup for PHY instances.
- Define all register base offsets macros at the top of file instead of
hard-coding magic numbers directly in probe.
- Link to v2: https://lore.kernel.org/all/20260115064223.21926-1-jiayu.riscv@isrc.iscas.ac.cn/
Changes in v3:
- Please ignore v3.
Changes in v2:
- Fold the child into the parent in dtsi.
- Define one usbphy with phy-cells=1.
- Delete the clock of the usbphy as it is not needed.
- Link to v1: https://lore.kernel.org/all/20251230023725.15966-1-jiayu.riscv@isrc.iscas.ac.cn/
Jiayu Du (4):
dt-bindings: phy: Add Canaan K230 USB PHY
dt-bindings: usb: dwc2: Add support for Canaan K230 SoC
phy: usb: Add driver for Canaan K230 USB 2.0 PHY
riscv: dts: canaan: Add syscon and USB nodes for K230
.../bindings/phy/canaan,k230-usb-phy.yaml | 35 +++
.../devicetree/bindings/usb/dwc2.yaml | 3 +
.../boot/dts/canaan/k230-canmv-dshanpi.dts | 17 ++
arch/riscv/boot/dts/canaan/k230.dtsi | 35 +++
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/canaan/Kconfig | 14 +
drivers/phy/canaan/Makefile | 2 +
drivers/phy/canaan/phy-k230-usb.c | 284 ++++++++++++++++++
9 files changed, 392 insertions(+)
create mode 100644 Documentation/devicetree/bindings/phy/canaan,k230-usb-phy.yaml
create mode 100644 drivers/phy/canaan/Kconfig
create mode 100644 drivers/phy/canaan/Makefile
create mode 100644 drivers/phy/canaan/phy-k230-usb.c
--
2.52.0
| null | null | null | [PATCH v5 0/4] Add USB support for Canaan K230 | On Mon, Feb 02, 2026 at 07:31:36PM +0800, Jiayu Du wrote:
Hi Vinod, will you review this patch? Thank you again!
Regards,
Jiayu Du | {
"author": "Jiayu Du <jiayu.riscv@isrc.iscas.ac.cn>",
"date": "Wed, 25 Feb 2026 20:14:46 +0800",
"is_openbsd": false,
"thread_id": "177220615264.330302.188095105582835535.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Add support for the USB PHY and DWC2 IP which is used by Canaan K230,
and made relevant changes to the DTS.
This series is based on the initial 100ask K230 DshanPi series [1] which
is based on the clock and pinctrl series. Check the details in the link.
Link: https://lore.kernel.org/all/20260115060801.16819-1-jiayu.riscv@isrc.iscas.ac.cn/ [1]
Changes in v5:
- Changed the year of Copyright to 2026.
- Add blank line after the declaration of variables
- Fix wrong alignment.
- Link to v4: https://lore.kernel.org/all/20260120143243.71937-1-jiayu.riscv@isrc.iscas.ac.cn/
Changes in v4:
- Shrink reg length to match the address/size-cells in k230-usb-phy yaml.
- Move all PHY instance creation and initialization from xlate to probe.
- Modify xlate function to only perform index lookup for PHY instances.
- Define all register base offsets macros at the top of file instead of
hard-coding magic numbers directly in probe.
- Link to v2: https://lore.kernel.org/all/20260115064223.21926-1-jiayu.riscv@isrc.iscas.ac.cn/
Changes in v3:
- Please ignore v3.
Changes in v2:
- Fold the child into the parent in dtsi.
- Define one usbphy with phy-cells=1.
- Delete the clock of the usbphy as it is not needed.
- Link to v1: https://lore.kernel.org/all/20251230023725.15966-1-jiayu.riscv@isrc.iscas.ac.cn/
Jiayu Du (4):
dt-bindings: phy: Add Canaan K230 USB PHY
dt-bindings: usb: dwc2: Add support for Canaan K230 SoC
phy: usb: Add driver for Canaan K230 USB 2.0 PHY
riscv: dts: canaan: Add syscon and USB nodes for K230
.../bindings/phy/canaan,k230-usb-phy.yaml | 35 +++
.../devicetree/bindings/usb/dwc2.yaml | 3 +
.../boot/dts/canaan/k230-canmv-dshanpi.dts | 17 ++
arch/riscv/boot/dts/canaan/k230.dtsi | 35 +++
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/canaan/Kconfig | 14 +
drivers/phy/canaan/Makefile | 2 +
drivers/phy/canaan/phy-k230-usb.c | 284 ++++++++++++++++++
9 files changed, 392 insertions(+)
create mode 100644 Documentation/devicetree/bindings/phy/canaan,k230-usb-phy.yaml
create mode 100644 drivers/phy/canaan/Kconfig
create mode 100644 drivers/phy/canaan/Makefile
create mode 100644 drivers/phy/canaan/phy-k230-usb.c
--
2.52.0
| null | null | null | [PATCH v5 0/4] Add USB support for Canaan K230 | On Wed, 21 Jan 2026 22:55:21 +0800, Jiayu Du wrote:
Applied, thanks!
[1/4] dt-bindings: phy: Add Canaan K230 USB PHY
commit: 50357e7d7992ba8f02c87ff7a5c4db17918635da
[3/4] phy: usb: Add driver for Canaan K230 USB 2.0 PHY
commit: 8787fa1da603e9e51efff11841e97b5d374aef34
Best regards,
--
~Vinod | {
"author": "Vinod Koul <vkoul@kernel.org>",
"date": "Fri, 27 Feb 2026 20:59:12 +0530",
"is_openbsd": false,
"thread_id": "177220615264.330302.188095105582835535.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Use dev_err_probe() consistently in the probe path of several ADI IIO
drivers. This simplifies error handling and ensures proper logging of
deferred probes.
Each driver is updated in two patches: first introducing a local
struct device *dev variable alongside the existing spi variable to
replace &spi->dev references in non-error paths, then converting
dev_err() error paths to use dev_err_probe().
Drivers updated:
- adrf6780
- admv1014
- admv1013
- adf4377
- ad7293
- admv8818
Changes in v4:
- Split each driver update back into two separate patches: one for
introducing the struct device variable and one for the dev_err_probe()
conversion. No lines are edited twice cross patch pairs, error-only
functions get dev introduced in the "use dev_err_probe" commit.
Antoniu Miclaus (12):
iio: frequency: adrf6780: add dev variable
iio: frequency: adrf6780: use dev_err_probe
iio: frequency: admv1014: add dev variable
iio: frequency: admv1014: use dev_err_probe
iio: frequency: admv1013: add dev variable
iio: frequency: admv1013: use dev_err_probe
iio: frequency: adf4377: add dev variable
iio: frequency: adf4377: use dev_err_probe
iio: dac: ad7293: add dev variable
iio: dac: ad7293: use dev_err_probe
iio: filter: admv8818: add dev variable
iio: filter: admv8818: use dev_err_probe
drivers/iio/dac/ad7293.c | 31 ++++++-----
drivers/iio/filter/admv8818.c | 56 +++++++++-----------
drivers/iio/frequency/adf4377.c | 56 ++++++++++----------
drivers/iio/frequency/admv1013.c | 43 +++++++--------
drivers/iio/frequency/admv1014.c | 89 ++++++++++++++------------------
drivers/iio/frequency/adrf6780.c | 60 +++++++++++----------
6 files changed, 155 insertions(+), 180 deletions(-)
--
2.43.0
| null | null | null | [PATCH v4 00/12] iio: use dev_err_probe in probe path for ADI drivers | Use dev_err_probe() consistently in the probe path to simplify error
handling and ensure deferred probes are logged correctly.
Signed-off-by: Antoniu Miclaus <antoniu.miclaus@analog.com>
---
drivers/iio/frequency/adrf6780.c | 25 +++++++++++--------------
1 file changed, 11 insertions(+), 14 deletions(-)
diff --git a/drivers/iio/frequency/adrf6780.c b/drivers/iio/frequency/adrf6780.c
index 1899995f7b20..257fd31a0b0e 100644
--- a/drivers/iio/frequency/adrf6780.c
+++ b/drivers/iio/frequency/adrf6780.c
@@ -346,23 +346,21 @@ static const struct iio_chan_spec adrf6780_channels[] = {
static int adrf6780_reset(struct adrf6780_state *st)
{
int ret;
- struct spi_device *spi = st->spi;
+ struct device *dev = &st->spi->dev;
ret = __adrf6780_spi_update_bits(st, ADRF6780_REG_CONTROL,
ADRF6780_SOFT_RESET_MSK,
FIELD_PREP(ADRF6780_SOFT_RESET_MSK, 1));
- if (ret) {
- dev_err(&spi->dev, "ADRF6780 SPI software reset failed.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret,
+ "ADRF6780 SPI software reset failed.\n");
ret = __adrf6780_spi_update_bits(st, ADRF6780_REG_CONTROL,
ADRF6780_SOFT_RESET_MSK,
FIELD_PREP(ADRF6780_SOFT_RESET_MSK, 0));
- if (ret) {
- dev_err(&spi->dev, "ADRF6780 SPI software reset disable failed.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret,
+ "ADRF6780 SPI software reset disable failed.\n");
return 0;
}
@@ -371,7 +369,7 @@ static int adrf6780_init(struct adrf6780_state *st)
{
int ret;
unsigned int chip_id, enable_reg, enable_reg_msk;
- struct spi_device *spi = st->spi;
+ struct device *dev = &st->spi->dev;
/* Perform a software reset */
ret = adrf6780_reset(st);
@@ -383,10 +381,9 @@ static int adrf6780_init(struct adrf6780_state *st)
return ret;
chip_id = FIELD_GET(ADRF6780_CHIP_ID_MSK, chip_id);
- if (chip_id != ADRF6780_CHIP_ID) {
- dev_err(&spi->dev, "ADRF6780 Invalid Chip ID.\n");
- return -EINVAL;
- }
+ if (chip_id != ADRF6780_CHIP_ID)
+ return dev_err_probe(dev, -EINVAL,
+ "ADRF6780 Invalid Chip ID.\n");
enable_reg_msk = ADRF6780_VGA_BUFFER_EN_MSK |
ADRF6780_DETECTOR_EN_MSK |
--
2.43.0 | {
"author": "Antoniu Miclaus <antoniu.miclaus@analog.com>",
"date": "Fri, 27 Feb 2026 16:01:31 +0200",
"is_openbsd": false,
"thread_id": "aaGyUMNzk9cNC5LG@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | Use dev_err_probe() consistently in the probe path of several ADI IIO
drivers. This simplifies error handling and ensures proper logging of
deferred probes.
Each driver is updated in two patches: first introducing a local
struct device *dev variable alongside the existing spi variable to
replace &spi->dev references in non-error paths, then converting
dev_err() error paths to use dev_err_probe().
Drivers updated:
- adrf6780
- admv1014
- admv1013
- adf4377
- ad7293
- admv8818
Changes in v4:
- Split each driver update back into two separate patches: one for
introducing the struct device variable and one for the dev_err_probe()
conversion. No lines are edited twice cross patch pairs, error-only
functions get dev introduced in the "use dev_err_probe" commit.
Antoniu Miclaus (12):
iio: frequency: adrf6780: add dev variable
iio: frequency: adrf6780: use dev_err_probe
iio: frequency: admv1014: add dev variable
iio: frequency: admv1014: use dev_err_probe
iio: frequency: admv1013: add dev variable
iio: frequency: admv1013: use dev_err_probe
iio: frequency: adf4377: add dev variable
iio: frequency: adf4377: use dev_err_probe
iio: dac: ad7293: add dev variable
iio: dac: ad7293: use dev_err_probe
iio: filter: admv8818: add dev variable
iio: filter: admv8818: use dev_err_probe
drivers/iio/dac/ad7293.c | 31 ++++++-----
drivers/iio/filter/admv8818.c | 56 +++++++++-----------
drivers/iio/frequency/adf4377.c | 56 ++++++++++----------
drivers/iio/frequency/admv1013.c | 43 +++++++--------
drivers/iio/frequency/admv1014.c | 89 ++++++++++++++------------------
drivers/iio/frequency/adrf6780.c | 60 +++++++++++----------
6 files changed, 155 insertions(+), 180 deletions(-)
--
2.43.0
| null | null | null | [PATCH v4 00/12] iio: use dev_err_probe in probe path for ADI drivers | Introduce a local struct device pointer in functions that reference
&spi->dev for device-managed resource calls and device property reads,
improving code readability.
Signed-off-by: Antoniu Miclaus <antoniu.miclaus@analog.com>
---
drivers/iio/frequency/adrf6780.c | 35 ++++++++++++++++----------------
1 file changed, 18 insertions(+), 17 deletions(-)
diff --git a/drivers/iio/frequency/adrf6780.c b/drivers/iio/frequency/adrf6780.c
index a7a21f929970..1899995f7b20 100644
--- a/drivers/iio/frequency/adrf6780.c
+++ b/drivers/iio/frequency/adrf6780.c
@@ -426,18 +426,18 @@ static int adrf6780_init(struct adrf6780_state *st)
static void adrf6780_properties_parse(struct adrf6780_state *st)
{
- struct spi_device *spi = st->spi;
-
- st->vga_buff_en = device_property_read_bool(&spi->dev, "adi,vga-buff-en");
- st->lo_buff_en = device_property_read_bool(&spi->dev, "adi,lo-buff-en");
- st->if_mode_en = device_property_read_bool(&spi->dev, "adi,if-mode-en");
- st->iq_mode_en = device_property_read_bool(&spi->dev, "adi,iq-mode-en");
- st->lo_x2_en = device_property_read_bool(&spi->dev, "adi,lo-x2-en");
- st->lo_ppf_en = device_property_read_bool(&spi->dev, "adi,lo-ppf-en");
- st->lo_en = device_property_read_bool(&spi->dev, "adi,lo-en");
- st->uc_bias_en = device_property_read_bool(&spi->dev, "adi,uc-bias-en");
- st->lo_sideband = device_property_read_bool(&spi->dev, "adi,lo-sideband");
- st->vdet_out_en = device_property_read_bool(&spi->dev, "adi,vdet-out-en");
+ struct device *dev = &st->spi->dev;
+
+ st->vga_buff_en = device_property_read_bool(dev, "adi,vga-buff-en");
+ st->lo_buff_en = device_property_read_bool(dev, "adi,lo-buff-en");
+ st->if_mode_en = device_property_read_bool(dev, "adi,if-mode-en");
+ st->iq_mode_en = device_property_read_bool(dev, "adi,iq-mode-en");
+ st->lo_x2_en = device_property_read_bool(dev, "adi,lo-x2-en");
+ st->lo_ppf_en = device_property_read_bool(dev, "adi,lo-ppf-en");
+ st->lo_en = device_property_read_bool(dev, "adi,lo-en");
+ st->uc_bias_en = device_property_read_bool(dev, "adi,uc-bias-en");
+ st->lo_sideband = device_property_read_bool(dev, "adi,lo-sideband");
+ st->vdet_out_en = device_property_read_bool(dev, "adi,vdet-out-en");
}
static void adrf6780_powerdown(void *data)
@@ -450,9 +450,10 @@ static int adrf6780_probe(struct spi_device *spi)
{
struct iio_dev *indio_dev;
struct adrf6780_state *st;
+ struct device *dev = &spi->dev;
int ret;
- indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
+ indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
if (!indio_dev)
return -ENOMEM;
@@ -467,9 +468,9 @@ static int adrf6780_probe(struct spi_device *spi)
adrf6780_properties_parse(st);
- st->clkin = devm_clk_get_enabled(&spi->dev, "lo_in");
+ st->clkin = devm_clk_get_enabled(dev, "lo_in");
if (IS_ERR(st->clkin))
- return dev_err_probe(&spi->dev, PTR_ERR(st->clkin),
+ return dev_err_probe(dev, PTR_ERR(st->clkin),
"failed to get the LO input clock\n");
mutex_init(&st->lock);
@@ -478,11 +479,11 @@ static int adrf6780_probe(struct spi_device *spi)
if (ret)
return ret;
- ret = devm_add_action_or_reset(&spi->dev, adrf6780_powerdown, st);
+ ret = devm_add_action_or_reset(dev, adrf6780_powerdown, st);
if (ret)
return ret;
- return devm_iio_device_register(&spi->dev, indio_dev);
+ return devm_iio_device_register(dev, indio_dev);
}
static const struct spi_device_id adrf6780_id[] = {
--
2.43.0 | {
"author": "Antoniu Miclaus <antoniu.miclaus@analog.com>",
"date": "Fri, 27 Feb 2026 16:01:30 +0200",
"is_openbsd": false,
"thread_id": "aaGyUMNzk9cNC5LG@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | Use dev_err_probe() consistently in the probe path of several ADI IIO
drivers. This simplifies error handling and ensures proper logging of
deferred probes.
Each driver is updated in two patches: first introducing a local
struct device *dev variable alongside the existing spi variable to
replace &spi->dev references in non-error paths, then converting
dev_err() error paths to use dev_err_probe().
Drivers updated:
- adrf6780
- admv1014
- admv1013
- adf4377
- ad7293
- admv8818
Changes in v4:
- Split each driver update back into two separate patches: one for
introducing the struct device variable and one for the dev_err_probe()
conversion. No lines are edited twice cross patch pairs, error-only
functions get dev introduced in the "use dev_err_probe" commit.
Antoniu Miclaus (12):
iio: frequency: adrf6780: add dev variable
iio: frequency: adrf6780: use dev_err_probe
iio: frequency: admv1014: add dev variable
iio: frequency: admv1014: use dev_err_probe
iio: frequency: admv1013: add dev variable
iio: frequency: admv1013: use dev_err_probe
iio: frequency: adf4377: add dev variable
iio: frequency: adf4377: use dev_err_probe
iio: dac: ad7293: add dev variable
iio: dac: ad7293: use dev_err_probe
iio: filter: admv8818: add dev variable
iio: filter: admv8818: use dev_err_probe
drivers/iio/dac/ad7293.c | 31 ++++++-----
drivers/iio/filter/admv8818.c | 56 +++++++++-----------
drivers/iio/frequency/adf4377.c | 56 ++++++++++----------
drivers/iio/frequency/admv1013.c | 43 +++++++--------
drivers/iio/frequency/admv1014.c | 89 ++++++++++++++------------------
drivers/iio/frequency/adrf6780.c | 60 +++++++++++----------
6 files changed, 155 insertions(+), 180 deletions(-)
--
2.43.0
| null | null | null | [PATCH v4 00/12] iio: use dev_err_probe in probe path for ADI drivers | Introduce a local struct device pointer in functions that reference
&spi->dev for device-managed resource calls and device property reads,
improving code readability.
Signed-off-by: Antoniu Miclaus <antoniu.miclaus@analog.com>
---
drivers/iio/frequency/admv1014.c | 29 ++++++++++++++++-------------
1 file changed, 16 insertions(+), 13 deletions(-)
diff --git a/drivers/iio/frequency/admv1014.c b/drivers/iio/frequency/admv1014.c
index 7a8f92ec80a2..f829c4595df3 100644
--- a/drivers/iio/frequency/admv1014.c
+++ b/drivers/iio/frequency/admv1014.c
@@ -610,6 +610,7 @@ static int admv1014_init(struct admv1014_state *st)
{
unsigned int chip_id, enable_reg, enable_reg_msk;
struct spi_device *spi = st->spi;
+ struct device *dev = &spi->dev;
int ret;
ret = regulator_bulk_enable(ADMV1014_NUM_REGULATORS, st->regulators);
@@ -618,7 +619,7 @@ static int admv1014_init(struct admv1014_state *st)
return ret;
}
- ret = devm_add_action_or_reset(&spi->dev, admv1014_reg_disable, st->regulators);
+ ret = devm_add_action_or_reset(dev, admv1014_reg_disable, st->regulators);
if (ret)
return ret;
@@ -626,16 +627,16 @@ static int admv1014_init(struct admv1014_state *st)
if (ret)
return ret;
- ret = devm_add_action_or_reset(&spi->dev, admv1014_clk_disable, st->clkin);
+ ret = devm_add_action_or_reset(dev, admv1014_clk_disable, st->clkin);
if (ret)
return ret;
st->nb.notifier_call = admv1014_freq_change;
- ret = devm_clk_notifier_register(&spi->dev, st->clkin, &st->nb);
+ ret = devm_clk_notifier_register(dev, st->clkin, &st->nb);
if (ret)
return ret;
- ret = devm_add_action_or_reset(&spi->dev, admv1014_powerdown, st);
+ ret = devm_add_action_or_reset(dev, admv1014_powerdown, st);
if (ret)
return ret;
@@ -712,13 +713,14 @@ static int admv1014_properties_parse(struct admv1014_state *st)
{
unsigned int i;
struct spi_device *spi = st->spi;
+ struct device *dev = &spi->dev;
int ret;
- st->det_en = device_property_read_bool(&spi->dev, "adi,detector-enable");
+ st->det_en = device_property_read_bool(dev, "adi,detector-enable");
- st->p1db_comp = device_property_read_bool(&spi->dev, "adi,p1db-compensation-enable");
+ st->p1db_comp = device_property_read_bool(dev, "adi,p1db-compensation-enable");
- ret = device_property_match_property_string(&spi->dev, "adi,input-mode",
+ ret = device_property_match_property_string(dev, "adi,input-mode",
input_mode_names,
ARRAY_SIZE(input_mode_names));
if (ret >= 0)
@@ -726,7 +728,7 @@ static int admv1014_properties_parse(struct admv1014_state *st)
else
st->input_mode = ADMV1014_IQ_MODE;
- ret = device_property_match_property_string(&spi->dev, "adi,quad-se-mode",
+ ret = device_property_match_property_string(dev, "adi,quad-se-mode",
quad_se_mode_names,
ARRAY_SIZE(quad_se_mode_names));
if (ret >= 0)
@@ -737,16 +739,16 @@ static int admv1014_properties_parse(struct admv1014_state *st)
for (i = 0; i < ADMV1014_NUM_REGULATORS; ++i)
st->regulators[i].supply = admv1014_reg_name[i];
- ret = devm_regulator_bulk_get(&st->spi->dev, ADMV1014_NUM_REGULATORS,
+ ret = devm_regulator_bulk_get(dev, ADMV1014_NUM_REGULATORS,
st->regulators);
if (ret) {
dev_err(&spi->dev, "Failed to request regulators");
return ret;
}
- st->clkin = devm_clk_get(&spi->dev, "lo_in");
+ st->clkin = devm_clk_get(dev, "lo_in");
if (IS_ERR(st->clkin))
- return dev_err_probe(&spi->dev, PTR_ERR(st->clkin),
+ return dev_err_probe(dev, PTR_ERR(st->clkin),
"failed to get the LO input clock\n");
return 0;
@@ -756,9 +758,10 @@ static int admv1014_probe(struct spi_device *spi)
{
struct iio_dev *indio_dev;
struct admv1014_state *st;
+ struct device *dev = &spi->dev;
int ret;
- indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
+ indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
if (!indio_dev)
return -ENOMEM;
@@ -787,7 +790,7 @@ static int admv1014_probe(struct spi_device *spi)
if (ret)
return ret;
- return devm_iio_device_register(&spi->dev, indio_dev);
+ return devm_iio_device_register(dev, indio_dev);
}
static const struct spi_device_id admv1014_id[] = {
--
2.43.0 | {
"author": "Antoniu Miclaus <antoniu.miclaus@analog.com>",
"date": "Fri, 27 Feb 2026 16:01:32 +0200",
"is_openbsd": false,
"thread_id": "aaGyUMNzk9cNC5LG@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | Use dev_err_probe() consistently in the probe path of several ADI IIO
drivers. This simplifies error handling and ensures proper logging of
deferred probes.
Each driver is updated in two patches: first introducing a local
struct device *dev variable alongside the existing spi variable to
replace &spi->dev references in non-error paths, then converting
dev_err() error paths to use dev_err_probe().
Drivers updated:
- adrf6780
- admv1014
- admv1013
- adf4377
- ad7293
- admv8818
Changes in v4:
- Split each driver update back into two separate patches: one for
introducing the struct device variable and one for the dev_err_probe()
conversion. No lines are edited twice cross patch pairs, error-only
functions get dev introduced in the "use dev_err_probe" commit.
Antoniu Miclaus (12):
iio: frequency: adrf6780: add dev variable
iio: frequency: adrf6780: use dev_err_probe
iio: frequency: admv1014: add dev variable
iio: frequency: admv1014: use dev_err_probe
iio: frequency: admv1013: add dev variable
iio: frequency: admv1013: use dev_err_probe
iio: frequency: adf4377: add dev variable
iio: frequency: adf4377: use dev_err_probe
iio: dac: ad7293: add dev variable
iio: dac: ad7293: use dev_err_probe
iio: filter: admv8818: add dev variable
iio: filter: admv8818: use dev_err_probe
drivers/iio/dac/ad7293.c | 31 ++++++-----
drivers/iio/filter/admv8818.c | 56 +++++++++-----------
drivers/iio/frequency/adf4377.c | 56 ++++++++++----------
drivers/iio/frequency/admv1013.c | 43 +++++++--------
drivers/iio/frequency/admv1014.c | 89 ++++++++++++++------------------
drivers/iio/frequency/adrf6780.c | 60 +++++++++++----------
6 files changed, 155 insertions(+), 180 deletions(-)
--
2.43.0
| null | null | null | [PATCH v4 00/12] iio: use dev_err_probe in probe path for ADI drivers | Use dev_err_probe() consistently in the probe path to simplify error
handling and ensure deferred probes are logged correctly.
Signed-off-by: Antoniu Miclaus <antoniu.miclaus@analog.com>
---
drivers/iio/frequency/admv1014.c | 60 +++++++++++++-------------------
1 file changed, 24 insertions(+), 36 deletions(-)
diff --git a/drivers/iio/frequency/admv1014.c b/drivers/iio/frequency/admv1014.c
index f829c4595df3..25e8cd8135ad 100644
--- a/drivers/iio/frequency/admv1014.c
+++ b/drivers/iio/frequency/admv1014.c
@@ -614,10 +614,8 @@ static int admv1014_init(struct admv1014_state *st)
int ret;
ret = regulator_bulk_enable(ADMV1014_NUM_REGULATORS, st->regulators);
- if (ret) {
- dev_err(&spi->dev, "Failed to enable regulators");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret, "Failed to enable regulators");
ret = devm_add_action_or_reset(dev, admv1014_reg_disable, st->regulators);
if (ret)
@@ -644,55 +642,47 @@ static int admv1014_init(struct admv1014_state *st)
ret = __admv1014_spi_update_bits(st, ADMV1014_REG_SPI_CONTROL,
ADMV1014_SPI_SOFT_RESET_MSK,
FIELD_PREP(ADMV1014_SPI_SOFT_RESET_MSK, 1));
- if (ret) {
- dev_err(&spi->dev, "ADMV1014 SPI software reset failed.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret,
+ "ADMV1014 SPI software reset failed.\n");
ret = __admv1014_spi_update_bits(st, ADMV1014_REG_SPI_CONTROL,
ADMV1014_SPI_SOFT_RESET_MSK,
FIELD_PREP(ADMV1014_SPI_SOFT_RESET_MSK, 0));
- if (ret) {
- dev_err(&spi->dev, "ADMV1014 SPI software reset disable failed.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret,
+ "ADMV1014 SPI software reset disable failed.\n");
ret = __admv1014_spi_write(st, ADMV1014_REG_VVA_TEMP_COMP, 0x727C);
- if (ret) {
- dev_err(&spi->dev, "Writing default Temperature Compensation value failed.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret,
+ "Writing default Temperature Compensation value failed.\n");
ret = __admv1014_spi_read(st, ADMV1014_REG_SPI_CONTROL, &chip_id);
if (ret)
return ret;
chip_id = FIELD_GET(ADMV1014_CHIP_ID_MSK, chip_id);
- if (chip_id != ADMV1014_CHIP_ID) {
- dev_err(&spi->dev, "Invalid Chip ID.\n");
- return -EINVAL;
- }
+ if (chip_id != ADMV1014_CHIP_ID)
+ return dev_err_probe(dev, -EINVAL, "Invalid Chip ID.\n");
ret = __admv1014_spi_update_bits(st, ADMV1014_REG_QUAD,
ADMV1014_QUAD_SE_MODE_MSK,
FIELD_PREP(ADMV1014_QUAD_SE_MODE_MSK,
st->quad_se_mode));
- if (ret) {
- dev_err(&spi->dev, "Writing Quad SE Mode failed.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret,
+ "Writing Quad SE Mode failed.\n");
ret = admv1014_update_quad_filters(st);
- if (ret) {
- dev_err(&spi->dev, "Update Quad Filters failed.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret,
+ "Update Quad Filters failed.\n");
ret = admv1014_update_vcm_settings(st);
- if (ret) {
- dev_err(&spi->dev, "Update VCM Settings failed.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret,
+ "Update VCM Settings failed.\n");
enable_reg_msk = ADMV1014_P1DB_COMPENSATION_MSK |
ADMV1014_IF_AMP_PD_MSK |
@@ -741,10 +731,8 @@ static int admv1014_properties_parse(struct admv1014_state *st)
ret = devm_regulator_bulk_get(dev, ADMV1014_NUM_REGULATORS,
st->regulators);
- if (ret) {
- dev_err(&spi->dev, "Failed to request regulators");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret, "Failed to request regulators");
st->clkin = devm_clk_get(dev, "lo_in");
if (IS_ERR(st->clkin))
--
2.43.0 | {
"author": "Antoniu Miclaus <antoniu.miclaus@analog.com>",
"date": "Fri, 27 Feb 2026 16:01:33 +0200",
"is_openbsd": false,
"thread_id": "aaGyUMNzk9cNC5LG@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | Use dev_err_probe() consistently in the probe path of several ADI IIO
drivers. This simplifies error handling and ensures proper logging of
deferred probes.
Each driver is updated in two patches: first introducing a local
struct device *dev variable alongside the existing spi variable to
replace &spi->dev references in non-error paths, then converting
dev_err() error paths to use dev_err_probe().
Drivers updated:
- adrf6780
- admv1014
- admv1013
- adf4377
- ad7293
- admv8818
Changes in v4:
- Split each driver update back into two separate patches: one for
introducing the struct device variable and one for the dev_err_probe()
conversion. No lines are edited twice cross patch pairs, error-only
functions get dev introduced in the "use dev_err_probe" commit.
Antoniu Miclaus (12):
iio: frequency: adrf6780: add dev variable
iio: frequency: adrf6780: use dev_err_probe
iio: frequency: admv1014: add dev variable
iio: frequency: admv1014: use dev_err_probe
iio: frequency: admv1013: add dev variable
iio: frequency: admv1013: use dev_err_probe
iio: frequency: adf4377: add dev variable
iio: frequency: adf4377: use dev_err_probe
iio: dac: ad7293: add dev variable
iio: dac: ad7293: use dev_err_probe
iio: filter: admv8818: add dev variable
iio: filter: admv8818: use dev_err_probe
drivers/iio/dac/ad7293.c | 31 ++++++-----
drivers/iio/filter/admv8818.c | 56 +++++++++-----------
drivers/iio/frequency/adf4377.c | 56 ++++++++++----------
drivers/iio/frequency/admv1013.c | 43 +++++++--------
drivers/iio/frequency/admv1014.c | 89 ++++++++++++++------------------
drivers/iio/frequency/adrf6780.c | 60 +++++++++++----------
6 files changed, 155 insertions(+), 180 deletions(-)
--
2.43.0
| null | null | null | [PATCH v4 00/12] iio: use dev_err_probe in probe path for ADI drivers | Introduce a local struct device pointer in functions that reference
&spi->dev for device-managed resource calls and device property reads,
improving code readability.
Signed-off-by: Antoniu Miclaus <antoniu.miclaus@analog.com>
---
drivers/iio/frequency/admv1013.c | 29 +++++++++++++++--------------
1 file changed, 15 insertions(+), 14 deletions(-)
diff --git a/drivers/iio/frequency/admv1013.c b/drivers/iio/frequency/admv1013.c
index d8e8d541990f..d29e288da011 100644
--- a/drivers/iio/frequency/admv1013.c
+++ b/drivers/iio/frequency/admv1013.c
@@ -518,11 +518,11 @@ static int admv1013_properties_parse(struct admv1013_state *st)
{
int ret;
const char *str;
- struct spi_device *spi = st->spi;
+ struct device *dev = &st->spi->dev;
- st->det_en = device_property_read_bool(&spi->dev, "adi,detector-enable");
+ st->det_en = device_property_read_bool(dev, "adi,detector-enable");
- ret = device_property_read_string(&spi->dev, "adi,input-mode", &str);
+ ret = device_property_read_string(dev, "adi,input-mode", &str);
if (ret)
st->input_mode = ADMV1013_IQ_MODE;
@@ -533,7 +533,7 @@ static int admv1013_properties_parse(struct admv1013_state *st)
else
return -EINVAL;
- ret = device_property_read_string(&spi->dev, "adi,quad-se-mode", &str);
+ ret = device_property_read_string(dev, "adi,quad-se-mode", &str);
if (ret)
st->quad_se_mode = ADMV1013_SE_MODE_DIFF;
@@ -546,11 +546,11 @@ static int admv1013_properties_parse(struct admv1013_state *st)
else
return -EINVAL;
- ret = devm_regulator_bulk_get_enable(&st->spi->dev,
+ ret = devm_regulator_bulk_get_enable(dev,
ARRAY_SIZE(admv1013_vcc_regs),
admv1013_vcc_regs);
if (ret) {
- dev_err_probe(&spi->dev, ret,
+ dev_err_probe(dev, ret,
"Failed to request VCC regulators\n");
return ret;
}
@@ -562,9 +562,10 @@ static int admv1013_probe(struct spi_device *spi)
{
struct iio_dev *indio_dev;
struct admv1013_state *st;
+ struct device *dev = &spi->dev;
int ret, vcm_uv;
- indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
+ indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
if (!indio_dev)
return -ENOMEM;
@@ -581,20 +582,20 @@ static int admv1013_probe(struct spi_device *spi)
if (ret)
return ret;
- ret = devm_regulator_get_enable_read_voltage(&spi->dev, "vcm");
+ ret = devm_regulator_get_enable_read_voltage(dev, "vcm");
if (ret < 0)
- return dev_err_probe(&spi->dev, ret,
+ return dev_err_probe(dev, ret,
"failed to get the common-mode voltage\n");
vcm_uv = ret;
- st->clkin = devm_clk_get_enabled(&spi->dev, "lo_in");
+ st->clkin = devm_clk_get_enabled(dev, "lo_in");
if (IS_ERR(st->clkin))
- return dev_err_probe(&spi->dev, PTR_ERR(st->clkin),
+ return dev_err_probe(dev, PTR_ERR(st->clkin),
"failed to get the LO input clock\n");
st->nb.notifier_call = admv1013_freq_change;
- ret = devm_clk_notifier_register(&spi->dev, st->clkin, &st->nb);
+ ret = devm_clk_notifier_register(dev, st->clkin, &st->nb);
if (ret)
return ret;
@@ -606,11 +607,11 @@ static int admv1013_probe(struct spi_device *spi)
return ret;
}
- ret = devm_add_action_or_reset(&spi->dev, admv1013_powerdown, st);
+ ret = devm_add_action_or_reset(dev, admv1013_powerdown, st);
if (ret)
return ret;
- return devm_iio_device_register(&spi->dev, indio_dev);
+ return devm_iio_device_register(dev, indio_dev);
}
static const struct spi_device_id admv1013_id[] = {
--
2.43.0 | {
"author": "Antoniu Miclaus <antoniu.miclaus@analog.com>",
"date": "Fri, 27 Feb 2026 16:01:34 +0200",
"is_openbsd": false,
"thread_id": "aaGyUMNzk9cNC5LG@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | Use dev_err_probe() consistently in the probe path of several ADI IIO
drivers. This simplifies error handling and ensures proper logging of
deferred probes.
Each driver is updated in two patches: first introducing a local
struct device *dev variable alongside the existing spi variable to
replace &spi->dev references in non-error paths, then converting
dev_err() error paths to use dev_err_probe().
Drivers updated:
- adrf6780
- admv1014
- admv1013
- adf4377
- ad7293
- admv8818
Changes in v4:
- Split each driver update back into two separate patches: one for
introducing the struct device variable and one for the dev_err_probe()
conversion. No lines are edited twice cross patch pairs, error-only
functions get dev introduced in the "use dev_err_probe" commit.
Antoniu Miclaus (12):
iio: frequency: adrf6780: add dev variable
iio: frequency: adrf6780: use dev_err_probe
iio: frequency: admv1014: add dev variable
iio: frequency: admv1014: use dev_err_probe
iio: frequency: admv1013: add dev variable
iio: frequency: admv1013: use dev_err_probe
iio: frequency: adf4377: add dev variable
iio: frequency: adf4377: use dev_err_probe
iio: dac: ad7293: add dev variable
iio: dac: ad7293: use dev_err_probe
iio: filter: admv8818: add dev variable
iio: filter: admv8818: use dev_err_probe
drivers/iio/dac/ad7293.c | 31 ++++++-----
drivers/iio/filter/admv8818.c | 56 +++++++++-----------
drivers/iio/frequency/adf4377.c | 56 ++++++++++----------
drivers/iio/frequency/admv1013.c | 43 +++++++--------
drivers/iio/frequency/admv1014.c | 89 ++++++++++++++------------------
drivers/iio/frequency/adrf6780.c | 60 +++++++++++----------
6 files changed, 155 insertions(+), 180 deletions(-)
--
2.43.0
| null | null | null | [PATCH v4 00/12] iio: use dev_err_probe in probe path for ADI drivers | Use dev_err_probe() consistently in the probe path to simplify error
handling and ensure deferred probes are logged correctly.
Signed-off-by: Antoniu Miclaus <antoniu.miclaus@analog.com>
---
drivers/iio/frequency/admv1013.c | 14 +++++---------
1 file changed, 5 insertions(+), 9 deletions(-)
diff --git a/drivers/iio/frequency/admv1013.c b/drivers/iio/frequency/admv1013.c
index d29e288da011..9202443ef445 100644
--- a/drivers/iio/frequency/admv1013.c
+++ b/drivers/iio/frequency/admv1013.c
@@ -441,7 +441,7 @@ static int admv1013_init(struct admv1013_state *st, int vcm_uv)
{
int ret;
unsigned int data;
- struct spi_device *spi = st->spi;
+ struct device *dev = &st->spi->dev;
/* Perform a software reset */
ret = __admv1013_spi_update_bits(st, ADMV1013_REG_SPI_CONTROL,
@@ -461,10 +461,8 @@ static int admv1013_init(struct admv1013_state *st, int vcm_uv)
return ret;
data = FIELD_GET(ADMV1013_CHIP_ID_MSK, data);
- if (data != ADMV1013_CHIP_ID) {
- dev_err(&spi->dev, "Invalid Chip ID.\n");
- return -EINVAL;
- }
+ if (data != ADMV1013_CHIP_ID)
+ return dev_err_probe(dev, -EINVAL, "Invalid Chip ID.\n");
ret = __admv1013_spi_write(st, ADMV1013_REG_VVA_TEMP_COMP, 0xE700);
if (ret)
@@ -602,10 +600,8 @@ static int admv1013_probe(struct spi_device *spi)
mutex_init(&st->lock);
ret = admv1013_init(st, vcm_uv);
- if (ret) {
- dev_err(&spi->dev, "admv1013 init failed\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret, "admv1013 init failed\n");
ret = devm_add_action_or_reset(dev, admv1013_powerdown, st);
if (ret)
--
2.43.0 | {
"author": "Antoniu Miclaus <antoniu.miclaus@analog.com>",
"date": "Fri, 27 Feb 2026 16:01:35 +0200",
"is_openbsd": false,
"thread_id": "aaGyUMNzk9cNC5LG@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | Use dev_err_probe() consistently in the probe path of several ADI IIO
drivers. This simplifies error handling and ensures proper logging of
deferred probes.
Each driver is updated in two patches: first introducing a local
struct device *dev variable alongside the existing spi variable to
replace &spi->dev references in non-error paths, then converting
dev_err() error paths to use dev_err_probe().
Drivers updated:
- adrf6780
- admv1014
- admv1013
- adf4377
- ad7293
- admv8818
Changes in v4:
- Split each driver update back into two separate patches: one for
introducing the struct device variable and one for the dev_err_probe()
conversion. No lines are edited twice cross patch pairs, error-only
functions get dev introduced in the "use dev_err_probe" commit.
Antoniu Miclaus (12):
iio: frequency: adrf6780: add dev variable
iio: frequency: adrf6780: use dev_err_probe
iio: frequency: admv1014: add dev variable
iio: frequency: admv1014: use dev_err_probe
iio: frequency: admv1013: add dev variable
iio: frequency: admv1013: use dev_err_probe
iio: frequency: adf4377: add dev variable
iio: frequency: adf4377: use dev_err_probe
iio: dac: ad7293: add dev variable
iio: dac: ad7293: use dev_err_probe
iio: filter: admv8818: add dev variable
iio: filter: admv8818: use dev_err_probe
drivers/iio/dac/ad7293.c | 31 ++++++-----
drivers/iio/filter/admv8818.c | 56 +++++++++-----------
drivers/iio/frequency/adf4377.c | 56 ++++++++++----------
drivers/iio/frequency/admv1013.c | 43 +++++++--------
drivers/iio/frequency/admv1014.c | 89 ++++++++++++++------------------
drivers/iio/frequency/adrf6780.c | 60 +++++++++++----------
6 files changed, 155 insertions(+), 180 deletions(-)
--
2.43.0
| null | null | null | [PATCH v4 00/12] iio: use dev_err_probe in probe path for ADI drivers | Introduce a local struct device pointer in functions that reference
&spi->dev for device-managed resource calls and device property reads,
improving code readability.
Signed-off-by: Antoniu Miclaus <antoniu.miclaus@analog.com>
---
drivers/iio/frequency/adf4377.c | 27 ++++++++++++++-------------
1 file changed, 14 insertions(+), 13 deletions(-)
diff --git a/drivers/iio/frequency/adf4377.c b/drivers/iio/frequency/adf4377.c
index fa686f785fa4..c2ae6f2012ce 100644
--- a/drivers/iio/frequency/adf4377.c
+++ b/drivers/iio/frequency/adf4377.c
@@ -882,35 +882,35 @@ static const struct iio_chan_spec adf4377_channels[] = {
static int adf4377_properties_parse(struct adf4377_state *st)
{
- struct spi_device *spi = st->spi;
+ struct device *dev = &st->spi->dev;
int ret;
- st->clkin = devm_clk_get_enabled(&spi->dev, "ref_in");
+ st->clkin = devm_clk_get_enabled(dev, "ref_in");
if (IS_ERR(st->clkin))
- return dev_err_probe(&spi->dev, PTR_ERR(st->clkin),
+ return dev_err_probe(dev, PTR_ERR(st->clkin),
"failed to get the reference input clock\n");
- st->gpio_ce = devm_gpiod_get_optional(&st->spi->dev, "chip-enable",
+ st->gpio_ce = devm_gpiod_get_optional(dev, "chip-enable",
GPIOD_OUT_LOW);
if (IS_ERR(st->gpio_ce))
- return dev_err_probe(&spi->dev, PTR_ERR(st->gpio_ce),
+ return dev_err_probe(dev, PTR_ERR(st->gpio_ce),
"failed to get the CE GPIO\n");
- st->gpio_enclk1 = devm_gpiod_get_optional(&st->spi->dev, "clk1-enable",
+ st->gpio_enclk1 = devm_gpiod_get_optional(dev, "clk1-enable",
GPIOD_OUT_LOW);
if (IS_ERR(st->gpio_enclk1))
- return dev_err_probe(&spi->dev, PTR_ERR(st->gpio_enclk1),
+ return dev_err_probe(dev, PTR_ERR(st->gpio_enclk1),
"failed to get the CE GPIO\n");
if (st->chip_info->has_gpio_enclk2) {
- st->gpio_enclk2 = devm_gpiod_get_optional(&st->spi->dev, "clk2-enable",
+ st->gpio_enclk2 = devm_gpiod_get_optional(dev, "clk2-enable",
GPIOD_OUT_LOW);
if (IS_ERR(st->gpio_enclk2))
- return dev_err_probe(&spi->dev, PTR_ERR(st->gpio_enclk2),
+ return dev_err_probe(dev, PTR_ERR(st->gpio_enclk2),
"failed to get the CE GPIO\n");
}
- ret = device_property_match_property_string(&spi->dev, "adi,muxout-select",
+ ret = device_property_match_property_string(dev, "adi,muxout-select",
adf4377_muxout_modes,
ARRAY_SIZE(adf4377_muxout_modes));
if (ret >= 0)
@@ -1055,9 +1055,10 @@ static int adf4377_probe(struct spi_device *spi)
struct iio_dev *indio_dev;
struct regmap *regmap;
struct adf4377_state *st;
+ struct device *dev = &spi->dev;
int ret;
- indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
+ indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
if (!indio_dev)
return -ENOMEM;
@@ -1080,7 +1081,7 @@ static int adf4377_probe(struct spi_device *spi)
return ret;
st->nb.notifier_call = adf4377_freq_change;
- ret = devm_clk_notifier_register(&spi->dev, st->clkin, &st->nb);
+ ret = devm_clk_notifier_register(dev, st->clkin, &st->nb);
if (ret)
return ret;
@@ -1097,7 +1098,7 @@ static int adf4377_probe(struct spi_device *spi)
indio_dev->num_channels = ARRAY_SIZE(adf4377_channels);
}
- return devm_iio_device_register(&spi->dev, indio_dev);
+ return devm_iio_device_register(dev, indio_dev);
}
static const struct spi_device_id adf4377_id[] = {
--
2.43.0 | {
"author": "Antoniu Miclaus <antoniu.miclaus@analog.com>",
"date": "Fri, 27 Feb 2026 16:01:36 +0200",
"is_openbsd": false,
"thread_id": "aaGyUMNzk9cNC5LG@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | Use dev_err_probe() consistently in the probe path of several ADI IIO
drivers. This simplifies error handling and ensures proper logging of
deferred probes.
Each driver is updated in two patches: first introducing a local
struct device *dev variable alongside the existing spi variable to
replace &spi->dev references in non-error paths, then converting
dev_err() error paths to use dev_err_probe().
Drivers updated:
- adrf6780
- admv1014
- admv1013
- adf4377
- ad7293
- admv8818
Changes in v4:
- Split each driver update back into two separate patches: one for
introducing the struct device variable and one for the dev_err_probe()
conversion. No lines are edited twice cross patch pairs, error-only
functions get dev introduced in the "use dev_err_probe" commit.
Antoniu Miclaus (12):
iio: frequency: adrf6780: add dev variable
iio: frequency: adrf6780: use dev_err_probe
iio: frequency: admv1014: add dev variable
iio: frequency: admv1014: use dev_err_probe
iio: frequency: admv1013: add dev variable
iio: frequency: admv1013: use dev_err_probe
iio: frequency: adf4377: add dev variable
iio: frequency: adf4377: use dev_err_probe
iio: dac: ad7293: add dev variable
iio: dac: ad7293: use dev_err_probe
iio: filter: admv8818: add dev variable
iio: filter: admv8818: use dev_err_probe
drivers/iio/dac/ad7293.c | 31 ++++++-----
drivers/iio/filter/admv8818.c | 56 +++++++++-----------
drivers/iio/frequency/adf4377.c | 56 ++++++++++----------
drivers/iio/frequency/admv1013.c | 43 +++++++--------
drivers/iio/frequency/admv1014.c | 89 ++++++++++++++------------------
drivers/iio/frequency/adrf6780.c | 60 +++++++++++----------
6 files changed, 155 insertions(+), 180 deletions(-)
--
2.43.0
| null | null | null | [PATCH v4 00/12] iio: use dev_err_probe in probe path for ADI drivers | Use dev_err_probe() consistently in the probe path to simplify error
handling and ensure deferred probes are logged correctly.
Signed-off-by: Antoniu Miclaus <antoniu.miclaus@analog.com>
---
drivers/iio/frequency/adf4377.c | 29 ++++++++++++-----------------
1 file changed, 12 insertions(+), 17 deletions(-)
diff --git a/drivers/iio/frequency/adf4377.c b/drivers/iio/frequency/adf4377.c
index c2ae6f2012ce..ce3a396624c3 100644
--- a/drivers/iio/frequency/adf4377.c
+++ b/drivers/iio/frequency/adf4377.c
@@ -706,23 +706,20 @@ static void adf4377_gpio_init(struct adf4377_state *st)
static int adf4377_init(struct adf4377_state *st)
{
- struct spi_device *spi = st->spi;
+ struct device *dev = &st->spi->dev;
int ret;
adf4377_gpio_init(st);
ret = adf4377_soft_reset(st);
- if (ret) {
- dev_err(&spi->dev, "Failed to soft reset.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret, "Failed to soft reset.\n");
ret = regmap_multi_reg_write(st->regmap, adf4377_reg_defaults,
ARRAY_SIZE(adf4377_reg_defaults));
- if (ret) {
- dev_err(&spi->dev, "Failed to set default registers.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret,
+ "Failed to set default registers.\n");
ret = regmap_update_bits(st->regmap, 0x00,
ADF4377_0000_SDO_ACTIVE_MSK | ADF4377_0000_SDO_ACTIVE_R_MSK,
@@ -730,10 +727,9 @@ static int adf4377_init(struct adf4377_state *st)
ADF4377_0000_SDO_ACTIVE_SPI_4W) |
FIELD_PREP(ADF4377_0000_SDO_ACTIVE_R_MSK,
ADF4377_0000_SDO_ACTIVE_SPI_4W));
- if (ret) {
- dev_err(&spi->dev, "Failed to set 4-Wire Operation.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret,
+ "Failed to set 4-Wire Operation.\n");
st->clkin_freq = clk_get_rate(st->clkin);
@@ -747,10 +743,9 @@ static int adf4377_init(struct adf4377_state *st)
FIELD_PREP(ADF4377_001A_PD_PFDCP_MSK, 0) |
FIELD_PREP(ADF4377_001A_PD_CLKOUT1_MSK, 0) |
FIELD_PREP(ADF4377_001A_PD_CLKOUT2_MSK, 0));
- if (ret) {
- dev_err(&spi->dev, "Failed to set power down registers.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret,
+ "Failed to set power down registers.\n");
/* Set Mux Output */
ret = regmap_update_bits(st->regmap, 0x1D,
--
2.43.0 | {
"author": "Antoniu Miclaus <antoniu.miclaus@analog.com>",
"date": "Fri, 27 Feb 2026 16:01:37 +0200",
"is_openbsd": false,
"thread_id": "aaGyUMNzk9cNC5LG@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | Use dev_err_probe() consistently in the probe path of several ADI IIO
drivers. This simplifies error handling and ensures proper logging of
deferred probes.
Each driver is updated in two patches: first introducing a local
struct device *dev variable alongside the existing spi variable to
replace &spi->dev references in non-error paths, then converting
dev_err() error paths to use dev_err_probe().
Drivers updated:
- adrf6780
- admv1014
- admv1013
- adf4377
- ad7293
- admv8818
Changes in v4:
- Split each driver update back into two separate patches: one for
introducing the struct device variable and one for the dev_err_probe()
conversion. No lines are edited twice cross patch pairs, error-only
functions get dev introduced in the "use dev_err_probe" commit.
Antoniu Miclaus (12):
iio: frequency: adrf6780: add dev variable
iio: frequency: adrf6780: use dev_err_probe
iio: frequency: admv1014: add dev variable
iio: frequency: admv1014: use dev_err_probe
iio: frequency: admv1013: add dev variable
iio: frequency: admv1013: use dev_err_probe
iio: frequency: adf4377: add dev variable
iio: frequency: adf4377: use dev_err_probe
iio: dac: ad7293: add dev variable
iio: dac: ad7293: use dev_err_probe
iio: filter: admv8818: add dev variable
iio: filter: admv8818: use dev_err_probe
drivers/iio/dac/ad7293.c | 31 ++++++-----
drivers/iio/filter/admv8818.c | 56 +++++++++-----------
drivers/iio/frequency/adf4377.c | 56 ++++++++++----------
drivers/iio/frequency/admv1013.c | 43 +++++++--------
drivers/iio/frequency/admv1014.c | 89 ++++++++++++++------------------
drivers/iio/frequency/adrf6780.c | 60 +++++++++++----------
6 files changed, 155 insertions(+), 180 deletions(-)
--
2.43.0
| null | null | null | [PATCH v4 00/12] iio: use dev_err_probe in probe path for ADI drivers | Use dev_err_probe() consistently in the probe path to simplify error
handling and ensure deferred probes are logged correctly.
Signed-off-by: Antoniu Miclaus <antoniu.miclaus@analog.com>
---
drivers/iio/dac/ad7293.c | 8 +++-----
1 file changed, 3 insertions(+), 5 deletions(-)
diff --git a/drivers/iio/dac/ad7293.c b/drivers/iio/dac/ad7293.c
index c86c54d53df1..df6f126abf05 100644
--- a/drivers/iio/dac/ad7293.c
+++ b/drivers/iio/dac/ad7293.c
@@ -806,7 +806,7 @@ static int ad7293_init(struct ad7293_state *st)
{
int ret;
u16 chip_id;
- struct spi_device *spi = st->spi;
+ struct device *dev = &st->spi->dev;
ret = ad7293_properties_parse(st);
if (ret)
@@ -821,10 +821,8 @@ static int ad7293_init(struct ad7293_state *st)
if (ret)
return ret;
- if (chip_id != AD7293_CHIP_ID) {
- dev_err(&spi->dev, "Invalid Chip ID.\n");
- return -EINVAL;
- }
+ if (chip_id != AD7293_CHIP_ID)
+ return dev_err_probe(dev, -EINVAL, "Invalid Chip ID.\n");
if (!st->vrefin_en)
return __ad7293_spi_update_bits(st, AD7293_REG_GENERAL,
--
2.43.0 | {
"author": "Antoniu Miclaus <antoniu.miclaus@analog.com>",
"date": "Fri, 27 Feb 2026 16:01:39 +0200",
"is_openbsd": false,
"thread_id": "aaGyUMNzk9cNC5LG@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | Use dev_err_probe() consistently in the probe path of several ADI IIO
drivers. This simplifies error handling and ensures proper logging of
deferred probes.
Each driver is updated in two patches: first introducing a local
struct device *dev variable alongside the existing spi variable to
replace &spi->dev references in non-error paths, then converting
dev_err() error paths to use dev_err_probe().
Drivers updated:
- adrf6780
- admv1014
- admv1013
- adf4377
- ad7293
- admv8818
Changes in v4:
- Split each driver update back into two separate patches: one for
introducing the struct device variable and one for the dev_err_probe()
conversion. No lines are edited twice cross patch pairs, error-only
functions get dev introduced in the "use dev_err_probe" commit.
Antoniu Miclaus (12):
iio: frequency: adrf6780: add dev variable
iio: frequency: adrf6780: use dev_err_probe
iio: frequency: admv1014: add dev variable
iio: frequency: admv1014: use dev_err_probe
iio: frequency: admv1013: add dev variable
iio: frequency: admv1013: use dev_err_probe
iio: frequency: adf4377: add dev variable
iio: frequency: adf4377: use dev_err_probe
iio: dac: ad7293: add dev variable
iio: dac: ad7293: use dev_err_probe
iio: filter: admv8818: add dev variable
iio: filter: admv8818: use dev_err_probe
drivers/iio/dac/ad7293.c | 31 ++++++-----
drivers/iio/filter/admv8818.c | 56 +++++++++-----------
drivers/iio/frequency/adf4377.c | 56 ++++++++++----------
drivers/iio/frequency/admv1013.c | 43 +++++++--------
drivers/iio/frequency/admv1014.c | 89 ++++++++++++++------------------
drivers/iio/frequency/adrf6780.c | 60 +++++++++++----------
6 files changed, 155 insertions(+), 180 deletions(-)
--
2.43.0
| null | null | null | [PATCH v4 00/12] iio: use dev_err_probe in probe path for ADI drivers | Introduce a local struct device pointer in functions that reference
&spi->dev for device-managed resource calls and device property reads,
improving code readability.
Signed-off-by: Antoniu Miclaus <antoniu.miclaus@analog.com>
---
drivers/iio/dac/ad7293.c | 23 ++++++++++++-----------
1 file changed, 12 insertions(+), 11 deletions(-)
diff --git a/drivers/iio/dac/ad7293.c b/drivers/iio/dac/ad7293.c
index c3797e40cdd9..c86c54d53df1 100644
--- a/drivers/iio/dac/ad7293.c
+++ b/drivers/iio/dac/ad7293.c
@@ -776,27 +776,27 @@ static int ad7293_reset(struct ad7293_state *st)
static int ad7293_properties_parse(struct ad7293_state *st)
{
- struct spi_device *spi = st->spi;
+ struct device *dev = &st->spi->dev;
int ret;
- ret = devm_regulator_get_enable(&spi->dev, "avdd");
+ ret = devm_regulator_get_enable(dev, "avdd");
if (ret)
- return dev_err_probe(&spi->dev, ret, "failed to enable AVDD\n");
+ return dev_err_probe(dev, ret, "failed to enable AVDD\n");
- ret = devm_regulator_get_enable(&spi->dev, "vdrive");
+ ret = devm_regulator_get_enable(dev, "vdrive");
if (ret)
- return dev_err_probe(&spi->dev, ret, "failed to enable VDRIVE\n");
+ return dev_err_probe(dev, ret, "failed to enable VDRIVE\n");
- ret = devm_regulator_get_enable_optional(&spi->dev, "vrefin");
+ ret = devm_regulator_get_enable_optional(dev, "vrefin");
if (ret < 0 && ret != -ENODEV)
- return dev_err_probe(&spi->dev, ret, "failed to enable VREFIN\n");
+ return dev_err_probe(dev, ret, "failed to enable VREFIN\n");
st->vrefin_en = ret != -ENODEV;
- st->gpio_reset = devm_gpiod_get_optional(&st->spi->dev, "reset",
+ st->gpio_reset = devm_gpiod_get_optional(dev, "reset",
GPIOD_OUT_HIGH);
if (IS_ERR(st->gpio_reset))
- return dev_err_probe(&spi->dev, PTR_ERR(st->gpio_reset),
+ return dev_err_probe(dev, PTR_ERR(st->gpio_reset),
"failed to get the reset GPIO\n");
return 0;
@@ -845,9 +845,10 @@ static int ad7293_probe(struct spi_device *spi)
{
struct iio_dev *indio_dev;
struct ad7293_state *st;
+ struct device *dev = &spi->dev;
int ret;
- indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
+ indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
if (!indio_dev)
return -ENOMEM;
@@ -867,7 +868,7 @@ static int ad7293_probe(struct spi_device *spi)
if (ret)
return ret;
- return devm_iio_device_register(&spi->dev, indio_dev);
+ return devm_iio_device_register(dev, indio_dev);
}
static const struct spi_device_id ad7293_id[] = {
--
2.43.0 | {
"author": "Antoniu Miclaus <antoniu.miclaus@analog.com>",
"date": "Fri, 27 Feb 2026 16:01:38 +0200",
"is_openbsd": false,
"thread_id": "aaGyUMNzk9cNC5LG@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | Use dev_err_probe() consistently in the probe path of several ADI IIO
drivers. This simplifies error handling and ensures proper logging of
deferred probes.
Each driver is updated in two patches: first introducing a local
struct device *dev variable alongside the existing spi variable to
replace &spi->dev references in non-error paths, then converting
dev_err() error paths to use dev_err_probe().
Drivers updated:
- adrf6780
- admv1014
- admv1013
- adf4377
- ad7293
- admv8818
Changes in v4:
- Split each driver update back into two separate patches: one for
introducing the struct device variable and one for the dev_err_probe()
conversion. No lines are edited twice cross patch pairs, error-only
functions get dev introduced in the "use dev_err_probe" commit.
Antoniu Miclaus (12):
iio: frequency: adrf6780: add dev variable
iio: frequency: adrf6780: use dev_err_probe
iio: frequency: admv1014: add dev variable
iio: frequency: admv1014: use dev_err_probe
iio: frequency: admv1013: add dev variable
iio: frequency: admv1013: use dev_err_probe
iio: frequency: adf4377: add dev variable
iio: frequency: adf4377: use dev_err_probe
iio: dac: ad7293: add dev variable
iio: dac: ad7293: use dev_err_probe
iio: filter: admv8818: add dev variable
iio: filter: admv8818: use dev_err_probe
drivers/iio/dac/ad7293.c | 31 ++++++-----
drivers/iio/filter/admv8818.c | 56 +++++++++-----------
drivers/iio/frequency/adf4377.c | 56 ++++++++++----------
drivers/iio/frequency/admv1013.c | 43 +++++++--------
drivers/iio/frequency/admv1014.c | 89 ++++++++++++++------------------
drivers/iio/frequency/adrf6780.c | 60 +++++++++++----------
6 files changed, 155 insertions(+), 180 deletions(-)
--
2.43.0
| null | null | null | [PATCH v4 00/12] iio: use dev_err_probe in probe path for ADI drivers | Introduce a local struct device pointer in functions that reference
&spi->dev for device-managed resource calls and device property reads,
improving code readability.
Signed-off-by: Antoniu Miclaus <antoniu.miclaus@analog.com>
---
drivers/iio/filter/admv8818.c | 21 +++++++++++----------
1 file changed, 11 insertions(+), 10 deletions(-)
diff --git a/drivers/iio/filter/admv8818.c b/drivers/iio/filter/admv8818.c
index 19f823446cda..5fafd71da2b3 100644
--- a/drivers/iio/filter/admv8818.c
+++ b/drivers/iio/filter/admv8818.c
@@ -701,12 +701,12 @@ static int admv8818_init(struct admv8818_state *st)
static int admv8818_clk_setup(struct admv8818_state *st)
{
- struct spi_device *spi = st->spi;
+ struct device *dev = &st->spi->dev;
int ret;
- st->clkin = devm_clk_get_optional(&spi->dev, "rf_in");
+ st->clkin = devm_clk_get_optional(dev, "rf_in");
if (IS_ERR(st->clkin))
- return dev_err_probe(&spi->dev, PTR_ERR(st->clkin),
+ return dev_err_probe(dev, PTR_ERR(st->clkin),
"failed to get the input clock\n");
else if (!st->clkin)
return 0;
@@ -715,7 +715,7 @@ static int admv8818_clk_setup(struct admv8818_state *st)
if (ret)
return ret;
- ret = devm_add_action_or_reset(&spi->dev, admv8818_clk_disable, st);
+ ret = devm_add_action_or_reset(dev, admv8818_clk_disable, st);
if (ret)
return ret;
@@ -724,16 +724,16 @@ static int admv8818_clk_setup(struct admv8818_state *st)
if (ret < 0)
return ret;
- return devm_add_action_or_reset(&spi->dev, admv8818_clk_notifier_unreg, st);
+ return devm_add_action_or_reset(dev, admv8818_clk_notifier_unreg, st);
}
static int admv8818_read_properties(struct admv8818_state *st)
{
- struct spi_device *spi = st->spi;
+ struct device *dev = &st->spi->dev;
u32 mhz;
int ret;
- ret = device_property_read_u32(&spi->dev, "adi,lpf-margin-mhz", &mhz);
+ ret = device_property_read_u32(dev, "adi,lpf-margin-mhz", &mhz);
if (ret == 0)
st->lpf_margin_hz = (u64)mhz * HZ_PER_MHZ;
else if (ret == -EINVAL)
@@ -742,7 +742,7 @@ static int admv8818_read_properties(struct admv8818_state *st)
return ret;
- ret = device_property_read_u32(&spi->dev, "adi,hpf-margin-mhz", &mhz);
+ ret = device_property_read_u32(dev, "adi,hpf-margin-mhz", &mhz);
if (ret == 0)
st->hpf_margin_hz = (u64)mhz * HZ_PER_MHZ;
else if (ret == -EINVAL)
@@ -758,9 +758,10 @@ static int admv8818_probe(struct spi_device *spi)
struct iio_dev *indio_dev;
struct regmap *regmap;
struct admv8818_state *st;
+ struct device *dev = &spi->dev;
int ret;
- indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
+ indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
if (!indio_dev)
return -ENOMEM;
@@ -792,7 +793,7 @@ static int admv8818_probe(struct spi_device *spi)
if (ret)
return ret;
- return devm_iio_device_register(&spi->dev, indio_dev);
+ return devm_iio_device_register(dev, indio_dev);
}
static const struct spi_device_id admv8818_id[] = {
--
2.43.0 | {
"author": "Antoniu Miclaus <antoniu.miclaus@analog.com>",
"date": "Fri, 27 Feb 2026 16:01:40 +0200",
"is_openbsd": false,
"thread_id": "aaGyUMNzk9cNC5LG@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | Use dev_err_probe() consistently in the probe path of several ADI IIO
drivers. This simplifies error handling and ensures proper logging of
deferred probes.
Each driver is updated in two patches: first introducing a local
struct device *dev variable alongside the existing spi variable to
replace &spi->dev references in non-error paths, then converting
dev_err() error paths to use dev_err_probe().
Drivers updated:
- adrf6780
- admv1014
- admv1013
- adf4377
- ad7293
- admv8818
Changes in v4:
- Split each driver update back into two separate patches: one for
introducing the struct device variable and one for the dev_err_probe()
conversion. No lines are edited twice cross patch pairs, error-only
functions get dev introduced in the "use dev_err_probe" commit.
Antoniu Miclaus (12):
iio: frequency: adrf6780: add dev variable
iio: frequency: adrf6780: use dev_err_probe
iio: frequency: admv1014: add dev variable
iio: frequency: admv1014: use dev_err_probe
iio: frequency: admv1013: add dev variable
iio: frequency: admv1013: use dev_err_probe
iio: frequency: adf4377: add dev variable
iio: frequency: adf4377: use dev_err_probe
iio: dac: ad7293: add dev variable
iio: dac: ad7293: use dev_err_probe
iio: filter: admv8818: add dev variable
iio: filter: admv8818: use dev_err_probe
drivers/iio/dac/ad7293.c | 31 ++++++-----
drivers/iio/filter/admv8818.c | 56 +++++++++-----------
drivers/iio/frequency/adf4377.c | 56 ++++++++++----------
drivers/iio/frequency/admv1013.c | 43 +++++++--------
drivers/iio/frequency/admv1014.c | 89 ++++++++++++++------------------
drivers/iio/frequency/adrf6780.c | 60 +++++++++++----------
6 files changed, 155 insertions(+), 180 deletions(-)
--
2.43.0
| null | null | null | [PATCH v4 00/12] iio: use dev_err_probe in probe path for ADI drivers | Use dev_err_probe() consistently in the probe path to simplify error
handling and ensure deferred probes are logged correctly.
Signed-off-by: Antoniu Miclaus <antoniu.miclaus@analog.com>
---
drivers/iio/filter/admv8818.c | 35 ++++++++++++++---------------------
1 file changed, 14 insertions(+), 21 deletions(-)
diff --git a/drivers/iio/filter/admv8818.c b/drivers/iio/filter/admv8818.c
index 5fafd71da2b3..0b9e3ba55476 100644
--- a/drivers/iio/filter/admv8818.c
+++ b/drivers/iio/filter/admv8818.c
@@ -657,41 +657,34 @@ static void admv8818_clk_disable(void *data)
static int admv8818_init(struct admv8818_state *st)
{
int ret;
- struct spi_device *spi = st->spi;
+ struct device *dev = &st->spi->dev;
unsigned int chip_id;
ret = regmap_write(st->regmap, ADMV8818_REG_SPI_CONFIG_A,
ADMV8818_SOFTRESET_N_MSK | ADMV8818_SOFTRESET_MSK);
- if (ret) {
- dev_err(&spi->dev, "ADMV8818 Soft Reset failed.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret, "ADMV8818 Soft Reset failed.\n");
ret = regmap_write(st->regmap, ADMV8818_REG_SPI_CONFIG_A,
ADMV8818_SDOACTIVE_N_MSK | ADMV8818_SDOACTIVE_MSK);
- if (ret) {
- dev_err(&spi->dev, "ADMV8818 SDO Enable failed.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret, "ADMV8818 SDO Enable failed.\n");
ret = regmap_read(st->regmap, ADMV8818_REG_CHIPTYPE, &chip_id);
- if (ret) {
- dev_err(&spi->dev, "ADMV8818 Chip ID read failed.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret,
+ "ADMV8818 Chip ID read failed.\n");
- if (chip_id != 0x1) {
- dev_err(&spi->dev, "ADMV8818 Invalid Chip ID.\n");
- return -EINVAL;
- }
+ if (chip_id != 0x1)
+ return dev_err_probe(dev, -EINVAL,
+ "ADMV8818 Invalid Chip ID.\n");
ret = regmap_update_bits(st->regmap, ADMV8818_REG_SPI_CONFIG_B,
ADMV8818_SINGLE_INSTRUCTION_MSK,
FIELD_PREP(ADMV8818_SINGLE_INSTRUCTION_MSK, 1));
- if (ret) {
- dev_err(&spi->dev, "ADMV8818 Single Instruction failed.\n");
- return ret;
- }
+ if (ret)
+ return dev_err_probe(dev, ret,
+ "ADMV8818 Single Instruction failed.\n");
if (st->clkin)
return admv8818_rfin_band_select(st);
--
2.43.0 | {
"author": "Antoniu Miclaus <antoniu.miclaus@analog.com>",
"date": "Fri, 27 Feb 2026 16:01:41 +0200",
"is_openbsd": false,
"thread_id": "aaGyUMNzk9cNC5LG@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | Use dev_err_probe() consistently in the probe path of several ADI IIO
drivers. This simplifies error handling and ensures proper logging of
deferred probes.
Each driver is updated in two patches: first introducing a local
struct device *dev variable alongside the existing spi variable to
replace &spi->dev references in non-error paths, then converting
dev_err() error paths to use dev_err_probe().
Drivers updated:
- adrf6780
- admv1014
- admv1013
- adf4377
- ad7293
- admv8818
Changes in v4:
- Split each driver update back into two separate patches: one for
introducing the struct device variable and one for the dev_err_probe()
conversion. No lines are edited twice cross patch pairs, error-only
functions get dev introduced in the "use dev_err_probe" commit.
Antoniu Miclaus (12):
iio: frequency: adrf6780: add dev variable
iio: frequency: adrf6780: use dev_err_probe
iio: frequency: admv1014: add dev variable
iio: frequency: admv1014: use dev_err_probe
iio: frequency: admv1013: add dev variable
iio: frequency: admv1013: use dev_err_probe
iio: frequency: adf4377: add dev variable
iio: frequency: adf4377: use dev_err_probe
iio: dac: ad7293: add dev variable
iio: dac: ad7293: use dev_err_probe
iio: filter: admv8818: add dev variable
iio: filter: admv8818: use dev_err_probe
drivers/iio/dac/ad7293.c | 31 ++++++-----
drivers/iio/filter/admv8818.c | 56 +++++++++-----------
drivers/iio/frequency/adf4377.c | 56 ++++++++++----------
drivers/iio/frequency/admv1013.c | 43 +++++++--------
drivers/iio/frequency/admv1014.c | 89 ++++++++++++++------------------
drivers/iio/frequency/adrf6780.c | 60 +++++++++++----------
6 files changed, 155 insertions(+), 180 deletions(-)
--
2.43.0
| null | null | null | [PATCH v4 00/12] iio: use dev_err_probe in probe path for ADI drivers | On Fri, Feb 27, 2026 at 04:01:29PM +0200, Antoniu Miclaus wrote:
Thanks, I briefly looked and it looks fine to me,
Reviewed-by: Andy Shevchenko <andriy.shevchenko@intel.com>
--
With Best Regards,
Andy Shevchenko | {
"author": "Andy Shevchenko <andriy.shevchenko@intel.com>",
"date": "Fri, 27 Feb 2026 17:03:44 +0200",
"is_openbsd": false,
"thread_id": "aaGyUMNzk9cNC5LG@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | Axiado AX3000 SoC contains Arasan PHY which provides the interface to the
HS200 eMMC controller.
This series includes:
1. Add bindings for Axiado AX3000 eMMC PHY
2. Add Axiado AX3000 eMMC phy driver
3. Update MAINTAINERS for the new driver
4. Update Axiado AX3000 device tree
Changes in v2:
- Fix dt-binding format
- Fix compilation error in m68k
- Use readl_poll_timeout instead of read_poll_timeout
- Link to v1: https://lore.kernel.org/r/20260109-axiado-ax3000-add-emmc-phy-driver-support-v1-0-dd43459dbfea@axiado.com
Changes: (The previous version was mixed with Host driver, so I separate
the PHY driver as a new thread)
- Fix property order in required section to match properties section
- Fixed example to use lowercase hex and proper node naming
- Removed wrapper functions, use readl/writel directly
- Replaced manual polling loops with read_poll_timeout macro
- Used devm_platform_ioremap_resource instead of separate calls
- Removed unnecessary of_match_node check
- Used dev_err_probe for error reporting
- Added proper Kconfig dependencies (ARCH_AXIADO || COMPILE_TEST)
- Fixed various coding style issues
- Link to previous patches: https://lore.kernel.org/all/20251222-axiado-ax3000-add-emmc-host-driver-support-v1-0-5457d0ebcdb4@axiado.com/
Signed-off-by: Tzu-Hao Wei <twei@axiado.com>
---
SriNavmani A (3):
dt-bindings: phy: axiado,ax3000-emmc-phy: add Axiado eMMC PHY
phy: axiado: add Axiado eMMC PHY driver
arm64: dts: axiado: Add eMMC PHY node
Tzu-Hao Wei (1):
MAINTAINERS: Add Axiado AX3000 eMMC PHY driver
.../bindings/phy/axiado,ax3000-emmc-phy.yaml | 37 ++++
MAINTAINERS | 10 +
arch/arm64/boot/dts/axiado/ax3000.dtsi | 7 +
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/axiado/Kconfig | 11 +
drivers/phy/axiado/Makefile | 1 +
drivers/phy/axiado/phy-axiado-emmc.c | 221 +++++++++++++++++++++
8 files changed, 289 insertions(+)
---
base-commit: 63804fed149a6750ffd28610c5c1c98cce6bd377
change-id: 20260108-axiado-ax3000-add-emmc-phy-driver-support-d61aead8f622
Best regards,
--
Tzu-Hao Wei <twei@axiado.com>
| null | null | null | [PATCH v2 0/4] Add eMMC PHY support for Axiado AX3000 SoC | From: SriNavmani A <srinavmani@axiado.com>
Axiado AX3000 SoC contains Arasan PHY which provides the interface to the
HS200 eMMC host controller.
Signed-off-by: SriNavmani A <srinavmani@axiado.com>
Signed-off-by: Tzu-Hao Wei <twei@axiado.com>
---
.../bindings/phy/axiado,ax3000-emmc-phy.yaml | 37 ++++++++++++++++++++++
1 file changed, 37 insertions(+)
diff --git a/Documentation/devicetree/bindings/phy/axiado,ax3000-emmc-phy.yaml b/Documentation/devicetree/bindings/phy/axiado,ax3000-emmc-phy.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..61700b80e93f7185e16ca9eab0922fe6bb29fe86
--- /dev/null
+++ b/Documentation/devicetree/bindings/phy/axiado,ax3000-emmc-phy.yaml
@@ -0,0 +1,37 @@
+# SPDX-License-Identifier: GPL-2.0-only OR BSD-2-Clause
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/phy/axiado,ax3000-emmc-phy.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Axiado AX3000 Arasan eMMC PHY
+
+maintainers:
+ - SriNavmani A <srinavmani@axiado.com>
+ - Tzu-Hao Wei <twei@axiado.com>
+ - Prasad Bolisetty <pbolisetty@axiado.com>
+
+properties:
+ compatible:
+ const: axiado,ax3000-emmc-phy
+
+ reg:
+ maxItems: 1
+
+ "#phy-cells":
+ const: 0
+
+required:
+ - compatible
+ - reg
+ - "#phy-cells"
+
+additionalProperties: false
+
+examples:
+ - |
+ phy@80801c00 {
+ compatible = "axiado,ax3000-emmc-phy";
+ reg = <0x80801c00 0x1000>;
+ #phy-cells = <0>;
+ };
--
2.34.1 | {
"author": "Tzu-Hao Wei <twei@axiado.com>",
"date": "Fri, 06 Feb 2026 16:22:08 +0800",
"is_openbsd": false,
"thread_id": "20260206-axiado-ax3000-add-emmc-phy-driver-support-v2-0-a2f59e97a92d@axiado.com.mbox.gz"
} |
lkml_critique | lkml | Axiado AX3000 SoC contains Arasan PHY which provides the interface to the
HS200 eMMC controller.
This series includes:
1. Add bindings for Axiado AX3000 eMMC PHY
2. Add Axiado AX3000 eMMC phy driver
3. Update MAINTAINERS for the new driver
4. Update Axiado AX3000 device tree
Changes in v2:
- Fix dt-binding format
- Fix compilation error in m68k
- Use readl_poll_timeout instead of read_poll_timeout
- Link to v1: https://lore.kernel.org/r/20260109-axiado-ax3000-add-emmc-phy-driver-support-v1-0-dd43459dbfea@axiado.com
Changes: (The previous version was mixed with Host driver, so I separate
the PHY driver as a new thread)
- Fix property order in required section to match properties section
- Fixed example to use lowercase hex and proper node naming
- Removed wrapper functions, use readl/writel directly
- Replaced manual polling loops with read_poll_timeout macro
- Used devm_platform_ioremap_resource instead of separate calls
- Removed unnecessary of_match_node check
- Used dev_err_probe for error reporting
- Added proper Kconfig dependencies (ARCH_AXIADO || COMPILE_TEST)
- Fixed various coding style issues
- Link to previous patches: https://lore.kernel.org/all/20251222-axiado-ax3000-add-emmc-host-driver-support-v1-0-5457d0ebcdb4@axiado.com/
Signed-off-by: Tzu-Hao Wei <twei@axiado.com>
---
SriNavmani A (3):
dt-bindings: phy: axiado,ax3000-emmc-phy: add Axiado eMMC PHY
phy: axiado: add Axiado eMMC PHY driver
arm64: dts: axiado: Add eMMC PHY node
Tzu-Hao Wei (1):
MAINTAINERS: Add Axiado AX3000 eMMC PHY driver
.../bindings/phy/axiado,ax3000-emmc-phy.yaml | 37 ++++
MAINTAINERS | 10 +
arch/arm64/boot/dts/axiado/ax3000.dtsi | 7 +
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/axiado/Kconfig | 11 +
drivers/phy/axiado/Makefile | 1 +
drivers/phy/axiado/phy-axiado-emmc.c | 221 +++++++++++++++++++++
8 files changed, 289 insertions(+)
---
base-commit: 63804fed149a6750ffd28610c5c1c98cce6bd377
change-id: 20260108-axiado-ax3000-add-emmc-phy-driver-support-d61aead8f622
Best regards,
--
Tzu-Hao Wei <twei@axiado.com>
| null | null | null | [PATCH v2 0/4] Add eMMC PHY support for Axiado AX3000 SoC | Add SriNavmani, Prasad and me as maintainers for Axiado AX3000 eMMC PHY
driver
Acked-by: Prasad Bolisetty <pbolisetty@axiado.com>
Signed-off-by: Tzu-Hao Wei <twei@axiado.com>
---
MAINTAINERS | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/MAINTAINERS b/MAINTAINERS
index 67db88b04537b431c927b73624993233eef43e3f..c33b0aa94de81c89b674e44d4813c4e3b95b7b2d 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -4254,6 +4254,16 @@ W: https://ez.analog.com/linux-software-drivers
F: Documentation/devicetree/bindings/hwmon/adi,axi-fan-control.yaml
F: drivers/hwmon/axi-fan-control.c
+AXIADO EMMC PHY DRIVER
+M: SriNavmani A <srinavmani@axiado.com>
+M: Tzu-Hao Wei <twei@axiado.com>
+M: Prasad Bolisetty <pbolisetty@axiado.com>
+L: linux-phy@lists.infradead.org (moderated for non-subscribers)
+S: Maintained
+F: Documentation/devicetree/bindings/phy/axiado,ax3000-emmc-phy.yaml
+F: drivers/phy/axiado/Kconfig
+F: drivers/phy/axiado/phy-axiado-emmc.c
+
AXI SPI ENGINE
M: Michael Hennerich <michael.hennerich@analog.com>
M: Nuno Sá <nuno.sa@analog.com>
--
2.34.1 | {
"author": "Tzu-Hao Wei <twei@axiado.com>",
"date": "Fri, 06 Feb 2026 16:22:10 +0800",
"is_openbsd": false,
"thread_id": "20260206-axiado-ax3000-add-emmc-phy-driver-support-v2-0-a2f59e97a92d@axiado.com.mbox.gz"
} |
lkml_critique | lkml | Axiado AX3000 SoC contains Arasan PHY which provides the interface to the
HS200 eMMC controller.
This series includes:
1. Add bindings for Axiado AX3000 eMMC PHY
2. Add Axiado AX3000 eMMC phy driver
3. Update MAINTAINERS for the new driver
4. Update Axiado AX3000 device tree
Changes in v2:
- Fix dt-binding format
- Fix compilation error in m68k
- Use readl_poll_timeout instead of read_poll_timeout
- Link to v1: https://lore.kernel.org/r/20260109-axiado-ax3000-add-emmc-phy-driver-support-v1-0-dd43459dbfea@axiado.com
Changes: (The previous version was mixed with Host driver, so I separate
the PHY driver as a new thread)
- Fix property order in required section to match properties section
- Fixed example to use lowercase hex and proper node naming
- Removed wrapper functions, use readl/writel directly
- Replaced manual polling loops with read_poll_timeout macro
- Used devm_platform_ioremap_resource instead of separate calls
- Removed unnecessary of_match_node check
- Used dev_err_probe for error reporting
- Added proper Kconfig dependencies (ARCH_AXIADO || COMPILE_TEST)
- Fixed various coding style issues
- Link to previous patches: https://lore.kernel.org/all/20251222-axiado-ax3000-add-emmc-host-driver-support-v1-0-5457d0ebcdb4@axiado.com/
Signed-off-by: Tzu-Hao Wei <twei@axiado.com>
---
SriNavmani A (3):
dt-bindings: phy: axiado,ax3000-emmc-phy: add Axiado eMMC PHY
phy: axiado: add Axiado eMMC PHY driver
arm64: dts: axiado: Add eMMC PHY node
Tzu-Hao Wei (1):
MAINTAINERS: Add Axiado AX3000 eMMC PHY driver
.../bindings/phy/axiado,ax3000-emmc-phy.yaml | 37 ++++
MAINTAINERS | 10 +
arch/arm64/boot/dts/axiado/ax3000.dtsi | 7 +
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/axiado/Kconfig | 11 +
drivers/phy/axiado/Makefile | 1 +
drivers/phy/axiado/phy-axiado-emmc.c | 221 +++++++++++++++++++++
8 files changed, 289 insertions(+)
---
base-commit: 63804fed149a6750ffd28610c5c1c98cce6bd377
change-id: 20260108-axiado-ax3000-add-emmc-phy-driver-support-d61aead8f622
Best regards,
--
Tzu-Hao Wei <twei@axiado.com>
| null | null | null | [PATCH v2 0/4] Add eMMC PHY support for Axiado AX3000 SoC | From: SriNavmani A <srinavmani@axiado.com>
Add the eMMC PHY device tree node to the AX3000 SoC DTSI.
AX3000 has one eMMC PHY interface.
Signed-off-by: SriNavmani A <srinavmani@axiado.com>
Signed-off-by: Tzu-Hao Wei <twei@axiado.com>
---
arch/arm64/boot/dts/axiado/ax3000.dtsi | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/arch/arm64/boot/dts/axiado/ax3000.dtsi b/arch/arm64/boot/dts/axiado/ax3000.dtsi
index 792f52e0c7dd42cbc54b0eb47e25b0fbf1a706b8..ccc8088bd8258cfb666268b14a3b0716a9ca69f4 100644
--- a/arch/arm64/boot/dts/axiado/ax3000.dtsi
+++ b/arch/arm64/boot/dts/axiado/ax3000.dtsi
@@ -507,6 +507,13 @@ uart3: serial@80520800 {
clocks = <&refclk &refclk>;
status = "disabled";
};
+
+ emmc_phy: phy@80801c00 {
+ compatible = "axiado,ax3000-emmc-phy";
+ reg = <0x0 0x80801c00 0x0 0x1000>;
+ #phy-cells = <0>;
+ status = "disabled";
+ };
};
timer {
--
2.34.1 | {
"author": "Tzu-Hao Wei <twei@axiado.com>",
"date": "Fri, 06 Feb 2026 16:22:11 +0800",
"is_openbsd": false,
"thread_id": "20260206-axiado-ax3000-add-emmc-phy-driver-support-v2-0-a2f59e97a92d@axiado.com.mbox.gz"
} |
lkml_critique | lkml | Axiado AX3000 SoC contains Arasan PHY which provides the interface to the
HS200 eMMC controller.
This series includes:
1. Add bindings for Axiado AX3000 eMMC PHY
2. Add Axiado AX3000 eMMC phy driver
3. Update MAINTAINERS for the new driver
4. Update Axiado AX3000 device tree
Changes in v2:
- Fix dt-binding format
- Fix compilation error in m68k
- Use readl_poll_timeout instead of read_poll_timeout
- Link to v1: https://lore.kernel.org/r/20260109-axiado-ax3000-add-emmc-phy-driver-support-v1-0-dd43459dbfea@axiado.com
Changes: (The previous version was mixed with Host driver, so I separate
the PHY driver as a new thread)
- Fix property order in required section to match properties section
- Fixed example to use lowercase hex and proper node naming
- Removed wrapper functions, use readl/writel directly
- Replaced manual polling loops with read_poll_timeout macro
- Used devm_platform_ioremap_resource instead of separate calls
- Removed unnecessary of_match_node check
- Used dev_err_probe for error reporting
- Added proper Kconfig dependencies (ARCH_AXIADO || COMPILE_TEST)
- Fixed various coding style issues
- Link to previous patches: https://lore.kernel.org/all/20251222-axiado-ax3000-add-emmc-host-driver-support-v1-0-5457d0ebcdb4@axiado.com/
Signed-off-by: Tzu-Hao Wei <twei@axiado.com>
---
SriNavmani A (3):
dt-bindings: phy: axiado,ax3000-emmc-phy: add Axiado eMMC PHY
phy: axiado: add Axiado eMMC PHY driver
arm64: dts: axiado: Add eMMC PHY node
Tzu-Hao Wei (1):
MAINTAINERS: Add Axiado AX3000 eMMC PHY driver
.../bindings/phy/axiado,ax3000-emmc-phy.yaml | 37 ++++
MAINTAINERS | 10 +
arch/arm64/boot/dts/axiado/ax3000.dtsi | 7 +
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/axiado/Kconfig | 11 +
drivers/phy/axiado/Makefile | 1 +
drivers/phy/axiado/phy-axiado-emmc.c | 221 +++++++++++++++++++++
8 files changed, 289 insertions(+)
---
base-commit: 63804fed149a6750ffd28610c5c1c98cce6bd377
change-id: 20260108-axiado-ax3000-add-emmc-phy-driver-support-d61aead8f622
Best regards,
--
Tzu-Hao Wei <twei@axiado.com>
| null | null | null | [PATCH v2 0/4] Add eMMC PHY support for Axiado AX3000 SoC | From: SriNavmani A <srinavmani@axiado.com>
It provides the required configurations for Axiado eMMC PHY driver for
HS200 mode.
Signed-off-by: SriNavmani A <srinavmani@axiado.com>
Co-developed-by: Prasad Bolisetty <pbolisetty@axiado.com>
Signed-off-by: Prasad Bolisetty <pbolisetty@axiado.com>
Signed-off-by: Tzu-Hao Wei <twei@axiado.com>
---
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/axiado/Kconfig | 11 ++
drivers/phy/axiado/Makefile | 1 +
drivers/phy/axiado/phy-axiado-emmc.c | 221 +++++++++++++++++++++++++++++++++++
5 files changed, 235 insertions(+)
diff --git a/drivers/phy/Kconfig b/drivers/phy/Kconfig
index 678dd0452f0aa0597773433f04d2a9ba77474d2a..b802274ea45a84bd36d7c0b7fb90e368a5c018b4 100644
--- a/drivers/phy/Kconfig
+++ b/drivers/phy/Kconfig
@@ -103,6 +103,7 @@ config PHY_NXP_PTN3222
source "drivers/phy/allwinner/Kconfig"
source "drivers/phy/amlogic/Kconfig"
+source "drivers/phy/axiado/Kconfig"
source "drivers/phy/broadcom/Kconfig"
source "drivers/phy/cadence/Kconfig"
source "drivers/phy/freescale/Kconfig"
diff --git a/drivers/phy/Makefile b/drivers/phy/Makefile
index bfb27fb5a494283d7fd05dd670ebd1b12df8b1a1..f1b9e4a8673bcde3fdc0fdc06a3deddb5785ced1 100644
--- a/drivers/phy/Makefile
+++ b/drivers/phy/Makefile
@@ -15,6 +15,7 @@ obj-$(CONFIG_PHY_AIROHA_PCIE) += phy-airoha-pcie.o
obj-$(CONFIG_PHY_NXP_PTN3222) += phy-nxp-ptn3222.o
obj-y += allwinner/ \
amlogic/ \
+ axiado/ \
broadcom/ \
cadence/ \
freescale/ \
diff --git a/drivers/phy/axiado/Kconfig b/drivers/phy/axiado/Kconfig
new file mode 100644
index 0000000000000000000000000000000000000000..d159e0345345987c7f48dcd12d3237997735d2b5
--- /dev/null
+++ b/drivers/phy/axiado/Kconfig
@@ -0,0 +1,11 @@
+#
+# PHY drivers for Axiado platforms
+#
+
+config PHY_AX3000_EMMC
+ tristate "Axiado eMMC PHY driver"
+ depends on OF && (ARCH_AXIADO || COMPILE_TEST)
+ select GENERIC_PHY
+ help
+ Enables this to support for the AX3000 EMMC PHY driver.
+ If unsure, say N.
diff --git a/drivers/phy/axiado/Makefile b/drivers/phy/axiado/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..1e2b1ba016092eaffdbd7acbd9cdc8577d79b35c
--- /dev/null
+++ b/drivers/phy/axiado/Makefile
@@ -0,0 +1 @@
+obj-$(CONFIG_PHY_AX3000_EMMC) += phy-axiado-emmc.o
diff --git a/drivers/phy/axiado/phy-axiado-emmc.c b/drivers/phy/axiado/phy-axiado-emmc.c
new file mode 100644
index 0000000000000000000000000000000000000000..28d2a30c3b35ee7dba917487959e226941e8ea4b
--- /dev/null
+++ b/drivers/phy/axiado/phy-axiado-emmc.c
@@ -0,0 +1,221 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * Axiado eMMC PHY driver
+ *
+ * Copyright (C) 2017 Arasan Chip Systems Inc.
+ * Copyright (C) 2022-2025 Axiado Corporation (or its affiliates).
+ *
+ * Based on Arasan Driver (sdhci-pci-arasan.c)
+ * sdhci-pci-arasan.c - Driver for Arasan PCI Controller with integrated phy.
+ */
+#include <linux/bitfield.h>
+#include <linux/delay.h>
+#include <linux/io.h>
+#include <linux/iopoll.h>
+#include <linux/module.h>
+#include <linux/of.h>
+#include <linux/phy/phy.h>
+#include <linux/platform_device.h>
+
+/* Arasan eMMC 5.1 - PHY configuration registers */
+#define CAP_REG_IN_S1_LSB 0x00
+#define CAP_REG_IN_S1_MSB 0x04
+#define PHY_CTRL_1 0x38
+#define PHY_CTRL_2 0x3C
+#define PHY_CTRL_3 0x40
+#define STATUS 0x50
+
+#define DLL_ENBL BIT(26)
+#define RTRIM_EN BIT(21)
+#define PDB_ENBL BIT(23)
+#define RETB_ENBL BIT(1)
+
+#define REN_STRB BIT(27)
+#define REN_CMD BIT(12)
+#define REN_DAT0 BIT(13)
+#define REN_DAT1 BIT(14)
+#define REN_DAT2 BIT(15)
+#define REN_DAT3 BIT(16)
+#define REN_DAT4 BIT(17)
+#define REN_DAT5 BIT(18)
+#define REN_DAT6 BIT(19)
+#define REN_DAT7 BIT(20)
+#define REN_CMD_EN (REN_CMD | REN_DAT0 | REN_DAT1 | REN_DAT2 | \
+ REN_DAT3 | REN_DAT4 | REN_DAT5 | REN_DAT6 | REN_DAT7)
+
+/* Pull-UP Enable on CMD Line */
+#define PU_CMD BIT(3)
+#define PU_DAT0 BIT(4)
+#define PU_DAT1 BIT(5)
+#define PU_DAT2 BIT(6)
+#define PU_DAT3 BIT(7)
+#define PU_DAT4 BIT(8)
+#define PU_DAT5 BIT(9)
+#define PU_DAT6 BIT(10)
+#define PU_DAT7 BIT(11)
+#define PU_CMD_EN (PU_CMD | PU_DAT0 | PU_DAT1 | PU_DAT2 | PU_DAT3 | \
+ PU_DAT4 | PU_DAT5 | PU_DAT6 | PU_DAT7)
+
+/* Selection value for the optimum delay from 1-32 output tap lines */
+#define OTAP_DLY 0x02
+/* DLL charge pump current trim default [1000] */
+#define DLL_TRM_ICP 0x08
+/* Select the frequency range of DLL Operation */
+#define FRQ_SEL 0x01
+
+#define OTAP_SEL_MASK GENMASK(10, 7)
+#define DLL_TRM_MASK GENMASK(25, 22)
+#define DLL_FRQSEL_MASK GENMASK(27, 25)
+
+#define OTAP_SEL(x) (FIELD_PREP(OTAP_SEL_MASK, x) | OTAPDLY_EN)
+#define DLL_TRM(x) (FIELD_PREP(DLL_TRM_MASK, x) | DLL_ENBL)
+#define DLL_FRQSEL(x) FIELD_PREP(DLL_FRQSEL_MASK, x)
+
+#define OTAPDLY_EN BIT(11)
+
+#define SEL_DLY_RXCLK BIT(18)
+#define SEL_DLY_TXCLK BIT(19)
+
+#define CALDONE_MASK 0x40
+#define DLL_RDY_MASK 0x1
+#define MAX_CLK_BUF0 BIT(20)
+#define MAX_CLK_BUF1 BIT(21)
+#define MAX_CLK_BUF2 BIT(22)
+
+#define CLK_MULTIPLIER 0xC008E
+#define POLL_TIMEOUT_MS 3000
+#define POLL_DELAY_US 100
+
+struct axiado_emmc_phy {
+ void __iomem *reg_base;
+ struct device *dev;
+};
+
+static int axiado_emmc_phy_init(struct phy *phy)
+{
+ struct axiado_emmc_phy *ax_phy = phy_get_drvdata(phy);
+ struct device *dev = ax_phy->dev;
+ u32 val;
+ int ret;
+
+ val = readl(ax_phy->reg_base + PHY_CTRL_1);
+ writel(val | RETB_ENBL | RTRIM_EN, ax_phy->reg_base + PHY_CTRL_1);
+
+ val = readl(ax_phy->reg_base + PHY_CTRL_3);
+ writel(val | PDB_ENBL, ax_phy->reg_base + PHY_CTRL_3);
+
+ ret = readl_poll_timeout(ax_phy->reg_base + STATUS, val,
+ val & CALDONE_MASK, POLL_DELAY_US,
+ POLL_TIMEOUT_MS * 1000);
+ if (ret) {
+ dev_err(dev, "PHY calibration timeout\n");
+ return ret;
+ }
+
+ val = readl(ax_phy->reg_base + PHY_CTRL_1);
+ writel(val | REN_CMD_EN | PU_CMD_EN, ax_phy->reg_base + PHY_CTRL_1);
+
+ val = readl(ax_phy->reg_base + PHY_CTRL_2);
+ writel(val | REN_STRB, ax_phy->reg_base + PHY_CTRL_2);
+
+ val = readl(ax_phy->reg_base + PHY_CTRL_3);
+ writel(val | MAX_CLK_BUF0 | MAX_CLK_BUF1 | MAX_CLK_BUF2,
+ ax_phy->reg_base + PHY_CTRL_3);
+
+ writel(CLK_MULTIPLIER, ax_phy->reg_base + CAP_REG_IN_S1_MSB);
+
+ val = readl(ax_phy->reg_base + PHY_CTRL_3);
+ writel(val | SEL_DLY_RXCLK | SEL_DLY_TXCLK,
+ ax_phy->reg_base + PHY_CTRL_3);
+
+ return 0;
+}
+
+static int axiado_emmc_phy_power_on(struct phy *phy)
+{
+ struct axiado_emmc_phy *ax_phy = phy_get_drvdata(phy);
+ struct device *dev = ax_phy->dev;
+ u32 val;
+ int ret;
+
+ val = readl(ax_phy->reg_base + PHY_CTRL_1);
+ writel(val | RETB_ENBL, ax_phy->reg_base + PHY_CTRL_1);
+
+ val = readl(ax_phy->reg_base + PHY_CTRL_3);
+ writel(val | PDB_ENBL, ax_phy->reg_base + PHY_CTRL_3);
+
+ val = readl(ax_phy->reg_base + PHY_CTRL_2);
+ writel(val | OTAP_SEL(OTAP_DLY), ax_phy->reg_base + PHY_CTRL_2);
+
+ val = readl(ax_phy->reg_base + PHY_CTRL_1);
+ writel(val | DLL_TRM(DLL_TRM_ICP), ax_phy->reg_base + PHY_CTRL_1);
+
+ val = readl(ax_phy->reg_base + PHY_CTRL_3);
+ writel(val | DLL_FRQSEL(FRQ_SEL), ax_phy->reg_base + PHY_CTRL_3);
+
+ ret = read_poll_timeout(readl, val, val & DLL_RDY_MASK, POLL_DELAY_US,
+ POLL_TIMEOUT_MS * 1000, false,
+ ax_phy->reg_base + STATUS);
+ if (ret) {
+ dev_err(dev, "DLL ready timeout\n");
+ return ret;
+ }
+
+ return 0;
+}
+
+static const struct phy_ops axiado_emmc_phy_ops = {
+ .init = axiado_emmc_phy_init,
+ .power_on = axiado_emmc_phy_power_on,
+ .owner = THIS_MODULE,
+};
+
+static const struct of_device_id axiado_emmc_phy_of_match[] = {
+ { .compatible = "axiado,ax3000-emmc-phy" },
+ { /* sentinel */ },
+};
+MODULE_DEVICE_TABLE(of, axiado_emmc_phy_of_match);
+
+static int axiado_emmc_phy_probe(struct platform_device *pdev)
+{
+ struct axiado_emmc_phy *ax_phy;
+ struct phy_provider *phy_provider;
+ struct device *dev = &pdev->dev;
+ struct phy *generic_phy;
+
+ if (!dev->of_node)
+ return -ENODEV;
+
+ ax_phy = devm_kzalloc(dev, sizeof(*ax_phy), GFP_KERNEL);
+ if (!ax_phy)
+ return -ENOMEM;
+
+ ax_phy->reg_base = devm_platform_ioremap_resource(pdev, 0);
+ if (IS_ERR(ax_phy->reg_base))
+ return PTR_ERR(ax_phy->reg_base);
+
+ ax_phy->dev = dev;
+
+ generic_phy = devm_phy_create(dev, dev->of_node, &axiado_emmc_phy_ops);
+ if (IS_ERR(generic_phy))
+ return dev_err_probe(dev, PTR_ERR(generic_phy),
+ "failed to create PHY\n");
+
+ phy_set_drvdata(generic_phy, ax_phy);
+ phy_provider = devm_of_phy_provider_register(dev, of_phy_simple_xlate);
+
+ return PTR_ERR_OR_ZERO(phy_provider);
+}
+
+static struct platform_driver axiado_emmc_phy_driver = {
+ .probe = axiado_emmc_phy_probe,
+ .driver = {
+ .name = "axiado-emmc-phy",
+ .of_match_table = axiado_emmc_phy_of_match,
+ },
+};
+module_platform_driver(axiado_emmc_phy_driver);
+
+MODULE_DESCRIPTION("AX3000 eMMC PHY Driver");
+MODULE_AUTHOR("Axiado Corporation");
+MODULE_LICENSE("GPL");
--
2.34.1 | {
"author": "Tzu-Hao Wei <twei@axiado.com>",
"date": "Fri, 06 Feb 2026 16:22:09 +0800",
"is_openbsd": false,
"thread_id": "20260206-axiado-ax3000-add-emmc-phy-driver-support-v2-0-a2f59e97a92d@axiado.com.mbox.gz"
} |
lkml_critique | lkml | Axiado AX3000 SoC contains Arasan PHY which provides the interface to the
HS200 eMMC controller.
This series includes:
1. Add bindings for Axiado AX3000 eMMC PHY
2. Add Axiado AX3000 eMMC phy driver
3. Update MAINTAINERS for the new driver
4. Update Axiado AX3000 device tree
Changes in v2:
- Fix dt-binding format
- Fix compilation error in m68k
- Use readl_poll_timeout instead of read_poll_timeout
- Link to v1: https://lore.kernel.org/r/20260109-axiado-ax3000-add-emmc-phy-driver-support-v1-0-dd43459dbfea@axiado.com
Changes: (The previous version was mixed with Host driver, so I separate
the PHY driver as a new thread)
- Fix property order in required section to match properties section
- Fixed example to use lowercase hex and proper node naming
- Removed wrapper functions, use readl/writel directly
- Replaced manual polling loops with read_poll_timeout macro
- Used devm_platform_ioremap_resource instead of separate calls
- Removed unnecessary of_match_node check
- Used dev_err_probe for error reporting
- Added proper Kconfig dependencies (ARCH_AXIADO || COMPILE_TEST)
- Fixed various coding style issues
- Link to previous patches: https://lore.kernel.org/all/20251222-axiado-ax3000-add-emmc-host-driver-support-v1-0-5457d0ebcdb4@axiado.com/
Signed-off-by: Tzu-Hao Wei <twei@axiado.com>
---
SriNavmani A (3):
dt-bindings: phy: axiado,ax3000-emmc-phy: add Axiado eMMC PHY
phy: axiado: add Axiado eMMC PHY driver
arm64: dts: axiado: Add eMMC PHY node
Tzu-Hao Wei (1):
MAINTAINERS: Add Axiado AX3000 eMMC PHY driver
.../bindings/phy/axiado,ax3000-emmc-phy.yaml | 37 ++++
MAINTAINERS | 10 +
arch/arm64/boot/dts/axiado/ax3000.dtsi | 7 +
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/axiado/Kconfig | 11 +
drivers/phy/axiado/Makefile | 1 +
drivers/phy/axiado/phy-axiado-emmc.c | 221 +++++++++++++++++++++
8 files changed, 289 insertions(+)
---
base-commit: 63804fed149a6750ffd28610c5c1c98cce6bd377
change-id: 20260108-axiado-ax3000-add-emmc-phy-driver-support-d61aead8f622
Best regards,
--
Tzu-Hao Wei <twei@axiado.com>
| null | null | null | [PATCH v2 0/4] Add eMMC PHY support for Axiado AX3000 SoC | On Fri, 06 Feb 2026 16:22:08 +0800, Tzu-Hao Wei wrote:
Reviewed-by: Rob Herring (Arm) <robh@kernel.org> | {
"author": "\"Rob Herring (Arm)\" <robh@kernel.org>",
"date": "Mon, 9 Feb 2026 19:30:29 -0600",
"is_openbsd": false,
"thread_id": "20260206-axiado-ax3000-add-emmc-phy-driver-support-v2-0-a2f59e97a92d@axiado.com.mbox.gz"
} |
lkml_critique | lkml | Axiado AX3000 SoC contains Arasan PHY which provides the interface to the
HS200 eMMC controller.
This series includes:
1. Add bindings for Axiado AX3000 eMMC PHY
2. Add Axiado AX3000 eMMC phy driver
3. Update MAINTAINERS for the new driver
4. Update Axiado AX3000 device tree
Changes in v2:
- Fix dt-binding format
- Fix compilation error in m68k
- Use readl_poll_timeout instead of read_poll_timeout
- Link to v1: https://lore.kernel.org/r/20260109-axiado-ax3000-add-emmc-phy-driver-support-v1-0-dd43459dbfea@axiado.com
Changes: (The previous version was mixed with Host driver, so I separate
the PHY driver as a new thread)
- Fix property order in required section to match properties section
- Fixed example to use lowercase hex and proper node naming
- Removed wrapper functions, use readl/writel directly
- Replaced manual polling loops with read_poll_timeout macro
- Used devm_platform_ioremap_resource instead of separate calls
- Removed unnecessary of_match_node check
- Used dev_err_probe for error reporting
- Added proper Kconfig dependencies (ARCH_AXIADO || COMPILE_TEST)
- Fixed various coding style issues
- Link to previous patches: https://lore.kernel.org/all/20251222-axiado-ax3000-add-emmc-host-driver-support-v1-0-5457d0ebcdb4@axiado.com/
Signed-off-by: Tzu-Hao Wei <twei@axiado.com>
---
SriNavmani A (3):
dt-bindings: phy: axiado,ax3000-emmc-phy: add Axiado eMMC PHY
phy: axiado: add Axiado eMMC PHY driver
arm64: dts: axiado: Add eMMC PHY node
Tzu-Hao Wei (1):
MAINTAINERS: Add Axiado AX3000 eMMC PHY driver
.../bindings/phy/axiado,ax3000-emmc-phy.yaml | 37 ++++
MAINTAINERS | 10 +
arch/arm64/boot/dts/axiado/ax3000.dtsi | 7 +
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/axiado/Kconfig | 11 +
drivers/phy/axiado/Makefile | 1 +
drivers/phy/axiado/phy-axiado-emmc.c | 221 +++++++++++++++++++++
8 files changed, 289 insertions(+)
---
base-commit: 63804fed149a6750ffd28610c5c1c98cce6bd377
change-id: 20260108-axiado-ax3000-add-emmc-phy-driver-support-d61aead8f622
Best regards,
--
Tzu-Hao Wei <twei@axiado.com>
| null | null | null | [PATCH v2 0/4] Add eMMC PHY support for Axiado AX3000 SoC | On 06-02-26, 16:22, Tzu-Hao Wei wrote:
2026
smaller hex case please, here and other places
The bit define are used only once, why not define the cmd with
respective bits here
no power_off?
--
~Vinod | {
"author": "Vinod Koul <vkoul@kernel.org>",
"date": "Fri, 27 Feb 2026 20:23:18 +0530",
"is_openbsd": false,
"thread_id": "20260206-axiado-ax3000-add-emmc-phy-driver-support-v2-0-a2f59e97a92d@axiado.com.mbox.gz"
} |
lkml_critique | lkml | Updates:
v9 -> v8:
- eswin,eic7700-sata-phy.yaml
- Modify the format of the "default" field in the
"eswin,tx-amplitude-tuning" and "eswin,tx-preemph-tuning"
properties.
- phy-eic7700-sata.c
- Correct the incorrectly formatted symbol "-" in the comments.
- Link to v8: https://lore.kernel.org/lkml/20260123024823.1612-1-luyulin@eswincomputing.com/
v8 -> v7:
- eswin,eic7700-sata-phy.yaml
- Add "eswin,tx-amplitude-tuning" and "eswin,tx-preemph-tuning"
properties, because these parameters may vary across different
circuit boards.
- Delete reviewed-by tag of Krzysztof Kozlowski, because the tuning
properties are introduced.
- phy-eic7700-sata.c
- Try to get SATA PHY transmitter amplitude and pre-emphasis signal
eye diagram tuning parameters from dts instead of hardcoded values
in the code. Because, these parameters may vary across different
circuit boards. Define default tuning parameters and use it when
these properties are not declared in dts.
- Add a comment to explain the reason for mapping I/O resources with
platform_get_resource and devm_ioremap instead of using the
devm_platform_ioremap_resource API.
- Link to v7: https://lore.kernel.org/lkml/20260106062944.1529-1-luyulin@eswincomputing.com/
v7 -> v6:
- phy-eic7700-sata.c
- Rename PHY_READY_TIMEOUT to PLL_LOCK_TIMEOUT_US with value 1000.
- Add macro PLL_LOCK_SLEEP_US set to 10.
- Add "goto disable_clk" in the eic7700_sata_phy_init function.
- Modify Copyright year from 2024 to 2026.
- Link to v6: https://lore.kernel.org/lkml/20251201060737.868-1-luyulin@eswincomputing.com/
v6 -> v5:
- eswin,eic7700-ahci.yaml
- Delete this file and it has already been applied in reply[1].
- eswin,eic7700-sata-phy.yaml
- Add clock and reset related properties.
- phy-eic7700-sata.c
- Map the io resource with platform_get_resource and devm_ioremap
instead of devm_platform_ioremap_resource API. Because the address
region of sata-phy falls into the region of hsp clock&reset which
has been got by hsp clock&reset driver.
- Use regmap_read_poll_timeout in wait_for_phy_ready to replace the
while loop check.
- Use devm_regmap_init_mmio and regmap_write to replace writel.
- Adapt to the clock and reset driver framework, replacing the
original readl and writel.
Because we are implementing the HSP layer clock and reset drivers,
the corresponding clock and reset registers can be registered into
the driver framework. And I have tested on the Sifive HiFive
Premier P550 board.
- Link to v5: https://lore.kernel.org/lkml/20250930083754.15-1-luyulin@eswincomputing.com/
v5 -> v4:
- eswin,eic7700-ahci.yaml
- Add "dt-bindings: ata:" prefix to the subject.
- Wrap at 80 characters in the YAML description field.
- Link to v4: https://lore.kernel.org/lkml/20250915125902.375-1-luyulin@eswincomputing.com/
v4 -> v3:
- eswin,eic7700-ahci.yaml
- Fix grammatical errors in patch subject and commit message
- Add an explanation in the commit message of patch 1 for retaining
the "ports-implemented" field, which Rob Herring suggested to
remove in the review comments on v2.
Link to Rob Herring's review:
https://lore.kernel.org/lkml/CAL_JsqKFotNLZZXwiy7S6K8qXLdGRAnsa-1zvZRDQBE39Gf5kg@mail.gmail.com/
Link to my question and Niklas Cassel's reply:
https://lore.kernel.org/lkml/aLBUC116MdJqDGIJ@flawful.org/
In this reply, Niklas Cassel mentioned his view:
If the ports-implemented register gets reset from
ahci_platform_assert_rsts(), then it seems acceptable to
retain the ports-implemented property in the device tree.
This aligns with our design.
Link to my reply:
https://lore.kernel.org/lkml/4ab70c6a.8be.198f47da494.Coremail.luyulin@eswincomputing.com/
Link to Niklas Cassel's question and my further explanation:
https://lore.kernel.org/lkml/aLlYkZWBaI5Yz6fo@ryzen/
https://lore.kernel.org/lkml/7206383a.d98.19918c22570.Coremail.luyulin@eswincomputing.com/
- eswin,eic7700-sata-phy.yaml
- Fix grammatical errors in patch subject and commit message
- Adjust the position of reg in the properties and required arrays
- Add reviewed-by tag of Krzysztof Kozlowski
- phy-eic7700-sata.c
- Correct the loop condition in wait_for_phy_ready() to use the
current jiffies instead of the fixed start time.
- Change the return value from -EFAULT to -ETIMEDOUT to correctly
indicate a timeout condition.
- Remove redundant clock disable handling in probe error path, as
SATA_SYS_CLK_EN is managed in phy_init() and phy_exit().
- Use dev_err_probe return in probe.
- Reorder local variables to follow reverse Xmas tree order.
- Wrap each line in the extended comments to 80 columns before
splitting lines.
- Adjust the position of `#include <linux/io.h>` for proper ordering.
- Link to v3: https://lore.kernel.org/lkml/20250904063427.1954-1-luyulin@eswincomputing.com/
v2 -> v3:
- Use full name in "From" and "Signed-off-by" fields information
- eswin,eic7700-ahci.yaml
- Remove the introduction to the reg, interrupts, phys, and
phy-names fields.
- Modify the usage of the clocks field in the examples.
- Correct the order of dt properties.
- phy-eic7700-sata.c
- Register operations use the GENMASK macro and FIELD_PREP instead
of the original bit offset method, and add
"#include <linux/bitfield.h>".
- Modify some macro definition names.
- Remove the redundant initialization assignments for "ret" and
"val".
- Delete ".suppress_bind_attrs = true".
- Modify the driver name.
- Add "#include <linux/io.h>" to fix the robot test issue.
- Link to v2: https://lore.kernel.org/lkml/20250819134722.220-1-luyulin@eswincomputing.com/
v2 -> v1:
- Delete the original controller driver and use ahci_dwc.c instead.
- Add eswin,eic7700-ahci.yaml
- Correct the descriptions of reset, interrupt and other hardware
resources for the sata controller on EIC7700 SoC.
- The clocks for both sata controller and sata PHY are controlled
via a register bit in the HSP bus and are not registered in the
clock tree. Clock are managed within the PHY driver, therefore it
is not described in this document.
- Add $ref: snps,dwc-ahci-common.yaml#.
- Add eswin,eic7700-sata-phy.yaml
- Add this file to include the description of the PHY on EIC7700 SoC.
- Add an eswin directory under the PHY driver path, and include the
SATA PHY driver code for EIC7700 SoC.
- Link to v1: https://lore.kernel.org/all/20250515085114.1692-1-hehuan1@eswincomputing.com/
Yulin Lu (2):
dt-bindings: phy: eswin: Document the EIC7700 SoC SATA PHY
phy: eswin: Create eswin directory and add EIC7700 SATA PHY driver
.../bindings/phy/eswin,eic7700-sata-phy.yaml | 92 ++++++
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/eswin/Kconfig | 14 +
drivers/phy/eswin/Makefile | 2 +
drivers/phy/eswin/phy-eic7700-sata.c | 273 ++++++++++++++++++
6 files changed, 383 insertions(+)
create mode 100644 Documentation/devicetree/bindings/phy/eswin,eic7700-sata-phy.yaml
create mode 100644 drivers/phy/eswin/Kconfig
create mode 100644 drivers/phy/eswin/Makefile
create mode 100644 drivers/phy/eswin/phy-eic7700-sata.c
--
2.25.1
| null | null | null | [PATCH v9 0/2] Add driver support for Eswin EIC7700 SoC SATA PHY | Document the SATA PHY on the EIC7700 SoC platform,
describing its usage.
Signed-off-by: Yulin Lu <luyulin@eswincomputing.com>
---
.../bindings/phy/eswin,eic7700-sata-phy.yaml | 92 +++++++++++++++++++
1 file changed, 92 insertions(+)
create mode 100644 Documentation/devicetree/bindings/phy/eswin,eic7700-sata-phy.yaml
diff --git a/Documentation/devicetree/bindings/phy/eswin,eic7700-sata-phy.yaml b/Documentation/devicetree/bindings/phy/eswin,eic7700-sata-phy.yaml
new file mode 100644
index 000000000000..fc7dbac77acf
--- /dev/null
+++ b/Documentation/devicetree/bindings/phy/eswin,eic7700-sata-phy.yaml
@@ -0,0 +1,92 @@
+# SPDX-License-Identifier: GPL-2.0-only OR BSD-2-Clause
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/phy/eswin,eic7700-sata-phy.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Eswin EIC7700 SoC SATA PHY
+
+maintainers:
+ - Yulin Lu <luyulin@eswincomputing.com>
+ - Huan He <hehuan1@eswincomputing.com>
+
+properties:
+ compatible:
+ const: eswin,eic7700-sata-phy
+
+ reg:
+ maxItems: 1
+
+ clocks:
+ maxItems: 1
+
+ clock-names:
+ const: phy
+
+ resets:
+ maxItems: 2
+
+ reset-names:
+ items:
+ - const: port
+ - const: phy
+
+ eswin,tx-amplitude-tuning:
+ description: This adjusts the transmitter amplitude signal, and its value
+ is derived from eye diagram tuning. The three values correspond to Gen1,
+ Gen2, and Gen3 parameters respectively.
+ $ref: /schemas/types.yaml#/definitions/uint32-array
+ items:
+ - description: Gen1 parameter.
+ minimum: 0
+ maximum: 0x7f
+ - description: Gen2 parameter.
+ minimum: 0
+ maximum: 0x7f
+ - description: Gen3 parameter.
+ minimum: 0
+ maximum: 0x7f
+ default: [0, 0, 0]
+
+ eswin,tx-preemph-tuning:
+ description: This adjusts the transmitter de-emphasis signal, and its value
+ is derived from eye diagram tuning. The three values correspond to Gen1,
+ Gen2, and Gen3 parameters respectively.
+ $ref: /schemas/types.yaml#/definitions/uint32-array
+ items:
+ - description: Gen1 parameter.
+ minimum: 0
+ maximum: 0x3f
+ - description: Gen2 parameter.
+ minimum: 0
+ maximum: 0x3f
+ - description: Gen3 parameter.
+ minimum: 0
+ maximum: 0x3f
+ default: [0, 0, 0]
+
+ "#phy-cells":
+ const: 0
+
+required:
+ - compatible
+ - reg
+ - clocks
+ - clock-names
+ - resets
+ - reset-names
+ - "#phy-cells"
+
+additionalProperties: false
+
+examples:
+ - |
+ sata-phy@50440300 {
+ compatible = "eswin,eic7700-sata-phy";
+ reg = <0x50440300 0x40>;
+ clocks = <&hspcrg 17>;
+ clock-names = "phy";
+ resets = <&hspcrg 0>, <&hspcrg 1>;
+ reset-names = "port", "phy";
+ #phy-cells = <0>;
+ };
--
2.25.1 | {
"author": "Yulin Lu <luyulin@eswincomputing.com>",
"date": "Thu, 5 Feb 2026 16:21:29 +0800",
"is_openbsd": false,
"thread_id": "177220617042.330302.2707782153123727768.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Updates:
v9 -> v8:
- eswin,eic7700-sata-phy.yaml
- Modify the format of the "default" field in the
"eswin,tx-amplitude-tuning" and "eswin,tx-preemph-tuning"
properties.
- phy-eic7700-sata.c
- Correct the incorrectly formatted symbol "-" in the comments.
- Link to v8: https://lore.kernel.org/lkml/20260123024823.1612-1-luyulin@eswincomputing.com/
v8 -> v7:
- eswin,eic7700-sata-phy.yaml
- Add "eswin,tx-amplitude-tuning" and "eswin,tx-preemph-tuning"
properties, because these parameters may vary across different
circuit boards.
- Delete reviewed-by tag of Krzysztof Kozlowski, because the tuning
properties are introduced.
- phy-eic7700-sata.c
- Try to get SATA PHY transmitter amplitude and pre-emphasis signal
eye diagram tuning parameters from dts instead of hardcoded values
in the code. Because, these parameters may vary across different
circuit boards. Define default tuning parameters and use it when
these properties are not declared in dts.
- Add a comment to explain the reason for mapping I/O resources with
platform_get_resource and devm_ioremap instead of using the
devm_platform_ioremap_resource API.
- Link to v7: https://lore.kernel.org/lkml/20260106062944.1529-1-luyulin@eswincomputing.com/
v7 -> v6:
- phy-eic7700-sata.c
- Rename PHY_READY_TIMEOUT to PLL_LOCK_TIMEOUT_US with value 1000.
- Add macro PLL_LOCK_SLEEP_US set to 10.
- Add "goto disable_clk" in the eic7700_sata_phy_init function.
- Modify Copyright year from 2024 to 2026.
- Link to v6: https://lore.kernel.org/lkml/20251201060737.868-1-luyulin@eswincomputing.com/
v6 -> v5:
- eswin,eic7700-ahci.yaml
- Delete this file and it has already been applied in reply[1].
- eswin,eic7700-sata-phy.yaml
- Add clock and reset related properties.
- phy-eic7700-sata.c
- Map the io resource with platform_get_resource and devm_ioremap
instead of devm_platform_ioremap_resource API. Because the address
region of sata-phy falls into the region of hsp clock&reset which
has been got by hsp clock&reset driver.
- Use regmap_read_poll_timeout in wait_for_phy_ready to replace the
while loop check.
- Use devm_regmap_init_mmio and regmap_write to replace writel.
- Adapt to the clock and reset driver framework, replacing the
original readl and writel.
Because we are implementing the HSP layer clock and reset drivers,
the corresponding clock and reset registers can be registered into
the driver framework. And I have tested on the Sifive HiFive
Premier P550 board.
- Link to v5: https://lore.kernel.org/lkml/20250930083754.15-1-luyulin@eswincomputing.com/
v5 -> v4:
- eswin,eic7700-ahci.yaml
- Add "dt-bindings: ata:" prefix to the subject.
- Wrap at 80 characters in the YAML description field.
- Link to v4: https://lore.kernel.org/lkml/20250915125902.375-1-luyulin@eswincomputing.com/
v4 -> v3:
- eswin,eic7700-ahci.yaml
- Fix grammatical errors in patch subject and commit message
- Add an explanation in the commit message of patch 1 for retaining
the "ports-implemented" field, which Rob Herring suggested to
remove in the review comments on v2.
Link to Rob Herring's review:
https://lore.kernel.org/lkml/CAL_JsqKFotNLZZXwiy7S6K8qXLdGRAnsa-1zvZRDQBE39Gf5kg@mail.gmail.com/
Link to my question and Niklas Cassel's reply:
https://lore.kernel.org/lkml/aLBUC116MdJqDGIJ@flawful.org/
In this reply, Niklas Cassel mentioned his view:
If the ports-implemented register gets reset from
ahci_platform_assert_rsts(), then it seems acceptable to
retain the ports-implemented property in the device tree.
This aligns with our design.
Link to my reply:
https://lore.kernel.org/lkml/4ab70c6a.8be.198f47da494.Coremail.luyulin@eswincomputing.com/
Link to Niklas Cassel's question and my further explanation:
https://lore.kernel.org/lkml/aLlYkZWBaI5Yz6fo@ryzen/
https://lore.kernel.org/lkml/7206383a.d98.19918c22570.Coremail.luyulin@eswincomputing.com/
- eswin,eic7700-sata-phy.yaml
- Fix grammatical errors in patch subject and commit message
- Adjust the position of reg in the properties and required arrays
- Add reviewed-by tag of Krzysztof Kozlowski
- phy-eic7700-sata.c
- Correct the loop condition in wait_for_phy_ready() to use the
current jiffies instead of the fixed start time.
- Change the return value from -EFAULT to -ETIMEDOUT to correctly
indicate a timeout condition.
- Remove redundant clock disable handling in probe error path, as
SATA_SYS_CLK_EN is managed in phy_init() and phy_exit().
- Use dev_err_probe return in probe.
- Reorder local variables to follow reverse Xmas tree order.
- Wrap each line in the extended comments to 80 columns before
splitting lines.
- Adjust the position of `#include <linux/io.h>` for proper ordering.
- Link to v3: https://lore.kernel.org/lkml/20250904063427.1954-1-luyulin@eswincomputing.com/
v2 -> v3:
- Use full name in "From" and "Signed-off-by" fields information
- eswin,eic7700-ahci.yaml
- Remove the introduction to the reg, interrupts, phys, and
phy-names fields.
- Modify the usage of the clocks field in the examples.
- Correct the order of dt properties.
- phy-eic7700-sata.c
- Register operations use the GENMASK macro and FIELD_PREP instead
of the original bit offset method, and add
"#include <linux/bitfield.h>".
- Modify some macro definition names.
- Remove the redundant initialization assignments for "ret" and
"val".
- Delete ".suppress_bind_attrs = true".
- Modify the driver name.
- Add "#include <linux/io.h>" to fix the robot test issue.
- Link to v2: https://lore.kernel.org/lkml/20250819134722.220-1-luyulin@eswincomputing.com/
v2 -> v1:
- Delete the original controller driver and use ahci_dwc.c instead.
- Add eswin,eic7700-ahci.yaml
- Correct the descriptions of reset, interrupt and other hardware
resources for the sata controller on EIC7700 SoC.
- The clocks for both sata controller and sata PHY are controlled
via a register bit in the HSP bus and are not registered in the
clock tree. Clock are managed within the PHY driver, therefore it
is not described in this document.
- Add $ref: snps,dwc-ahci-common.yaml#.
- Add eswin,eic7700-sata-phy.yaml
- Add this file to include the description of the PHY on EIC7700 SoC.
- Add an eswin directory under the PHY driver path, and include the
SATA PHY driver code for EIC7700 SoC.
- Link to v1: https://lore.kernel.org/all/20250515085114.1692-1-hehuan1@eswincomputing.com/
Yulin Lu (2):
dt-bindings: phy: eswin: Document the EIC7700 SoC SATA PHY
phy: eswin: Create eswin directory and add EIC7700 SATA PHY driver
.../bindings/phy/eswin,eic7700-sata-phy.yaml | 92 ++++++
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/eswin/Kconfig | 14 +
drivers/phy/eswin/Makefile | 2 +
drivers/phy/eswin/phy-eic7700-sata.c | 273 ++++++++++++++++++
6 files changed, 383 insertions(+)
create mode 100644 Documentation/devicetree/bindings/phy/eswin,eic7700-sata-phy.yaml
create mode 100644 drivers/phy/eswin/Kconfig
create mode 100644 drivers/phy/eswin/Makefile
create mode 100644 drivers/phy/eswin/phy-eic7700-sata.c
--
2.25.1
| null | null | null | [PATCH v9 0/2] Add driver support for Eswin EIC7700 SoC SATA PHY | Create the eswin phy driver directory and add support for the
SATA PHY driver on the EIC7700 SoC platform.
Signed-off-by: Yulin Lu <luyulin@eswincomputing.com>
---
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/eswin/Kconfig | 14 ++
drivers/phy/eswin/Makefile | 2 +
drivers/phy/eswin/phy-eic7700-sata.c | 273 +++++++++++++++++++++++++++
5 files changed, 291 insertions(+)
create mode 100644 drivers/phy/eswin/Kconfig
create mode 100644 drivers/phy/eswin/Makefile
create mode 100644 drivers/phy/eswin/phy-eic7700-sata.c
diff --git a/drivers/phy/Kconfig b/drivers/phy/Kconfig
index 678dd0452f0a..6d50704917f0 100644
--- a/drivers/phy/Kconfig
+++ b/drivers/phy/Kconfig
@@ -105,6 +105,7 @@ source "drivers/phy/allwinner/Kconfig"
source "drivers/phy/amlogic/Kconfig"
source "drivers/phy/broadcom/Kconfig"
source "drivers/phy/cadence/Kconfig"
+source "drivers/phy/eswin/Kconfig"
source "drivers/phy/freescale/Kconfig"
source "drivers/phy/hisilicon/Kconfig"
source "drivers/phy/ingenic/Kconfig"
diff --git a/drivers/phy/Makefile b/drivers/phy/Makefile
index bfb27fb5a494..482a143d3417 100644
--- a/drivers/phy/Makefile
+++ b/drivers/phy/Makefile
@@ -17,6 +17,7 @@ obj-y += allwinner/ \
amlogic/ \
broadcom/ \
cadence/ \
+ eswin/ \
freescale/ \
hisilicon/ \
ingenic/ \
diff --git a/drivers/phy/eswin/Kconfig b/drivers/phy/eswin/Kconfig
new file mode 100644
index 000000000000..cf2bf2efc32f
--- /dev/null
+++ b/drivers/phy/eswin/Kconfig
@@ -0,0 +1,14 @@
+# SPDX-License-Identifier: GPL-2.0-only
+#
+# Phy drivers for ESWIN platforms
+#
+config PHY_EIC7700_SATA
+ tristate "eic7700 Sata SerDes/PHY driver"
+ depends on ARCH_ESWIN || COMPILE_TEST
+ depends on HAS_IOMEM
+ select GENERIC_PHY
+ help
+ Enable this to support SerDes/Phy found on ESWIN's
+ EIC7700 SoC. This Phy supports SATA 1.5 Gb/s,
+ SATA 3.0 Gb/s, SATA 6.0 Gb/s speeds.
+ It supports one SATA host port to accept one SATA device.
diff --git a/drivers/phy/eswin/Makefile b/drivers/phy/eswin/Makefile
new file mode 100644
index 000000000000..db08c66be812
--- /dev/null
+++ b/drivers/phy/eswin/Makefile
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0
+obj-$(CONFIG_PHY_EIC7700_SATA) += phy-eic7700-sata.o
diff --git a/drivers/phy/eswin/phy-eic7700-sata.c b/drivers/phy/eswin/phy-eic7700-sata.c
new file mode 100644
index 000000000000..c33653d48daa
--- /dev/null
+++ b/drivers/phy/eswin/phy-eic7700-sata.c
@@ -0,0 +1,273 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * ESWIN SATA PHY driver
+ *
+ * Copyright 2026, Beijing ESWIN Computing Technology Co., Ltd..
+ * All rights reserved.
+ *
+ * Authors: Yulin Lu <luyulin@eswincomputing.com>
+ */
+
+#include <linux/bitfield.h>
+#include <linux/clk.h>
+#include <linux/delay.h>
+#include <linux/io.h>
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/phy/phy.h>
+#include <linux/platform_device.h>
+#include <linux/regmap.h>
+#include <linux/reset.h>
+
+#define SATA_AXI_LP_CTRL 0x08
+#define SATA_MPLL_CTRL 0x20
+#define SATA_P0_PHY_STAT 0x24
+#define SATA_PHY_CTRL0 0x28
+#define SATA_PHY_CTRL1 0x2c
+#define SATA_REF_CTRL 0x34
+#define SATA_REF_CTRL1 0x38
+#define SATA_LOS_IDEN 0x3c
+
+#define SATA_CLK_RST_SOURCE_PHY BIT(0)
+#define SATA_P0_PHY_TX_AMPLITUDE_GEN1_MASK GENMASK(6, 0)
+#define SATA_P0_PHY_TX_AMPLITUDE_GEN1_DEFAULT 0x42
+#define SATA_P0_PHY_TX_AMPLITUDE_GEN2_MASK GENMASK(14, 8)
+#define SATA_P0_PHY_TX_AMPLITUDE_GEN2_DEFAULT 0x46
+#define SATA_P0_PHY_TX_AMPLITUDE_GEN3_MASK GENMASK(22, 16)
+#define SATA_P0_PHY_TX_AMPLITUDE_GEN3_DEFAULT 0x73
+#define SATA_P0_PHY_TX_PREEMPH_GEN1_MASK GENMASK(5, 0)
+#define SATA_P0_PHY_TX_PREEMPH_GEN1_DEFAULT 0x5
+#define SATA_P0_PHY_TX_PREEMPH_GEN2_MASK GENMASK(13, 8)
+#define SATA_P0_PHY_TX_PREEMPH_GEN2_DEFAULT 0x5
+#define SATA_P0_PHY_TX_PREEMPH_GEN3_MASK GENMASK(21, 16)
+#define SATA_P0_PHY_TX_PREEMPH_GEN3_DEFAULT 0x23
+#define SATA_LOS_LEVEL_MASK GENMASK(4, 0)
+#define SATA_LOS_BIAS_MASK GENMASK(18, 16)
+#define SATA_M_CSYSREQ BIT(0)
+#define SATA_S_CSYSREQ BIT(16)
+#define SATA_REF_REPEATCLK_EN BIT(0)
+#define SATA_REF_USE_PAD BIT(20)
+#define SATA_MPLL_MULTIPLIER_MASK GENMASK(22, 16)
+#define SATA_P0_PHY_READY BIT(0)
+
+#define PLL_LOCK_SLEEP_US 10
+#define PLL_LOCK_TIMEOUT_US 1000
+
+struct eic7700_sata_phy {
+ u32 tx_amplitude_tuning_val[3];
+ u32 tx_preemph_tuning_val[3];
+ struct reset_control *rst;
+ struct regmap *regmap;
+ struct clk *clk;
+ struct phy *phy;
+};
+
+static const struct regmap_config eic7700_sata_phy_regmap_config = {
+ .reg_bits = 32,
+ .val_bits = 32,
+ .reg_stride = 4,
+ .max_register = SATA_LOS_IDEN,
+};
+
+static int wait_for_phy_ready(struct regmap *regmap, u32 reg, u32 checkbit,
+ u32 status)
+{
+ u32 val;
+ int ret;
+
+ ret = regmap_read_poll_timeout(regmap, reg, val,
+ (val & checkbit) == status,
+ PLL_LOCK_SLEEP_US, PLL_LOCK_TIMEOUT_US);
+
+ return ret;
+}
+
+static int eic7700_sata_phy_init(struct phy *phy)
+{
+ struct eic7700_sata_phy *sata_phy = phy_get_drvdata(phy);
+ u32 val;
+ int ret;
+
+ ret = clk_prepare_enable(sata_phy->clk);
+ if (ret)
+ return ret;
+
+ regmap_write(sata_phy->regmap, SATA_REF_CTRL1, SATA_CLK_RST_SOURCE_PHY);
+
+ val = FIELD_PREP(SATA_P0_PHY_TX_AMPLITUDE_GEN1_MASK,
+ sata_phy->tx_amplitude_tuning_val[0]) |
+ FIELD_PREP(SATA_P0_PHY_TX_AMPLITUDE_GEN2_MASK,
+ sata_phy->tx_amplitude_tuning_val[1]) |
+ FIELD_PREP(SATA_P0_PHY_TX_AMPLITUDE_GEN3_MASK,
+ sata_phy->tx_amplitude_tuning_val[2]);
+ regmap_write(sata_phy->regmap, SATA_PHY_CTRL0, val);
+
+ val = FIELD_PREP(SATA_P0_PHY_TX_PREEMPH_GEN1_MASK,
+ sata_phy->tx_preemph_tuning_val[0]) |
+ FIELD_PREP(SATA_P0_PHY_TX_PREEMPH_GEN2_MASK,
+ sata_phy->tx_preemph_tuning_val[1]) |
+ FIELD_PREP(SATA_P0_PHY_TX_PREEMPH_GEN3_MASK,
+ sata_phy->tx_preemph_tuning_val[2]);
+ regmap_write(sata_phy->regmap, SATA_PHY_CTRL1, val);
+
+ val = FIELD_PREP(SATA_LOS_LEVEL_MASK, 0x9) |
+ FIELD_PREP(SATA_LOS_BIAS_MASK, 0x2);
+ regmap_write(sata_phy->regmap, SATA_LOS_IDEN, val);
+
+ val = SATA_M_CSYSREQ | SATA_S_CSYSREQ;
+ regmap_write(sata_phy->regmap, SATA_AXI_LP_CTRL, val);
+
+ val = SATA_REF_REPEATCLK_EN | SATA_REF_USE_PAD;
+ regmap_write(sata_phy->regmap, SATA_REF_CTRL, val);
+
+ val = FIELD_PREP(SATA_MPLL_MULTIPLIER_MASK, 0x3c);
+ regmap_write(sata_phy->regmap, SATA_MPLL_CTRL, val);
+
+ usleep_range(15, 20);
+
+ ret = reset_control_deassert(sata_phy->rst);
+ if (ret)
+ goto disable_clk;
+
+ ret = wait_for_phy_ready(sata_phy->regmap, SATA_P0_PHY_STAT,
+ SATA_P0_PHY_READY, 1);
+ if (ret < 0) {
+ dev_err(&sata_phy->phy->dev, "PHY READY check failed\n");
+ goto disable_clk;
+ }
+
+ return 0;
+
+disable_clk:
+ clk_disable_unprepare(sata_phy->clk);
+ return ret;
+}
+
+static int eic7700_sata_phy_exit(struct phy *phy)
+{
+ struct eic7700_sata_phy *sata_phy = phy_get_drvdata(phy);
+ int ret;
+
+ ret = reset_control_assert(sata_phy->rst);
+ if (ret)
+ return ret;
+
+ clk_disable_unprepare(sata_phy->clk);
+
+ return 0;
+}
+
+static const struct phy_ops eic7700_sata_phy_ops = {
+ .init = eic7700_sata_phy_init,
+ .exit = eic7700_sata_phy_exit,
+ .owner = THIS_MODULE,
+};
+
+static void eic7700_get_tuning_param(struct device_node *np,
+ struct eic7700_sata_phy *sata_phy)
+{
+ if (of_property_read_u32_array
+ (np, "eswin,tx-amplitude-tuning",
+ sata_phy->tx_amplitude_tuning_val,
+ ARRAY_SIZE(sata_phy->tx_amplitude_tuning_val))) {
+ sata_phy->tx_amplitude_tuning_val[0] =
+ SATA_P0_PHY_TX_AMPLITUDE_GEN1_DEFAULT;
+ sata_phy->tx_amplitude_tuning_val[1] =
+ SATA_P0_PHY_TX_AMPLITUDE_GEN2_DEFAULT;
+ sata_phy->tx_amplitude_tuning_val[2] =
+ SATA_P0_PHY_TX_AMPLITUDE_GEN3_DEFAULT;
+ }
+
+ if (of_property_read_u32_array
+ (np, "eswin,tx-preemph-tuning",
+ sata_phy->tx_preemph_tuning_val,
+ ARRAY_SIZE(sata_phy->tx_preemph_tuning_val))) {
+ sata_phy->tx_preemph_tuning_val[0] =
+ SATA_P0_PHY_TX_PREEMPH_GEN1_DEFAULT;
+ sata_phy->tx_preemph_tuning_val[1] =
+ SATA_P0_PHY_TX_PREEMPH_GEN2_DEFAULT;
+ sata_phy->tx_preemph_tuning_val[2] =
+ SATA_P0_PHY_TX_PREEMPH_GEN3_DEFAULT;
+ }
+}
+
+static int eic7700_sata_phy_probe(struct platform_device *pdev)
+{
+ struct eic7700_sata_phy *sata_phy;
+ struct phy_provider *phy_provider;
+ struct device *dev = &pdev->dev;
+ struct device_node *np = dev->of_node;
+ struct resource *res;
+ void __iomem *regs;
+
+ sata_phy = devm_kzalloc(dev, sizeof(*sata_phy), GFP_KERNEL);
+ if (!sata_phy)
+ return -ENOMEM;
+
+ /*
+ * Map the I/O resource with platform_get_resource and devm_ioremap
+ * instead of the devm_platform_ioremap_resource API, because the
+ * address region of the SATA-PHY falls into the region of the HSP
+ * clock & reset that has already been obtained by the HSP
+ * clock-and-reset driver.
+ */
+ res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
+ if (!res)
+ return -ENOENT;
+
+ regs = devm_ioremap(dev, res->start, resource_size(res));
+ if (IS_ERR(regs))
+ return PTR_ERR(regs);
+
+ sata_phy->regmap = devm_regmap_init_mmio
+ (dev, regs, &eic7700_sata_phy_regmap_config);
+ if (IS_ERR(sata_phy->regmap))
+ return dev_err_probe(dev, PTR_ERR(sata_phy->regmap),
+ "failed to init regmap\n");
+
+ dev_set_drvdata(dev, sata_phy);
+
+ eic7700_get_tuning_param(np, sata_phy);
+
+ sata_phy->clk = devm_clk_get(dev, "phy");
+ if (IS_ERR(sata_phy->clk))
+ return PTR_ERR(sata_phy->clk);
+
+ sata_phy->rst = devm_reset_control_array_get_exclusive(dev);
+ if (IS_ERR(sata_phy->rst))
+ return dev_err_probe(dev, PTR_ERR(sata_phy->rst),
+ "failed to get reset control\n");
+
+ sata_phy->phy = devm_phy_create(dev, NULL, &eic7700_sata_phy_ops);
+ if (IS_ERR(sata_phy->phy))
+ return dev_err_probe(dev, PTR_ERR(sata_phy->phy),
+ "failed to create PHY\n");
+
+ phy_set_drvdata(sata_phy->phy, sata_phy);
+
+ phy_provider = devm_of_phy_provider_register(dev, of_phy_simple_xlate);
+ if (IS_ERR(phy_provider))
+ return dev_err_probe(dev, PTR_ERR(phy_provider),
+ "failed to register PHY provider\n");
+
+ return 0;
+}
+
+static const struct of_device_id eic7700_sata_phy_of_match[] = {
+ { .compatible = "eswin,eic7700-sata-phy" },
+ { },
+};
+MODULE_DEVICE_TABLE(of, eic7700_sata_phy_of_match);
+
+static struct platform_driver eic7700_sata_phy_driver = {
+ .probe = eic7700_sata_phy_probe,
+ .driver = {
+ .of_match_table = eic7700_sata_phy_of_match,
+ .name = "eic7700-sata-phy",
+ }
+};
+module_platform_driver(eic7700_sata_phy_driver);
+
+MODULE_DESCRIPTION("SATA PHY driver for the ESWIN EIC7700 SoC");
+MODULE_AUTHOR("Yulin Lu <luyulin@eswincomputing.com>");
+MODULE_LICENSE("GPL");
--
2.25.1 | {
"author": "Yulin Lu <luyulin@eswincomputing.com>",
"date": "Thu, 5 Feb 2026 16:22:19 +0800",
"is_openbsd": false,
"thread_id": "177220617042.330302.2707782153123727768.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Updates:
v9 -> v8:
- eswin,eic7700-sata-phy.yaml
- Modify the format of the "default" field in the
"eswin,tx-amplitude-tuning" and "eswin,tx-preemph-tuning"
properties.
- phy-eic7700-sata.c
- Correct the incorrectly formatted symbol "-" in the comments.
- Link to v8: https://lore.kernel.org/lkml/20260123024823.1612-1-luyulin@eswincomputing.com/
v8 -> v7:
- eswin,eic7700-sata-phy.yaml
- Add "eswin,tx-amplitude-tuning" and "eswin,tx-preemph-tuning"
properties, because these parameters may vary across different
circuit boards.
- Delete reviewed-by tag of Krzysztof Kozlowski, because the tuning
properties are introduced.
- phy-eic7700-sata.c
- Try to get SATA PHY transmitter amplitude and pre-emphasis signal
eye diagram tuning parameters from dts instead of hardcoded values
in the code. Because, these parameters may vary across different
circuit boards. Define default tuning parameters and use it when
these properties are not declared in dts.
- Add a comment to explain the reason for mapping I/O resources with
platform_get_resource and devm_ioremap instead of using the
devm_platform_ioremap_resource API.
- Link to v7: https://lore.kernel.org/lkml/20260106062944.1529-1-luyulin@eswincomputing.com/
v7 -> v6:
- phy-eic7700-sata.c
- Rename PHY_READY_TIMEOUT to PLL_LOCK_TIMEOUT_US with value 1000.
- Add macro PLL_LOCK_SLEEP_US set to 10.
- Add "goto disable_clk" in the eic7700_sata_phy_init function.
- Modify Copyright year from 2024 to 2026.
- Link to v6: https://lore.kernel.org/lkml/20251201060737.868-1-luyulin@eswincomputing.com/
v6 -> v5:
- eswin,eic7700-ahci.yaml
- Delete this file and it has already been applied in reply[1].
- eswin,eic7700-sata-phy.yaml
- Add clock and reset related properties.
- phy-eic7700-sata.c
- Map the io resource with platform_get_resource and devm_ioremap
instead of devm_platform_ioremap_resource API. Because the address
region of sata-phy falls into the region of hsp clock&reset which
has been got by hsp clock&reset driver.
- Use regmap_read_poll_timeout in wait_for_phy_ready to replace the
while loop check.
- Use devm_regmap_init_mmio and regmap_write to replace writel.
- Adapt to the clock and reset driver framework, replacing the
original readl and writel.
Because we are implementing the HSP layer clock and reset drivers,
the corresponding clock and reset registers can be registered into
the driver framework. And I have tested on the Sifive HiFive
Premier P550 board.
- Link to v5: https://lore.kernel.org/lkml/20250930083754.15-1-luyulin@eswincomputing.com/
v5 -> v4:
- eswin,eic7700-ahci.yaml
- Add "dt-bindings: ata:" prefix to the subject.
- Wrap at 80 characters in the YAML description field.
- Link to v4: https://lore.kernel.org/lkml/20250915125902.375-1-luyulin@eswincomputing.com/
v4 -> v3:
- eswin,eic7700-ahci.yaml
- Fix grammatical errors in patch subject and commit message
- Add an explanation in the commit message of patch 1 for retaining
the "ports-implemented" field, which Rob Herring suggested to
remove in the review comments on v2.
Link to Rob Herring's review:
https://lore.kernel.org/lkml/CAL_JsqKFotNLZZXwiy7S6K8qXLdGRAnsa-1zvZRDQBE39Gf5kg@mail.gmail.com/
Link to my question and Niklas Cassel's reply:
https://lore.kernel.org/lkml/aLBUC116MdJqDGIJ@flawful.org/
In this reply, Niklas Cassel mentioned his view:
If the ports-implemented register gets reset from
ahci_platform_assert_rsts(), then it seems acceptable to
retain the ports-implemented property in the device tree.
This aligns with our design.
Link to my reply:
https://lore.kernel.org/lkml/4ab70c6a.8be.198f47da494.Coremail.luyulin@eswincomputing.com/
Link to Niklas Cassel's question and my further explanation:
https://lore.kernel.org/lkml/aLlYkZWBaI5Yz6fo@ryzen/
https://lore.kernel.org/lkml/7206383a.d98.19918c22570.Coremail.luyulin@eswincomputing.com/
- eswin,eic7700-sata-phy.yaml
- Fix grammatical errors in patch subject and commit message
- Adjust the position of reg in the properties and required arrays
- Add reviewed-by tag of Krzysztof Kozlowski
- phy-eic7700-sata.c
- Correct the loop condition in wait_for_phy_ready() to use the
current jiffies instead of the fixed start time.
- Change the return value from -EFAULT to -ETIMEDOUT to correctly
indicate a timeout condition.
- Remove redundant clock disable handling in probe error path, as
SATA_SYS_CLK_EN is managed in phy_init() and phy_exit().
- Use dev_err_probe return in probe.
- Reorder local variables to follow reverse Xmas tree order.
- Wrap each line in the extended comments to 80 columns before
splitting lines.
- Adjust the position of `#include <linux/io.h>` for proper ordering.
- Link to v3: https://lore.kernel.org/lkml/20250904063427.1954-1-luyulin@eswincomputing.com/
v2 -> v3:
- Use full name in "From" and "Signed-off-by" fields information
- eswin,eic7700-ahci.yaml
- Remove the introduction to the reg, interrupts, phys, and
phy-names fields.
- Modify the usage of the clocks field in the examples.
- Correct the order of dt properties.
- phy-eic7700-sata.c
- Register operations use the GENMASK macro and FIELD_PREP instead
of the original bit offset method, and add
"#include <linux/bitfield.h>".
- Modify some macro definition names.
- Remove the redundant initialization assignments for "ret" and
"val".
- Delete ".suppress_bind_attrs = true".
- Modify the driver name.
- Add "#include <linux/io.h>" to fix the robot test issue.
- Link to v2: https://lore.kernel.org/lkml/20250819134722.220-1-luyulin@eswincomputing.com/
v2 -> v1:
- Delete the original controller driver and use ahci_dwc.c instead.
- Add eswin,eic7700-ahci.yaml
- Correct the descriptions of reset, interrupt and other hardware
resources for the sata controller on EIC7700 SoC.
- The clocks for both sata controller and sata PHY are controlled
via a register bit in the HSP bus and are not registered in the
clock tree. Clock are managed within the PHY driver, therefore it
is not described in this document.
- Add $ref: snps,dwc-ahci-common.yaml#.
- Add eswin,eic7700-sata-phy.yaml
- Add this file to include the description of the PHY on EIC7700 SoC.
- Add an eswin directory under the PHY driver path, and include the
SATA PHY driver code for EIC7700 SoC.
- Link to v1: https://lore.kernel.org/all/20250515085114.1692-1-hehuan1@eswincomputing.com/
Yulin Lu (2):
dt-bindings: phy: eswin: Document the EIC7700 SoC SATA PHY
phy: eswin: Create eswin directory and add EIC7700 SATA PHY driver
.../bindings/phy/eswin,eic7700-sata-phy.yaml | 92 ++++++
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/eswin/Kconfig | 14 +
drivers/phy/eswin/Makefile | 2 +
drivers/phy/eswin/phy-eic7700-sata.c | 273 ++++++++++++++++++
6 files changed, 383 insertions(+)
create mode 100644 Documentation/devicetree/bindings/phy/eswin,eic7700-sata-phy.yaml
create mode 100644 drivers/phy/eswin/Kconfig
create mode 100644 drivers/phy/eswin/Makefile
create mode 100644 drivers/phy/eswin/phy-eic7700-sata.c
--
2.25.1
| null | null | null | [PATCH v9 0/2] Add driver support for Eswin EIC7700 SoC SATA PHY | On Thu, Feb 05, 2026 at 04:21:29PM +0800, Yulin Lu wrote:
Reviewed-by: Krzysztof Kozlowski <krzysztof.kozlowski@oss.qualcomm.com>
Best regards,
Krzysztof | {
"author": "Krzysztof Kozlowski <krzk@kernel.org>",
"date": "Thu, 5 Feb 2026 14:41:44 +0100",
"is_openbsd": false,
"thread_id": "177220617042.330302.2707782153123727768.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Updates:
v9 -> v8:
- eswin,eic7700-sata-phy.yaml
- Modify the format of the "default" field in the
"eswin,tx-amplitude-tuning" and "eswin,tx-preemph-tuning"
properties.
- phy-eic7700-sata.c
- Correct the incorrectly formatted symbol "-" in the comments.
- Link to v8: https://lore.kernel.org/lkml/20260123024823.1612-1-luyulin@eswincomputing.com/
v8 -> v7:
- eswin,eic7700-sata-phy.yaml
- Add "eswin,tx-amplitude-tuning" and "eswin,tx-preemph-tuning"
properties, because these parameters may vary across different
circuit boards.
- Delete reviewed-by tag of Krzysztof Kozlowski, because the tuning
properties are introduced.
- phy-eic7700-sata.c
- Try to get SATA PHY transmitter amplitude and pre-emphasis signal
eye diagram tuning parameters from dts instead of hardcoded values
in the code. Because, these parameters may vary across different
circuit boards. Define default tuning parameters and use it when
these properties are not declared in dts.
- Add a comment to explain the reason for mapping I/O resources with
platform_get_resource and devm_ioremap instead of using the
devm_platform_ioremap_resource API.
- Link to v7: https://lore.kernel.org/lkml/20260106062944.1529-1-luyulin@eswincomputing.com/
v7 -> v6:
- phy-eic7700-sata.c
- Rename PHY_READY_TIMEOUT to PLL_LOCK_TIMEOUT_US with value 1000.
- Add macro PLL_LOCK_SLEEP_US set to 10.
- Add "goto disable_clk" in the eic7700_sata_phy_init function.
- Modify Copyright year from 2024 to 2026.
- Link to v6: https://lore.kernel.org/lkml/20251201060737.868-1-luyulin@eswincomputing.com/
v6 -> v5:
- eswin,eic7700-ahci.yaml
- Delete this file and it has already been applied in reply[1].
- eswin,eic7700-sata-phy.yaml
- Add clock and reset related properties.
- phy-eic7700-sata.c
- Map the io resource with platform_get_resource and devm_ioremap
instead of devm_platform_ioremap_resource API. Because the address
region of sata-phy falls into the region of hsp clock&reset which
has been got by hsp clock&reset driver.
- Use regmap_read_poll_timeout in wait_for_phy_ready to replace the
while loop check.
- Use devm_regmap_init_mmio and regmap_write to replace writel.
- Adapt to the clock and reset driver framework, replacing the
original readl and writel.
Because we are implementing the HSP layer clock and reset drivers,
the corresponding clock and reset registers can be registered into
the driver framework. And I have tested on the Sifive HiFive
Premier P550 board.
- Link to v5: https://lore.kernel.org/lkml/20250930083754.15-1-luyulin@eswincomputing.com/
v5 -> v4:
- eswin,eic7700-ahci.yaml
- Add "dt-bindings: ata:" prefix to the subject.
- Wrap at 80 characters in the YAML description field.
- Link to v4: https://lore.kernel.org/lkml/20250915125902.375-1-luyulin@eswincomputing.com/
v4 -> v3:
- eswin,eic7700-ahci.yaml
- Fix grammatical errors in patch subject and commit message
- Add an explanation in the commit message of patch 1 for retaining
the "ports-implemented" field, which Rob Herring suggested to
remove in the review comments on v2.
Link to Rob Herring's review:
https://lore.kernel.org/lkml/CAL_JsqKFotNLZZXwiy7S6K8qXLdGRAnsa-1zvZRDQBE39Gf5kg@mail.gmail.com/
Link to my question and Niklas Cassel's reply:
https://lore.kernel.org/lkml/aLBUC116MdJqDGIJ@flawful.org/
In this reply, Niklas Cassel mentioned his view:
If the ports-implemented register gets reset from
ahci_platform_assert_rsts(), then it seems acceptable to
retain the ports-implemented property in the device tree.
This aligns with our design.
Link to my reply:
https://lore.kernel.org/lkml/4ab70c6a.8be.198f47da494.Coremail.luyulin@eswincomputing.com/
Link to Niklas Cassel's question and my further explanation:
https://lore.kernel.org/lkml/aLlYkZWBaI5Yz6fo@ryzen/
https://lore.kernel.org/lkml/7206383a.d98.19918c22570.Coremail.luyulin@eswincomputing.com/
- eswin,eic7700-sata-phy.yaml
- Fix grammatical errors in patch subject and commit message
- Adjust the position of reg in the properties and required arrays
- Add reviewed-by tag of Krzysztof Kozlowski
- phy-eic7700-sata.c
- Correct the loop condition in wait_for_phy_ready() to use the
current jiffies instead of the fixed start time.
- Change the return value from -EFAULT to -ETIMEDOUT to correctly
indicate a timeout condition.
- Remove redundant clock disable handling in probe error path, as
SATA_SYS_CLK_EN is managed in phy_init() and phy_exit().
- Use dev_err_probe return in probe.
- Reorder local variables to follow reverse Xmas tree order.
- Wrap each line in the extended comments to 80 columns before
splitting lines.
- Adjust the position of `#include <linux/io.h>` for proper ordering.
- Link to v3: https://lore.kernel.org/lkml/20250904063427.1954-1-luyulin@eswincomputing.com/
v2 -> v3:
- Use full name in "From" and "Signed-off-by" fields information
- eswin,eic7700-ahci.yaml
- Remove the introduction to the reg, interrupts, phys, and
phy-names fields.
- Modify the usage of the clocks field in the examples.
- Correct the order of dt properties.
- phy-eic7700-sata.c
- Register operations use the GENMASK macro and FIELD_PREP instead
of the original bit offset method, and add
"#include <linux/bitfield.h>".
- Modify some macro definition names.
- Remove the redundant initialization assignments for "ret" and
"val".
- Delete ".suppress_bind_attrs = true".
- Modify the driver name.
- Add "#include <linux/io.h>" to fix the robot test issue.
- Link to v2: https://lore.kernel.org/lkml/20250819134722.220-1-luyulin@eswincomputing.com/
v2 -> v1:
- Delete the original controller driver and use ahci_dwc.c instead.
- Add eswin,eic7700-ahci.yaml
- Correct the descriptions of reset, interrupt and other hardware
resources for the sata controller on EIC7700 SoC.
- The clocks for both sata controller and sata PHY are controlled
via a register bit in the HSP bus and are not registered in the
clock tree. Clock are managed within the PHY driver, therefore it
is not described in this document.
- Add $ref: snps,dwc-ahci-common.yaml#.
- Add eswin,eic7700-sata-phy.yaml
- Add this file to include the description of the PHY on EIC7700 SoC.
- Add an eswin directory under the PHY driver path, and include the
SATA PHY driver code for EIC7700 SoC.
- Link to v1: https://lore.kernel.org/all/20250515085114.1692-1-hehuan1@eswincomputing.com/
Yulin Lu (2):
dt-bindings: phy: eswin: Document the EIC7700 SoC SATA PHY
phy: eswin: Create eswin directory and add EIC7700 SATA PHY driver
.../bindings/phy/eswin,eic7700-sata-phy.yaml | 92 ++++++
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/eswin/Kconfig | 14 +
drivers/phy/eswin/Makefile | 2 +
drivers/phy/eswin/phy-eic7700-sata.c | 273 ++++++++++++++++++
6 files changed, 383 insertions(+)
create mode 100644 Documentation/devicetree/bindings/phy/eswin,eic7700-sata-phy.yaml
create mode 100644 drivers/phy/eswin/Kconfig
create mode 100644 drivers/phy/eswin/Makefile
create mode 100644 drivers/phy/eswin/phy-eic7700-sata.c
--
2.25.1
| null | null | null | [PATCH v9 0/2] Add driver support for Eswin EIC7700 SoC SATA PHY | Hi Vinod, all,
In v7, I got driver review comments from Vinod. After fixing and submitting v8,
I received yaml comments from Krzysztof. v9 now has Reviewed-by from Krzysztof.
So I want to confirm whether there are any further comments on the driver code
in v9 and if it meets the requirements for merging.
Best regards,
Yulin Lu | {
"author": "\"Yulin Lu\" <luyulin@eswincomputing.com>",
"date": "Fri, 13 Feb 2026 14:20:26 +0800 (GMT+08:00)",
"is_openbsd": false,
"thread_id": "177220617042.330302.2707782153123727768.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | Updates:
v9 -> v8:
- eswin,eic7700-sata-phy.yaml
- Modify the format of the "default" field in the
"eswin,tx-amplitude-tuning" and "eswin,tx-preemph-tuning"
properties.
- phy-eic7700-sata.c
- Correct the incorrectly formatted symbol "-" in the comments.
- Link to v8: https://lore.kernel.org/lkml/20260123024823.1612-1-luyulin@eswincomputing.com/
v8 -> v7:
- eswin,eic7700-sata-phy.yaml
- Add "eswin,tx-amplitude-tuning" and "eswin,tx-preemph-tuning"
properties, because these parameters may vary across different
circuit boards.
- Delete reviewed-by tag of Krzysztof Kozlowski, because the tuning
properties are introduced.
- phy-eic7700-sata.c
- Try to get SATA PHY transmitter amplitude and pre-emphasis signal
eye diagram tuning parameters from dts instead of hardcoded values
in the code. Because, these parameters may vary across different
circuit boards. Define default tuning parameters and use it when
these properties are not declared in dts.
- Add a comment to explain the reason for mapping I/O resources with
platform_get_resource and devm_ioremap instead of using the
devm_platform_ioremap_resource API.
- Link to v7: https://lore.kernel.org/lkml/20260106062944.1529-1-luyulin@eswincomputing.com/
v7 -> v6:
- phy-eic7700-sata.c
- Rename PHY_READY_TIMEOUT to PLL_LOCK_TIMEOUT_US with value 1000.
- Add macro PLL_LOCK_SLEEP_US set to 10.
- Add "goto disable_clk" in the eic7700_sata_phy_init function.
- Modify Copyright year from 2024 to 2026.
- Link to v6: https://lore.kernel.org/lkml/20251201060737.868-1-luyulin@eswincomputing.com/
v6 -> v5:
- eswin,eic7700-ahci.yaml
- Delete this file and it has already been applied in reply[1].
- eswin,eic7700-sata-phy.yaml
- Add clock and reset related properties.
- phy-eic7700-sata.c
- Map the io resource with platform_get_resource and devm_ioremap
instead of devm_platform_ioremap_resource API. Because the address
region of sata-phy falls into the region of hsp clock&reset which
has been got by hsp clock&reset driver.
- Use regmap_read_poll_timeout in wait_for_phy_ready to replace the
while loop check.
- Use devm_regmap_init_mmio and regmap_write to replace writel.
- Adapt to the clock and reset driver framework, replacing the
original readl and writel.
Because we are implementing the HSP layer clock and reset drivers,
the corresponding clock and reset registers can be registered into
the driver framework. And I have tested on the Sifive HiFive
Premier P550 board.
- Link to v5: https://lore.kernel.org/lkml/20250930083754.15-1-luyulin@eswincomputing.com/
v5 -> v4:
- eswin,eic7700-ahci.yaml
- Add "dt-bindings: ata:" prefix to the subject.
- Wrap at 80 characters in the YAML description field.
- Link to v4: https://lore.kernel.org/lkml/20250915125902.375-1-luyulin@eswincomputing.com/
v4 -> v3:
- eswin,eic7700-ahci.yaml
- Fix grammatical errors in patch subject and commit message
- Add an explanation in the commit message of patch 1 for retaining
the "ports-implemented" field, which Rob Herring suggested to
remove in the review comments on v2.
Link to Rob Herring's review:
https://lore.kernel.org/lkml/CAL_JsqKFotNLZZXwiy7S6K8qXLdGRAnsa-1zvZRDQBE39Gf5kg@mail.gmail.com/
Link to my question and Niklas Cassel's reply:
https://lore.kernel.org/lkml/aLBUC116MdJqDGIJ@flawful.org/
In this reply, Niklas Cassel mentioned his view:
If the ports-implemented register gets reset from
ahci_platform_assert_rsts(), then it seems acceptable to
retain the ports-implemented property in the device tree.
This aligns with our design.
Link to my reply:
https://lore.kernel.org/lkml/4ab70c6a.8be.198f47da494.Coremail.luyulin@eswincomputing.com/
Link to Niklas Cassel's question and my further explanation:
https://lore.kernel.org/lkml/aLlYkZWBaI5Yz6fo@ryzen/
https://lore.kernel.org/lkml/7206383a.d98.19918c22570.Coremail.luyulin@eswincomputing.com/
- eswin,eic7700-sata-phy.yaml
- Fix grammatical errors in patch subject and commit message
- Adjust the position of reg in the properties and required arrays
- Add reviewed-by tag of Krzysztof Kozlowski
- phy-eic7700-sata.c
- Correct the loop condition in wait_for_phy_ready() to use the
current jiffies instead of the fixed start time.
- Change the return value from -EFAULT to -ETIMEDOUT to correctly
indicate a timeout condition.
- Remove redundant clock disable handling in probe error path, as
SATA_SYS_CLK_EN is managed in phy_init() and phy_exit().
- Use dev_err_probe return in probe.
- Reorder local variables to follow reverse Xmas tree order.
- Wrap each line in the extended comments to 80 columns before
splitting lines.
- Adjust the position of `#include <linux/io.h>` for proper ordering.
- Link to v3: https://lore.kernel.org/lkml/20250904063427.1954-1-luyulin@eswincomputing.com/
v2 -> v3:
- Use full name in "From" and "Signed-off-by" fields information
- eswin,eic7700-ahci.yaml
- Remove the introduction to the reg, interrupts, phys, and
phy-names fields.
- Modify the usage of the clocks field in the examples.
- Correct the order of dt properties.
- phy-eic7700-sata.c
- Register operations use the GENMASK macro and FIELD_PREP instead
of the original bit offset method, and add
"#include <linux/bitfield.h>".
- Modify some macro definition names.
- Remove the redundant initialization assignments for "ret" and
"val".
- Delete ".suppress_bind_attrs = true".
- Modify the driver name.
- Add "#include <linux/io.h>" to fix the robot test issue.
- Link to v2: https://lore.kernel.org/lkml/20250819134722.220-1-luyulin@eswincomputing.com/
v2 -> v1:
- Delete the original controller driver and use ahci_dwc.c instead.
- Add eswin,eic7700-ahci.yaml
- Correct the descriptions of reset, interrupt and other hardware
resources for the sata controller on EIC7700 SoC.
- The clocks for both sata controller and sata PHY are controlled
via a register bit in the HSP bus and are not registered in the
clock tree. Clock are managed within the PHY driver, therefore it
is not described in this document.
- Add $ref: snps,dwc-ahci-common.yaml#.
- Add eswin,eic7700-sata-phy.yaml
- Add this file to include the description of the PHY on EIC7700 SoC.
- Add an eswin directory under the PHY driver path, and include the
SATA PHY driver code for EIC7700 SoC.
- Link to v1: https://lore.kernel.org/all/20250515085114.1692-1-hehuan1@eswincomputing.com/
Yulin Lu (2):
dt-bindings: phy: eswin: Document the EIC7700 SoC SATA PHY
phy: eswin: Create eswin directory and add EIC7700 SATA PHY driver
.../bindings/phy/eswin,eic7700-sata-phy.yaml | 92 ++++++
drivers/phy/Kconfig | 1 +
drivers/phy/Makefile | 1 +
drivers/phy/eswin/Kconfig | 14 +
drivers/phy/eswin/Makefile | 2 +
drivers/phy/eswin/phy-eic7700-sata.c | 273 ++++++++++++++++++
6 files changed, 383 insertions(+)
create mode 100644 Documentation/devicetree/bindings/phy/eswin,eic7700-sata-phy.yaml
create mode 100644 drivers/phy/eswin/Kconfig
create mode 100644 drivers/phy/eswin/Makefile
create mode 100644 drivers/phy/eswin/phy-eic7700-sata.c
--
2.25.1
| null | null | null | [PATCH v9 0/2] Add driver support for Eswin EIC7700 SoC SATA PHY | On Thu, 05 Feb 2026 16:20:09 +0800, Yulin Lu wrote:
Applied, thanks!
[1/2] dt-bindings: phy: eswin: Document the EIC7700 SoC SATA PHY
commit: 820265f7b666d588bcb7df06f3332265c59e8cea
[2/2] phy: eswin: Create eswin directory and add EIC7700 SATA PHY driver
commit: 67ee9ccaa34a11c317411bb8e7d305d93d0b4111
Best regards,
--
~Vinod | {
"author": "Vinod Koul <vkoul@kernel.org>",
"date": "Fri, 27 Feb 2026 20:59:30 +0530",
"is_openbsd": false,
"thread_id": "177220617042.330302.2707782153123727768.b4-ty@kernel.org.mbox.gz"
} |
lkml_critique | lkml | When a process forks, the child process copies the parent's VMAs but the
user_mapped reference count is not incremented. As a result, when both the
parent and child processes exit, tracing_buffers_mmap_close() is called
twice. On the second call, user_mapped is already 0, causing the function to
return -ENODEV and triggering a WARN_ON.
Fix it by incrementing the user_mapped reference count without re-mapping
the pages in the VMA's open callback.
Fixes: cf9f0f7c4c5bb ("tracing: Allow user-space mapping of the ring-buffer")
Reported-by: syzbot+3b5dd2030fe08afdf65d@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=3b5dd2030fe08afdf65d
Tested-by: syzbot+3b5dd2030fe08afdf65d@syzkaller.appspotmail.com
Signed-off-by: Qing Wang <wangqing7171@gmail.com>
---
include/linux/ring_buffer.h | 1 +
kernel/trace/ring_buffer.c | 21 +++++++++++++++++++++
kernel/trace/trace.c | 13 +++++++++++++
3 files changed, 35 insertions(+)
diff --git a/include/linux/ring_buffer.h b/include/linux/ring_buffer.h
index 876358cfe1b1..d862fa610270 100644
--- a/include/linux/ring_buffer.h
+++ b/include/linux/ring_buffer.h
@@ -248,6 +248,7 @@ int trace_rb_cpu_prepare(unsigned int cpu, struct hlist_node *node);
int ring_buffer_map(struct trace_buffer *buffer, int cpu,
struct vm_area_struct *vma);
+void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu);
int ring_buffer_unmap(struct trace_buffer *buffer, int cpu);
int ring_buffer_map_get_reader(struct trace_buffer *buffer, int cpu);
#endif /* _LINUX_RING_BUFFER_H */
diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c
index f16f053ef77d..17d0ea0cc3e6 100644
--- a/kernel/trace/ring_buffer.c
+++ b/kernel/trace/ring_buffer.c
@@ -7310,6 +7310,27 @@ int ring_buffer_map(struct trace_buffer *buffer, int cpu,
return err;
}
+/*
+ * This is called when a VMA is duplicated (e.g., on fork()) to increment
+ * the user_mapped counter without remapping pages.
+ */
+void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu)
+{
+ struct ring_buffer_per_cpu *cpu_buffer;
+
+ if (WARN_ON(!cpumask_test_cpu(cpu, buffer->cpumask)))
+ return;
+
+ cpu_buffer = buffer->buffers[cpu];
+
+ guard(mutex)(&cpu_buffer->mapping_lock);
+
+ if (cpu_buffer->user_mapped)
+ __rb_inc_dec_mapped(cpu_buffer, true);
+ else
+ WARN(1, "Unexpected buffer stat, it should be mapped");
+}
+
int ring_buffer_unmap(struct trace_buffer *buffer, int cpu)
{
struct ring_buffer_per_cpu *cpu_buffer;
diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c
index 23de3719f495..1e7c032a72d2 100644
--- a/kernel/trace/trace.c
+++ b/kernel/trace/trace.c
@@ -8213,6 +8213,18 @@ static inline int get_snapshot_map(struct trace_array *tr) { return 0; }
static inline void put_snapshot_map(struct trace_array *tr) { }
#endif
+/*
+ * This is called when a VMA is duplicated (e.g., on fork()) to increment
+ * the user_mapped counter without remapping pages.
+ */
+static void tracing_buffers_mmap_open(struct vm_area_struct *vma)
+{
+ struct ftrace_buffer_info *info = vma->vm_file->private_data;
+ struct trace_iterator *iter = &info->iter;
+
+ ring_buffer_map_dup(iter->array_buffer->buffer, iter->cpu_file);
+}
+
static void tracing_buffers_mmap_close(struct vm_area_struct *vma)
{
struct ftrace_buffer_info *info = vma->vm_file->private_data;
@@ -8232,6 +8244,7 @@ static int tracing_buffers_may_split(struct vm_area_struct *vma, unsigned long a
}
static const struct vm_operations_struct tracing_buffers_vmops = {
+ .open = tracing_buffers_mmap_open,
.close = tracing_buffers_mmap_close,
.may_split = tracing_buffers_may_split,
};
--
2.34.1
| null | null | null | [PATCH] tracing: Fix WARN_ON in tracing_buffers_mmap_close | On Fri, Feb 27, 2026 at 10:58:42AM +0800, Qing Wang wrote:
Hum, not sure this is entirely correct. We do set VM_DONTCOPY when creating the
mapping (see __rb_map_vma). So AFAICT ->open() is not called in this situation (see
dup_mmap()) | {
"author": "Vincent Donnefort <vdonnefort@google.com>",
"date": "Fri, 27 Feb 2026 10:02:00 +0000",
"is_openbsd": false,
"thread_id": "aaG1Yl-HbPG3Buil@google.com.mbox.gz"
} |
lkml_critique | lkml | When a process forks, the child process copies the parent's VMAs but the
user_mapped reference count is not incremented. As a result, when both the
parent and child processes exit, tracing_buffers_mmap_close() is called
twice. On the second call, user_mapped is already 0, causing the function to
return -ENODEV and triggering a WARN_ON.
Fix it by incrementing the user_mapped reference count without re-mapping
the pages in the VMA's open callback.
Fixes: cf9f0f7c4c5bb ("tracing: Allow user-space mapping of the ring-buffer")
Reported-by: syzbot+3b5dd2030fe08afdf65d@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=3b5dd2030fe08afdf65d
Tested-by: syzbot+3b5dd2030fe08afdf65d@syzkaller.appspotmail.com
Signed-off-by: Qing Wang <wangqing7171@gmail.com>
---
include/linux/ring_buffer.h | 1 +
kernel/trace/ring_buffer.c | 21 +++++++++++++++++++++
kernel/trace/trace.c | 13 +++++++++++++
3 files changed, 35 insertions(+)
diff --git a/include/linux/ring_buffer.h b/include/linux/ring_buffer.h
index 876358cfe1b1..d862fa610270 100644
--- a/include/linux/ring_buffer.h
+++ b/include/linux/ring_buffer.h
@@ -248,6 +248,7 @@ int trace_rb_cpu_prepare(unsigned int cpu, struct hlist_node *node);
int ring_buffer_map(struct trace_buffer *buffer, int cpu,
struct vm_area_struct *vma);
+void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu);
int ring_buffer_unmap(struct trace_buffer *buffer, int cpu);
int ring_buffer_map_get_reader(struct trace_buffer *buffer, int cpu);
#endif /* _LINUX_RING_BUFFER_H */
diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c
index f16f053ef77d..17d0ea0cc3e6 100644
--- a/kernel/trace/ring_buffer.c
+++ b/kernel/trace/ring_buffer.c
@@ -7310,6 +7310,27 @@ int ring_buffer_map(struct trace_buffer *buffer, int cpu,
return err;
}
+/*
+ * This is called when a VMA is duplicated (e.g., on fork()) to increment
+ * the user_mapped counter without remapping pages.
+ */
+void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu)
+{
+ struct ring_buffer_per_cpu *cpu_buffer;
+
+ if (WARN_ON(!cpumask_test_cpu(cpu, buffer->cpumask)))
+ return;
+
+ cpu_buffer = buffer->buffers[cpu];
+
+ guard(mutex)(&cpu_buffer->mapping_lock);
+
+ if (cpu_buffer->user_mapped)
+ __rb_inc_dec_mapped(cpu_buffer, true);
+ else
+ WARN(1, "Unexpected buffer stat, it should be mapped");
+}
+
int ring_buffer_unmap(struct trace_buffer *buffer, int cpu)
{
struct ring_buffer_per_cpu *cpu_buffer;
diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c
index 23de3719f495..1e7c032a72d2 100644
--- a/kernel/trace/trace.c
+++ b/kernel/trace/trace.c
@@ -8213,6 +8213,18 @@ static inline int get_snapshot_map(struct trace_array *tr) { return 0; }
static inline void put_snapshot_map(struct trace_array *tr) { }
#endif
+/*
+ * This is called when a VMA is duplicated (e.g., on fork()) to increment
+ * the user_mapped counter without remapping pages.
+ */
+static void tracing_buffers_mmap_open(struct vm_area_struct *vma)
+{
+ struct ftrace_buffer_info *info = vma->vm_file->private_data;
+ struct trace_iterator *iter = &info->iter;
+
+ ring_buffer_map_dup(iter->array_buffer->buffer, iter->cpu_file);
+}
+
static void tracing_buffers_mmap_close(struct vm_area_struct *vma)
{
struct ftrace_buffer_info *info = vma->vm_file->private_data;
@@ -8232,6 +8244,7 @@ static int tracing_buffers_may_split(struct vm_area_struct *vma, unsigned long a
}
static const struct vm_operations_struct tracing_buffers_vmops = {
+ .open = tracing_buffers_mmap_open,
.close = tracing_buffers_mmap_close,
.may_split = tracing_buffers_may_split,
};
--
2.34.1
| null | null | null | [PATCH] tracing: Fix WARN_ON in tracing_buffers_mmap_close | On Fri, Feb 27, 2026 at 10:02:00AM +0000, Vincent Donnefort wrote:
Ah right, Syzkaller is using madvise(MADVISE_DOFORK) which resets VM_DONTCOPY. | {
"author": "Vincent Donnefort <vdonnefort@google.com>",
"date": "Fri, 27 Feb 2026 10:41:17 +0000",
"is_openbsd": false,
"thread_id": "aaG1Yl-HbPG3Buil@google.com.mbox.gz"
} |
lkml_critique | lkml | When a process forks, the child process copies the parent's VMAs but the
user_mapped reference count is not incremented. As a result, when both the
parent and child processes exit, tracing_buffers_mmap_close() is called
twice. On the second call, user_mapped is already 0, causing the function to
return -ENODEV and triggering a WARN_ON.
Fix it by incrementing the user_mapped reference count without re-mapping
the pages in the VMA's open callback.
Fixes: cf9f0f7c4c5bb ("tracing: Allow user-space mapping of the ring-buffer")
Reported-by: syzbot+3b5dd2030fe08afdf65d@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=3b5dd2030fe08afdf65d
Tested-by: syzbot+3b5dd2030fe08afdf65d@syzkaller.appspotmail.com
Signed-off-by: Qing Wang <wangqing7171@gmail.com>
---
include/linux/ring_buffer.h | 1 +
kernel/trace/ring_buffer.c | 21 +++++++++++++++++++++
kernel/trace/trace.c | 13 +++++++++++++
3 files changed, 35 insertions(+)
diff --git a/include/linux/ring_buffer.h b/include/linux/ring_buffer.h
index 876358cfe1b1..d862fa610270 100644
--- a/include/linux/ring_buffer.h
+++ b/include/linux/ring_buffer.h
@@ -248,6 +248,7 @@ int trace_rb_cpu_prepare(unsigned int cpu, struct hlist_node *node);
int ring_buffer_map(struct trace_buffer *buffer, int cpu,
struct vm_area_struct *vma);
+void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu);
int ring_buffer_unmap(struct trace_buffer *buffer, int cpu);
int ring_buffer_map_get_reader(struct trace_buffer *buffer, int cpu);
#endif /* _LINUX_RING_BUFFER_H */
diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c
index f16f053ef77d..17d0ea0cc3e6 100644
--- a/kernel/trace/ring_buffer.c
+++ b/kernel/trace/ring_buffer.c
@@ -7310,6 +7310,27 @@ int ring_buffer_map(struct trace_buffer *buffer, int cpu,
return err;
}
+/*
+ * This is called when a VMA is duplicated (e.g., on fork()) to increment
+ * the user_mapped counter without remapping pages.
+ */
+void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu)
+{
+ struct ring_buffer_per_cpu *cpu_buffer;
+
+ if (WARN_ON(!cpumask_test_cpu(cpu, buffer->cpumask)))
+ return;
+
+ cpu_buffer = buffer->buffers[cpu];
+
+ guard(mutex)(&cpu_buffer->mapping_lock);
+
+ if (cpu_buffer->user_mapped)
+ __rb_inc_dec_mapped(cpu_buffer, true);
+ else
+ WARN(1, "Unexpected buffer stat, it should be mapped");
+}
+
int ring_buffer_unmap(struct trace_buffer *buffer, int cpu)
{
struct ring_buffer_per_cpu *cpu_buffer;
diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c
index 23de3719f495..1e7c032a72d2 100644
--- a/kernel/trace/trace.c
+++ b/kernel/trace/trace.c
@@ -8213,6 +8213,18 @@ static inline int get_snapshot_map(struct trace_array *tr) { return 0; }
static inline void put_snapshot_map(struct trace_array *tr) { }
#endif
+/*
+ * This is called when a VMA is duplicated (e.g., on fork()) to increment
+ * the user_mapped counter without remapping pages.
+ */
+static void tracing_buffers_mmap_open(struct vm_area_struct *vma)
+{
+ struct ftrace_buffer_info *info = vma->vm_file->private_data;
+ struct trace_iterator *iter = &info->iter;
+
+ ring_buffer_map_dup(iter->array_buffer->buffer, iter->cpu_file);
+}
+
static void tracing_buffers_mmap_close(struct vm_area_struct *vma)
{
struct ftrace_buffer_info *info = vma->vm_file->private_data;
@@ -8232,6 +8244,7 @@ static int tracing_buffers_may_split(struct vm_area_struct *vma, unsigned long a
}
static const struct vm_operations_struct tracing_buffers_vmops = {
+ .open = tracing_buffers_mmap_open,
.close = tracing_buffers_mmap_close,
.may_split = tracing_buffers_may_split,
};
--
2.34.1
| null | null | null | [PATCH] tracing: Fix WARN_ON in tracing_buffers_mmap_close | On Fri, Feb 27, 2026 at 10:41:17AM +0000, Vincent Donnefort wrote:
As we are applying restrictive rules for this mapping, I believe setting VM_IO
might be a better fix. | {
"author": "Vincent Donnefort <vdonnefort@google.com>",
"date": "Fri, 27 Feb 2026 11:22:22 +0000",
"is_openbsd": false,
"thread_id": "aaG1Yl-HbPG3Buil@google.com.mbox.gz"
} |
lkml_critique | lkml | When a process forks, the child process copies the parent's VMAs but the
user_mapped reference count is not incremented. As a result, when both the
parent and child processes exit, tracing_buffers_mmap_close() is called
twice. On the second call, user_mapped is already 0, causing the function to
return -ENODEV and triggering a WARN_ON.
Fix it by incrementing the user_mapped reference count without re-mapping
the pages in the VMA's open callback.
Fixes: cf9f0f7c4c5bb ("tracing: Allow user-space mapping of the ring-buffer")
Reported-by: syzbot+3b5dd2030fe08afdf65d@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=3b5dd2030fe08afdf65d
Tested-by: syzbot+3b5dd2030fe08afdf65d@syzkaller.appspotmail.com
Signed-off-by: Qing Wang <wangqing7171@gmail.com>
---
include/linux/ring_buffer.h | 1 +
kernel/trace/ring_buffer.c | 21 +++++++++++++++++++++
kernel/trace/trace.c | 13 +++++++++++++
3 files changed, 35 insertions(+)
diff --git a/include/linux/ring_buffer.h b/include/linux/ring_buffer.h
index 876358cfe1b1..d862fa610270 100644
--- a/include/linux/ring_buffer.h
+++ b/include/linux/ring_buffer.h
@@ -248,6 +248,7 @@ int trace_rb_cpu_prepare(unsigned int cpu, struct hlist_node *node);
int ring_buffer_map(struct trace_buffer *buffer, int cpu,
struct vm_area_struct *vma);
+void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu);
int ring_buffer_unmap(struct trace_buffer *buffer, int cpu);
int ring_buffer_map_get_reader(struct trace_buffer *buffer, int cpu);
#endif /* _LINUX_RING_BUFFER_H */
diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c
index f16f053ef77d..17d0ea0cc3e6 100644
--- a/kernel/trace/ring_buffer.c
+++ b/kernel/trace/ring_buffer.c
@@ -7310,6 +7310,27 @@ int ring_buffer_map(struct trace_buffer *buffer, int cpu,
return err;
}
+/*
+ * This is called when a VMA is duplicated (e.g., on fork()) to increment
+ * the user_mapped counter without remapping pages.
+ */
+void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu)
+{
+ struct ring_buffer_per_cpu *cpu_buffer;
+
+ if (WARN_ON(!cpumask_test_cpu(cpu, buffer->cpumask)))
+ return;
+
+ cpu_buffer = buffer->buffers[cpu];
+
+ guard(mutex)(&cpu_buffer->mapping_lock);
+
+ if (cpu_buffer->user_mapped)
+ __rb_inc_dec_mapped(cpu_buffer, true);
+ else
+ WARN(1, "Unexpected buffer stat, it should be mapped");
+}
+
int ring_buffer_unmap(struct trace_buffer *buffer, int cpu)
{
struct ring_buffer_per_cpu *cpu_buffer;
diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c
index 23de3719f495..1e7c032a72d2 100644
--- a/kernel/trace/trace.c
+++ b/kernel/trace/trace.c
@@ -8213,6 +8213,18 @@ static inline int get_snapshot_map(struct trace_array *tr) { return 0; }
static inline void put_snapshot_map(struct trace_array *tr) { }
#endif
+/*
+ * This is called when a VMA is duplicated (e.g., on fork()) to increment
+ * the user_mapped counter without remapping pages.
+ */
+static void tracing_buffers_mmap_open(struct vm_area_struct *vma)
+{
+ struct ftrace_buffer_info *info = vma->vm_file->private_data;
+ struct trace_iterator *iter = &info->iter;
+
+ ring_buffer_map_dup(iter->array_buffer->buffer, iter->cpu_file);
+}
+
static void tracing_buffers_mmap_close(struct vm_area_struct *vma)
{
struct ftrace_buffer_info *info = vma->vm_file->private_data;
@@ -8232,6 +8244,7 @@ static int tracing_buffers_may_split(struct vm_area_struct *vma, unsigned long a
}
static const struct vm_operations_struct tracing_buffers_vmops = {
+ .open = tracing_buffers_mmap_open,
.close = tracing_buffers_mmap_close,
.may_split = tracing_buffers_may_split,
};
--
2.34.1
| null | null | null | [PATCH] tracing: Fix WARN_ON in tracing_buffers_mmap_close | On Fri, 27 Feb 2026 10:41:17 +0000
Vincent Donnefort <vdonnefort@google.com> wrote:
Hmm,
So this means user space can override the DONTCOPY? Can this cause bugs
elsewhere that DONTCOPY is used?
-- Steve | {
"author": "Steven Rostedt <rostedt@goodmis.org>",
"date": "Fri, 27 Feb 2026 10:10:02 -0500",
"is_openbsd": false,
"thread_id": "aaG1Yl-HbPG3Buil@google.com.mbox.gz"
} |
lkml_critique | lkml | When a process forks, the child process copies the parent's VMAs but the
user_mapped reference count is not incremented. As a result, when both the
parent and child processes exit, tracing_buffers_mmap_close() is called
twice. On the second call, user_mapped is already 0, causing the function to
return -ENODEV and triggering a WARN_ON.
Fix it by incrementing the user_mapped reference count without re-mapping
the pages in the VMA's open callback.
Fixes: cf9f0f7c4c5bb ("tracing: Allow user-space mapping of the ring-buffer")
Reported-by: syzbot+3b5dd2030fe08afdf65d@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=3b5dd2030fe08afdf65d
Tested-by: syzbot+3b5dd2030fe08afdf65d@syzkaller.appspotmail.com
Signed-off-by: Qing Wang <wangqing7171@gmail.com>
---
include/linux/ring_buffer.h | 1 +
kernel/trace/ring_buffer.c | 21 +++++++++++++++++++++
kernel/trace/trace.c | 13 +++++++++++++
3 files changed, 35 insertions(+)
diff --git a/include/linux/ring_buffer.h b/include/linux/ring_buffer.h
index 876358cfe1b1..d862fa610270 100644
--- a/include/linux/ring_buffer.h
+++ b/include/linux/ring_buffer.h
@@ -248,6 +248,7 @@ int trace_rb_cpu_prepare(unsigned int cpu, struct hlist_node *node);
int ring_buffer_map(struct trace_buffer *buffer, int cpu,
struct vm_area_struct *vma);
+void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu);
int ring_buffer_unmap(struct trace_buffer *buffer, int cpu);
int ring_buffer_map_get_reader(struct trace_buffer *buffer, int cpu);
#endif /* _LINUX_RING_BUFFER_H */
diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c
index f16f053ef77d..17d0ea0cc3e6 100644
--- a/kernel/trace/ring_buffer.c
+++ b/kernel/trace/ring_buffer.c
@@ -7310,6 +7310,27 @@ int ring_buffer_map(struct trace_buffer *buffer, int cpu,
return err;
}
+/*
+ * This is called when a VMA is duplicated (e.g., on fork()) to increment
+ * the user_mapped counter without remapping pages.
+ */
+void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu)
+{
+ struct ring_buffer_per_cpu *cpu_buffer;
+
+ if (WARN_ON(!cpumask_test_cpu(cpu, buffer->cpumask)))
+ return;
+
+ cpu_buffer = buffer->buffers[cpu];
+
+ guard(mutex)(&cpu_buffer->mapping_lock);
+
+ if (cpu_buffer->user_mapped)
+ __rb_inc_dec_mapped(cpu_buffer, true);
+ else
+ WARN(1, "Unexpected buffer stat, it should be mapped");
+}
+
int ring_buffer_unmap(struct trace_buffer *buffer, int cpu)
{
struct ring_buffer_per_cpu *cpu_buffer;
diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c
index 23de3719f495..1e7c032a72d2 100644
--- a/kernel/trace/trace.c
+++ b/kernel/trace/trace.c
@@ -8213,6 +8213,18 @@ static inline int get_snapshot_map(struct trace_array *tr) { return 0; }
static inline void put_snapshot_map(struct trace_array *tr) { }
#endif
+/*
+ * This is called when a VMA is duplicated (e.g., on fork()) to increment
+ * the user_mapped counter without remapping pages.
+ */
+static void tracing_buffers_mmap_open(struct vm_area_struct *vma)
+{
+ struct ftrace_buffer_info *info = vma->vm_file->private_data;
+ struct trace_iterator *iter = &info->iter;
+
+ ring_buffer_map_dup(iter->array_buffer->buffer, iter->cpu_file);
+}
+
static void tracing_buffers_mmap_close(struct vm_area_struct *vma)
{
struct ftrace_buffer_info *info = vma->vm_file->private_data;
@@ -8232,6 +8244,7 @@ static int tracing_buffers_may_split(struct vm_area_struct *vma, unsigned long a
}
static const struct vm_operations_struct tracing_buffers_vmops = {
+ .open = tracing_buffers_mmap_open,
.close = tracing_buffers_mmap_close,
.may_split = tracing_buffers_may_split,
};
--
2.34.1
| null | null | null | [PATCH] tracing: Fix WARN_ON in tracing_buffers_mmap_close | On Fri, Feb 27, 2026 at 10:10:02AM -0500, Steven Rostedt wrote:
Indeed, user space can clear DONTCOPY... unless we also set VM_IO. | {
"author": "Vincent Donnefort <vdonnefort@google.com>",
"date": "Fri, 27 Feb 2026 15:16:50 +0000",
"is_openbsd": false,
"thread_id": "aaG1Yl-HbPG3Buil@google.com.mbox.gz"
} |
lkml_critique | lkml | When a process forks, the child process copies the parent's VMAs but the
user_mapped reference count is not incremented. As a result, when both the
parent and child processes exit, tracing_buffers_mmap_close() is called
twice. On the second call, user_mapped is already 0, causing the function to
return -ENODEV and triggering a WARN_ON.
Fix it by incrementing the user_mapped reference count without re-mapping
the pages in the VMA's open callback.
Fixes: cf9f0f7c4c5bb ("tracing: Allow user-space mapping of the ring-buffer")
Reported-by: syzbot+3b5dd2030fe08afdf65d@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=3b5dd2030fe08afdf65d
Tested-by: syzbot+3b5dd2030fe08afdf65d@syzkaller.appspotmail.com
Signed-off-by: Qing Wang <wangqing7171@gmail.com>
---
include/linux/ring_buffer.h | 1 +
kernel/trace/ring_buffer.c | 21 +++++++++++++++++++++
kernel/trace/trace.c | 13 +++++++++++++
3 files changed, 35 insertions(+)
diff --git a/include/linux/ring_buffer.h b/include/linux/ring_buffer.h
index 876358cfe1b1..d862fa610270 100644
--- a/include/linux/ring_buffer.h
+++ b/include/linux/ring_buffer.h
@@ -248,6 +248,7 @@ int trace_rb_cpu_prepare(unsigned int cpu, struct hlist_node *node);
int ring_buffer_map(struct trace_buffer *buffer, int cpu,
struct vm_area_struct *vma);
+void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu);
int ring_buffer_unmap(struct trace_buffer *buffer, int cpu);
int ring_buffer_map_get_reader(struct trace_buffer *buffer, int cpu);
#endif /* _LINUX_RING_BUFFER_H */
diff --git a/kernel/trace/ring_buffer.c b/kernel/trace/ring_buffer.c
index f16f053ef77d..17d0ea0cc3e6 100644
--- a/kernel/trace/ring_buffer.c
+++ b/kernel/trace/ring_buffer.c
@@ -7310,6 +7310,27 @@ int ring_buffer_map(struct trace_buffer *buffer, int cpu,
return err;
}
+/*
+ * This is called when a VMA is duplicated (e.g., on fork()) to increment
+ * the user_mapped counter without remapping pages.
+ */
+void ring_buffer_map_dup(struct trace_buffer *buffer, int cpu)
+{
+ struct ring_buffer_per_cpu *cpu_buffer;
+
+ if (WARN_ON(!cpumask_test_cpu(cpu, buffer->cpumask)))
+ return;
+
+ cpu_buffer = buffer->buffers[cpu];
+
+ guard(mutex)(&cpu_buffer->mapping_lock);
+
+ if (cpu_buffer->user_mapped)
+ __rb_inc_dec_mapped(cpu_buffer, true);
+ else
+ WARN(1, "Unexpected buffer stat, it should be mapped");
+}
+
int ring_buffer_unmap(struct trace_buffer *buffer, int cpu)
{
struct ring_buffer_per_cpu *cpu_buffer;
diff --git a/kernel/trace/trace.c b/kernel/trace/trace.c
index 23de3719f495..1e7c032a72d2 100644
--- a/kernel/trace/trace.c
+++ b/kernel/trace/trace.c
@@ -8213,6 +8213,18 @@ static inline int get_snapshot_map(struct trace_array *tr) { return 0; }
static inline void put_snapshot_map(struct trace_array *tr) { }
#endif
+/*
+ * This is called when a VMA is duplicated (e.g., on fork()) to increment
+ * the user_mapped counter without remapping pages.
+ */
+static void tracing_buffers_mmap_open(struct vm_area_struct *vma)
+{
+ struct ftrace_buffer_info *info = vma->vm_file->private_data;
+ struct trace_iterator *iter = &info->iter;
+
+ ring_buffer_map_dup(iter->array_buffer->buffer, iter->cpu_file);
+}
+
static void tracing_buffers_mmap_close(struct vm_area_struct *vma)
{
struct ftrace_buffer_info *info = vma->vm_file->private_data;
@@ -8232,6 +8244,7 @@ static int tracing_buffers_may_split(struct vm_area_struct *vma, unsigned long a
}
static const struct vm_operations_struct tracing_buffers_vmops = {
+ .open = tracing_buffers_mmap_open,
.close = tracing_buffers_mmap_close,
.may_split = tracing_buffers_may_split,
};
--
2.34.1
| null | null | null | [PATCH] tracing: Fix WARN_ON in tracing_buffers_mmap_close | On Fri, 27 Feb 2026 11:22:22 +0000
Vincent Donnefort <vdonnefort@google.com> wrote:
Agreed.
-- Steve | {
"author": "Steven Rostedt <rostedt@goodmis.org>",
"date": "Fri, 27 Feb 2026 10:20:38 -0500",
"is_openbsd": false,
"thread_id": "aaG1Yl-HbPG3Buil@google.com.mbox.gz"
} |
lkml_critique | lkml | Add methods to get a reference to the contained value or populate the
SetOnce if empty. The new `as_ref_or_populate` method accepts a value
directly, while `as_ref_or_populate_with` accepts a fallible closure,
allowing for lazy initialization that may fail. Both methods spin-wait
if another thread is concurrently initializing the container.
Also add `populate_with` which takes a fallible closure and serves as
the implementation basis for the other populate methods.
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
rust/kernel/sync/set_once.rs | 53 ++++++++++++++++++++++++++++++++++++++------
1 file changed, 46 insertions(+), 7 deletions(-)
diff --git a/rust/kernel/sync/set_once.rs b/rust/kernel/sync/set_once.rs
index bdba601807d8b..9e3c4be4047f8 100644
--- a/rust/kernel/sync/set_once.rs
+++ b/rust/kernel/sync/set_once.rs
@@ -2,11 +2,14 @@
//! A container that can be initialized at most once.
-use super::atomic::{
- ordering::{Acquire, Relaxed, Release},
- Atomic,
-};
use core::{cell::UnsafeCell, mem::MaybeUninit};
+use kernel::{
+ error::Result,
+ sync::atomic::{
+ ordering::{Acquire, Relaxed, Release},
+ Atomic,
+ },
+};
/// A container that can be populated at most once. Thread safe.
///
@@ -76,10 +79,46 @@ pub fn as_ref(&self) -> Option<&T> {
}
}
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with the value returned by `callable` and return a reference to that
+ /// object.
+ pub fn as_ref_or_populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<&T> {
+ if !self.populate_with(callable)? {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ Ok(unsafe { &*self.value.get().cast() })
+ }
+
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with `value` and return a reference to that object.
+ pub fn as_ref_or_populate(&self, value: T) -> &T {
+ if !self.populate(value) {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ unsafe { &*self.value.get().cast() }
+ }
+
/// Populate the [`SetOnce`].
///
/// Returns `true` if the [`SetOnce`] was successfully populated.
pub fn populate(&self, value: T) -> bool {
+ self.populate_with(|| Ok(value)).expect("Cannot error")
+ }
+
+ /// Populate the [`SetOnce`] with the value returned by `callable`.
+ ///
+ /// Returns `true` if the [`SetOnce`] was successfully populated.
+ pub fn populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<bool> {
// INVARIANT: If the swap succeeds:
// - We increase `init`.
// - We write the valid value `1` to `init`.
@@ -88,16 +127,16 @@ pub fn populate(&self, value: T) -> bool {
if let Ok(0) = self.init.cmpxchg(0, 1, Relaxed) {
// SAFETY: By the type invariants of `Self`, the fact that we succeeded in writing `1`
// to `self.init` means we obtained exclusive access to `self.value`.
- unsafe { core::ptr::write(self.value.get().cast(), value) };
+ unsafe { core::ptr::write(self.value.get().cast(), callable()?) };
// INVARIANT:
// - We increase `init`.
// - We write the valid value `2` to `init`.
// - We release our exclusive access to `self.value` and it is now valid for shared
// access.
self.init.store(2, Release);
- true
+ Ok(true)
} else {
- false
+ Ok(false)
}
}
---
base-commit: 05f7e89ab9731565d8a62e3b5d1ec206485eeb0b
change-id: 20260215-set-once-lazy-c73fc34a55d9
Best regards,
--
Andreas Hindborg <a.hindborg@kernel.org>
| null | null | null | [PATCH] rust: sync: add lazy initialization methods to SetOnce | On Sun Feb 15, 2026 at 9:27 PM CET, Andreas Hindborg wrote:
I would name the argument `create`, but not `callable`. Same below.
Cheers,
Benno | {
"author": "\"Benno Lossin\" <lossin@kernel.org>",
"date": "Mon, 16 Feb 2026 00:28:02 +0100",
"is_openbsd": false,
"thread_id": "DGPTYBO26YBT.3S14I9F5YT1PW@garyguo.net.mbox.gz"
} |
lkml_critique | lkml | Add methods to get a reference to the contained value or populate the
SetOnce if empty. The new `as_ref_or_populate` method accepts a value
directly, while `as_ref_or_populate_with` accepts a fallible closure,
allowing for lazy initialization that may fail. Both methods spin-wait
if another thread is concurrently initializing the container.
Also add `populate_with` which takes a fallible closure and serves as
the implementation basis for the other populate methods.
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
rust/kernel/sync/set_once.rs | 53 ++++++++++++++++++++++++++++++++++++++------
1 file changed, 46 insertions(+), 7 deletions(-)
diff --git a/rust/kernel/sync/set_once.rs b/rust/kernel/sync/set_once.rs
index bdba601807d8b..9e3c4be4047f8 100644
--- a/rust/kernel/sync/set_once.rs
+++ b/rust/kernel/sync/set_once.rs
@@ -2,11 +2,14 @@
//! A container that can be initialized at most once.
-use super::atomic::{
- ordering::{Acquire, Relaxed, Release},
- Atomic,
-};
use core::{cell::UnsafeCell, mem::MaybeUninit};
+use kernel::{
+ error::Result,
+ sync::atomic::{
+ ordering::{Acquire, Relaxed, Release},
+ Atomic,
+ },
+};
/// A container that can be populated at most once. Thread safe.
///
@@ -76,10 +79,46 @@ pub fn as_ref(&self) -> Option<&T> {
}
}
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with the value returned by `callable` and return a reference to that
+ /// object.
+ pub fn as_ref_or_populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<&T> {
+ if !self.populate_with(callable)? {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ Ok(unsafe { &*self.value.get().cast() })
+ }
+
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with `value` and return a reference to that object.
+ pub fn as_ref_or_populate(&self, value: T) -> &T {
+ if !self.populate(value) {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ unsafe { &*self.value.get().cast() }
+ }
+
/// Populate the [`SetOnce`].
///
/// Returns `true` if the [`SetOnce`] was successfully populated.
pub fn populate(&self, value: T) -> bool {
+ self.populate_with(|| Ok(value)).expect("Cannot error")
+ }
+
+ /// Populate the [`SetOnce`] with the value returned by `callable`.
+ ///
+ /// Returns `true` if the [`SetOnce`] was successfully populated.
+ pub fn populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<bool> {
// INVARIANT: If the swap succeeds:
// - We increase `init`.
// - We write the valid value `1` to `init`.
@@ -88,16 +127,16 @@ pub fn populate(&self, value: T) -> bool {
if let Ok(0) = self.init.cmpxchg(0, 1, Relaxed) {
// SAFETY: By the type invariants of `Self`, the fact that we succeeded in writing `1`
// to `self.init` means we obtained exclusive access to `self.value`.
- unsafe { core::ptr::write(self.value.get().cast(), value) };
+ unsafe { core::ptr::write(self.value.get().cast(), callable()?) };
// INVARIANT:
// - We increase `init`.
// - We write the valid value `2` to `init`.
// - We release our exclusive access to `self.value` and it is now valid for shared
// access.
self.init.store(2, Release);
- true
+ Ok(true)
} else {
- false
+ Ok(false)
}
}
---
base-commit: 05f7e89ab9731565d8a62e3b5d1ec206485eeb0b
change-id: 20260215-set-once-lazy-c73fc34a55d9
Best regards,
--
Andreas Hindborg <a.hindborg@kernel.org>
| null | null | null | [PATCH] rust: sync: add lazy initialization methods to SetOnce | On Sun, Feb 15, 2026 at 09:27:17PM +0100, Andreas Hindborg wrote:
We should not be implementing our own spinlocks.
Alice | {
"author": "Alice Ryhl <aliceryhl@google.com>",
"date": "Mon, 16 Feb 2026 08:46:36 +0000",
"is_openbsd": false,
"thread_id": "DGPTYBO26YBT.3S14I9F5YT1PW@garyguo.net.mbox.gz"
} |
lkml_critique | lkml | Add methods to get a reference to the contained value or populate the
SetOnce if empty. The new `as_ref_or_populate` method accepts a value
directly, while `as_ref_or_populate_with` accepts a fallible closure,
allowing for lazy initialization that may fail. Both methods spin-wait
if another thread is concurrently initializing the container.
Also add `populate_with` which takes a fallible closure and serves as
the implementation basis for the other populate methods.
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
rust/kernel/sync/set_once.rs | 53 ++++++++++++++++++++++++++++++++++++++------
1 file changed, 46 insertions(+), 7 deletions(-)
diff --git a/rust/kernel/sync/set_once.rs b/rust/kernel/sync/set_once.rs
index bdba601807d8b..9e3c4be4047f8 100644
--- a/rust/kernel/sync/set_once.rs
+++ b/rust/kernel/sync/set_once.rs
@@ -2,11 +2,14 @@
//! A container that can be initialized at most once.
-use super::atomic::{
- ordering::{Acquire, Relaxed, Release},
- Atomic,
-};
use core::{cell::UnsafeCell, mem::MaybeUninit};
+use kernel::{
+ error::Result,
+ sync::atomic::{
+ ordering::{Acquire, Relaxed, Release},
+ Atomic,
+ },
+};
/// A container that can be populated at most once. Thread safe.
///
@@ -76,10 +79,46 @@ pub fn as_ref(&self) -> Option<&T> {
}
}
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with the value returned by `callable` and return a reference to that
+ /// object.
+ pub fn as_ref_or_populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<&T> {
+ if !self.populate_with(callable)? {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ Ok(unsafe { &*self.value.get().cast() })
+ }
+
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with `value` and return a reference to that object.
+ pub fn as_ref_or_populate(&self, value: T) -> &T {
+ if !self.populate(value) {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ unsafe { &*self.value.get().cast() }
+ }
+
/// Populate the [`SetOnce`].
///
/// Returns `true` if the [`SetOnce`] was successfully populated.
pub fn populate(&self, value: T) -> bool {
+ self.populate_with(|| Ok(value)).expect("Cannot error")
+ }
+
+ /// Populate the [`SetOnce`] with the value returned by `callable`.
+ ///
+ /// Returns `true` if the [`SetOnce`] was successfully populated.
+ pub fn populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<bool> {
// INVARIANT: If the swap succeeds:
// - We increase `init`.
// - We write the valid value `1` to `init`.
@@ -88,16 +127,16 @@ pub fn populate(&self, value: T) -> bool {
if let Ok(0) = self.init.cmpxchg(0, 1, Relaxed) {
// SAFETY: By the type invariants of `Self`, the fact that we succeeded in writing `1`
// to `self.init` means we obtained exclusive access to `self.value`.
- unsafe { core::ptr::write(self.value.get().cast(), value) };
+ unsafe { core::ptr::write(self.value.get().cast(), callable()?) };
// INVARIANT:
// - We increase `init`.
// - We write the valid value `2` to `init`.
// - We release our exclusive access to `self.value` and it is now valid for shared
// access.
self.init.store(2, Release);
- true
+ Ok(true)
} else {
- false
+ Ok(false)
}
}
---
base-commit: 05f7e89ab9731565d8a62e3b5d1ec206485eeb0b
change-id: 20260215-set-once-lazy-c73fc34a55d9
Best regards,
--
Andreas Hindborg <a.hindborg@kernel.org>
| null | null | null | [PATCH] rust: sync: add lazy initialization methods to SetOnce | "Alice Ryhl" <aliceryhl@google.com> writes:
That is a great proverb. I'd be happy to receive a suggestion on an
alternate approach for this particular context.
Best regards,
Andreas Hindborg | {
"author": "Andreas Hindborg <a.hindborg@kernel.org>",
"date": "Mon, 16 Feb 2026 12:10:16 +0100",
"is_openbsd": false,
"thread_id": "DGPTYBO26YBT.3S14I9F5YT1PW@garyguo.net.mbox.gz"
} |
lkml_critique | lkml | Add methods to get a reference to the contained value or populate the
SetOnce if empty. The new `as_ref_or_populate` method accepts a value
directly, while `as_ref_or_populate_with` accepts a fallible closure,
allowing for lazy initialization that may fail. Both methods spin-wait
if another thread is concurrently initializing the container.
Also add `populate_with` which takes a fallible closure and serves as
the implementation basis for the other populate methods.
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
rust/kernel/sync/set_once.rs | 53 ++++++++++++++++++++++++++++++++++++++------
1 file changed, 46 insertions(+), 7 deletions(-)
diff --git a/rust/kernel/sync/set_once.rs b/rust/kernel/sync/set_once.rs
index bdba601807d8b..9e3c4be4047f8 100644
--- a/rust/kernel/sync/set_once.rs
+++ b/rust/kernel/sync/set_once.rs
@@ -2,11 +2,14 @@
//! A container that can be initialized at most once.
-use super::atomic::{
- ordering::{Acquire, Relaxed, Release},
- Atomic,
-};
use core::{cell::UnsafeCell, mem::MaybeUninit};
+use kernel::{
+ error::Result,
+ sync::atomic::{
+ ordering::{Acquire, Relaxed, Release},
+ Atomic,
+ },
+};
/// A container that can be populated at most once. Thread safe.
///
@@ -76,10 +79,46 @@ pub fn as_ref(&self) -> Option<&T> {
}
}
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with the value returned by `callable` and return a reference to that
+ /// object.
+ pub fn as_ref_or_populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<&T> {
+ if !self.populate_with(callable)? {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ Ok(unsafe { &*self.value.get().cast() })
+ }
+
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with `value` and return a reference to that object.
+ pub fn as_ref_or_populate(&self, value: T) -> &T {
+ if !self.populate(value) {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ unsafe { &*self.value.get().cast() }
+ }
+
/// Populate the [`SetOnce`].
///
/// Returns `true` if the [`SetOnce`] was successfully populated.
pub fn populate(&self, value: T) -> bool {
+ self.populate_with(|| Ok(value)).expect("Cannot error")
+ }
+
+ /// Populate the [`SetOnce`] with the value returned by `callable`.
+ ///
+ /// Returns `true` if the [`SetOnce`] was successfully populated.
+ pub fn populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<bool> {
// INVARIANT: If the swap succeeds:
// - We increase `init`.
// - We write the valid value `1` to `init`.
@@ -88,16 +127,16 @@ pub fn populate(&self, value: T) -> bool {
if let Ok(0) = self.init.cmpxchg(0, 1, Relaxed) {
// SAFETY: By the type invariants of `Self`, the fact that we succeeded in writing `1`
// to `self.init` means we obtained exclusive access to `self.value`.
- unsafe { core::ptr::write(self.value.get().cast(), value) };
+ unsafe { core::ptr::write(self.value.get().cast(), callable()?) };
// INVARIANT:
// - We increase `init`.
// - We write the valid value `2` to `init`.
// - We release our exclusive access to `self.value` and it is now valid for shared
// access.
self.init.store(2, Release);
- true
+ Ok(true)
} else {
- false
+ Ok(false)
}
}
---
base-commit: 05f7e89ab9731565d8a62e3b5d1ec206485eeb0b
change-id: 20260215-set-once-lazy-c73fc34a55d9
Best regards,
--
Andreas Hindborg <a.hindborg@kernel.org>
| null | null | null | [PATCH] rust: sync: add lazy initialization methods to SetOnce | On Mon, Feb 16, 2026 at 12:10:16PM +0100, Andreas Hindborg wrote:
You can add a spinlock to SetOnce. Like I mentioned previously [1],
support for waiting will require the addition of extra fields.
I suppose we might be able to use include/linux/bit_spinlock.h here to
avoid taking up any additional space.
Alice
[1]: https://lore.kernel.org/all/CAH5fLggY2Ei14nVJzLBEoR1Rut1GKU4SZX=+14tuRH1aSuQVTA@mail.gmail.com/ | {
"author": "Alice Ryhl <aliceryhl@google.com>",
"date": "Mon, 16 Feb 2026 11:26:11 +0000",
"is_openbsd": false,
"thread_id": "DGPTYBO26YBT.3S14I9F5YT1PW@garyguo.net.mbox.gz"
} |
lkml_critique | lkml | Add methods to get a reference to the contained value or populate the
SetOnce if empty. The new `as_ref_or_populate` method accepts a value
directly, while `as_ref_or_populate_with` accepts a fallible closure,
allowing for lazy initialization that may fail. Both methods spin-wait
if another thread is concurrently initializing the container.
Also add `populate_with` which takes a fallible closure and serves as
the implementation basis for the other populate methods.
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
rust/kernel/sync/set_once.rs | 53 ++++++++++++++++++++++++++++++++++++++------
1 file changed, 46 insertions(+), 7 deletions(-)
diff --git a/rust/kernel/sync/set_once.rs b/rust/kernel/sync/set_once.rs
index bdba601807d8b..9e3c4be4047f8 100644
--- a/rust/kernel/sync/set_once.rs
+++ b/rust/kernel/sync/set_once.rs
@@ -2,11 +2,14 @@
//! A container that can be initialized at most once.
-use super::atomic::{
- ordering::{Acquire, Relaxed, Release},
- Atomic,
-};
use core::{cell::UnsafeCell, mem::MaybeUninit};
+use kernel::{
+ error::Result,
+ sync::atomic::{
+ ordering::{Acquire, Relaxed, Release},
+ Atomic,
+ },
+};
/// A container that can be populated at most once. Thread safe.
///
@@ -76,10 +79,46 @@ pub fn as_ref(&self) -> Option<&T> {
}
}
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with the value returned by `callable` and return a reference to that
+ /// object.
+ pub fn as_ref_or_populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<&T> {
+ if !self.populate_with(callable)? {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ Ok(unsafe { &*self.value.get().cast() })
+ }
+
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with `value` and return a reference to that object.
+ pub fn as_ref_or_populate(&self, value: T) -> &T {
+ if !self.populate(value) {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ unsafe { &*self.value.get().cast() }
+ }
+
/// Populate the [`SetOnce`].
///
/// Returns `true` if the [`SetOnce`] was successfully populated.
pub fn populate(&self, value: T) -> bool {
+ self.populate_with(|| Ok(value)).expect("Cannot error")
+ }
+
+ /// Populate the [`SetOnce`] with the value returned by `callable`.
+ ///
+ /// Returns `true` if the [`SetOnce`] was successfully populated.
+ pub fn populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<bool> {
// INVARIANT: If the swap succeeds:
// - We increase `init`.
// - We write the valid value `1` to `init`.
@@ -88,16 +127,16 @@ pub fn populate(&self, value: T) -> bool {
if let Ok(0) = self.init.cmpxchg(0, 1, Relaxed) {
// SAFETY: By the type invariants of `Self`, the fact that we succeeded in writing `1`
// to `self.init` means we obtained exclusive access to `self.value`.
- unsafe { core::ptr::write(self.value.get().cast(), value) };
+ unsafe { core::ptr::write(self.value.get().cast(), callable()?) };
// INVARIANT:
// - We increase `init`.
// - We write the valid value `2` to `init`.
// - We release our exclusive access to `self.value` and it is now valid for shared
// access.
self.init.store(2, Release);
- true
+ Ok(true)
} else {
- false
+ Ok(false)
}
}
---
base-commit: 05f7e89ab9731565d8a62e3b5d1ec206485eeb0b
change-id: 20260215-set-once-lazy-c73fc34a55d9
Best regards,
--
Andreas Hindborg <a.hindborg@kernel.org>
| null | null | null | [PATCH] rust: sync: add lazy initialization methods to SetOnce | On Mon, Feb 16, 2026 at 11:26:11AM +0000, Alice Ryhl wrote:
By the way, back then I suggested renaming it from OnceLock to SetOnce
because you did not support waiting for the value to be populated, and
you said you didn't need that. If you add that feature, then we should
rename it back to OnceLock, or create a new type OnceLock for users who
need that additional feature.
Alice | {
"author": "Alice Ryhl <aliceryhl@google.com>",
"date": "Mon, 16 Feb 2026 11:35:27 +0000",
"is_openbsd": false,
"thread_id": "DGPTYBO26YBT.3S14I9F5YT1PW@garyguo.net.mbox.gz"
} |
lkml_critique | lkml | Add methods to get a reference to the contained value or populate the
SetOnce if empty. The new `as_ref_or_populate` method accepts a value
directly, while `as_ref_or_populate_with` accepts a fallible closure,
allowing for lazy initialization that may fail. Both methods spin-wait
if another thread is concurrently initializing the container.
Also add `populate_with` which takes a fallible closure and serves as
the implementation basis for the other populate methods.
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
rust/kernel/sync/set_once.rs | 53 ++++++++++++++++++++++++++++++++++++++------
1 file changed, 46 insertions(+), 7 deletions(-)
diff --git a/rust/kernel/sync/set_once.rs b/rust/kernel/sync/set_once.rs
index bdba601807d8b..9e3c4be4047f8 100644
--- a/rust/kernel/sync/set_once.rs
+++ b/rust/kernel/sync/set_once.rs
@@ -2,11 +2,14 @@
//! A container that can be initialized at most once.
-use super::atomic::{
- ordering::{Acquire, Relaxed, Release},
- Atomic,
-};
use core::{cell::UnsafeCell, mem::MaybeUninit};
+use kernel::{
+ error::Result,
+ sync::atomic::{
+ ordering::{Acquire, Relaxed, Release},
+ Atomic,
+ },
+};
/// A container that can be populated at most once. Thread safe.
///
@@ -76,10 +79,46 @@ pub fn as_ref(&self) -> Option<&T> {
}
}
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with the value returned by `callable` and return a reference to that
+ /// object.
+ pub fn as_ref_or_populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<&T> {
+ if !self.populate_with(callable)? {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ Ok(unsafe { &*self.value.get().cast() })
+ }
+
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with `value` and return a reference to that object.
+ pub fn as_ref_or_populate(&self, value: T) -> &T {
+ if !self.populate(value) {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ unsafe { &*self.value.get().cast() }
+ }
+
/// Populate the [`SetOnce`].
///
/// Returns `true` if the [`SetOnce`] was successfully populated.
pub fn populate(&self, value: T) -> bool {
+ self.populate_with(|| Ok(value)).expect("Cannot error")
+ }
+
+ /// Populate the [`SetOnce`] with the value returned by `callable`.
+ ///
+ /// Returns `true` if the [`SetOnce`] was successfully populated.
+ pub fn populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<bool> {
// INVARIANT: If the swap succeeds:
// - We increase `init`.
// - We write the valid value `1` to `init`.
@@ -88,16 +127,16 @@ pub fn populate(&self, value: T) -> bool {
if let Ok(0) = self.init.cmpxchg(0, 1, Relaxed) {
// SAFETY: By the type invariants of `Self`, the fact that we succeeded in writing `1`
// to `self.init` means we obtained exclusive access to `self.value`.
- unsafe { core::ptr::write(self.value.get().cast(), value) };
+ unsafe { core::ptr::write(self.value.get().cast(), callable()?) };
// INVARIANT:
// - We increase `init`.
// - We write the valid value `2` to `init`.
// - We release our exclusive access to `self.value` and it is now valid for shared
// access.
self.init.store(2, Release);
- true
+ Ok(true)
} else {
- false
+ Ok(false)
}
}
---
base-commit: 05f7e89ab9731565d8a62e3b5d1ec206485eeb0b
change-id: 20260215-set-once-lazy-c73fc34a55d9
Best regards,
--
Andreas Hindborg <a.hindborg@kernel.org>
| null | null | null | [PATCH] rust: sync: add lazy initialization methods to SetOnce | "Alice Ryhl" <aliceryhl@google.com> writes:
Thanks, I'll be sure to take a look again.
That is fair. This is a different use case than the original one though.
I think we should keep this as one type for code reuse, but I am fine
with renaming to something that describe the usage better.
Best regards,
Andreas Hindborg | {
"author": "Andreas Hindborg <a.hindborg@kernel.org>",
"date": "Mon, 16 Feb 2026 14:32:42 +0100",
"is_openbsd": false,
"thread_id": "DGPTYBO26YBT.3S14I9F5YT1PW@garyguo.net.mbox.gz"
} |
lkml_critique | lkml | Add methods to get a reference to the contained value or populate the
SetOnce if empty. The new `as_ref_or_populate` method accepts a value
directly, while `as_ref_or_populate_with` accepts a fallible closure,
allowing for lazy initialization that may fail. Both methods spin-wait
if another thread is concurrently initializing the container.
Also add `populate_with` which takes a fallible closure and serves as
the implementation basis for the other populate methods.
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
rust/kernel/sync/set_once.rs | 53 ++++++++++++++++++++++++++++++++++++++------
1 file changed, 46 insertions(+), 7 deletions(-)
diff --git a/rust/kernel/sync/set_once.rs b/rust/kernel/sync/set_once.rs
index bdba601807d8b..9e3c4be4047f8 100644
--- a/rust/kernel/sync/set_once.rs
+++ b/rust/kernel/sync/set_once.rs
@@ -2,11 +2,14 @@
//! A container that can be initialized at most once.
-use super::atomic::{
- ordering::{Acquire, Relaxed, Release},
- Atomic,
-};
use core::{cell::UnsafeCell, mem::MaybeUninit};
+use kernel::{
+ error::Result,
+ sync::atomic::{
+ ordering::{Acquire, Relaxed, Release},
+ Atomic,
+ },
+};
/// A container that can be populated at most once. Thread safe.
///
@@ -76,10 +79,46 @@ pub fn as_ref(&self) -> Option<&T> {
}
}
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with the value returned by `callable` and return a reference to that
+ /// object.
+ pub fn as_ref_or_populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<&T> {
+ if !self.populate_with(callable)? {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ Ok(unsafe { &*self.value.get().cast() })
+ }
+
+ /// Get a reference to the contained object, or populate the [`SetOnce`]
+ /// with `value` and return a reference to that object.
+ pub fn as_ref_or_populate(&self, value: T) -> &T {
+ if !self.populate(value) {
+ while self.init.load(Acquire) != 2 {
+ core::hint::spin_loop();
+ }
+ }
+
+ // SAFETY: By the type invariants of `Self`, `self.init == 2` means that `self.value`
+ // is initialized and valid for shared access.
+ unsafe { &*self.value.get().cast() }
+ }
+
/// Populate the [`SetOnce`].
///
/// Returns `true` if the [`SetOnce`] was successfully populated.
pub fn populate(&self, value: T) -> bool {
+ self.populate_with(|| Ok(value)).expect("Cannot error")
+ }
+
+ /// Populate the [`SetOnce`] with the value returned by `callable`.
+ ///
+ /// Returns `true` if the [`SetOnce`] was successfully populated.
+ pub fn populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<bool> {
// INVARIANT: If the swap succeeds:
// - We increase `init`.
// - We write the valid value `1` to `init`.
@@ -88,16 +127,16 @@ pub fn populate(&self, value: T) -> bool {
if let Ok(0) = self.init.cmpxchg(0, 1, Relaxed) {
// SAFETY: By the type invariants of `Self`, the fact that we succeeded in writing `1`
// to `self.init` means we obtained exclusive access to `self.value`.
- unsafe { core::ptr::write(self.value.get().cast(), value) };
+ unsafe { core::ptr::write(self.value.get().cast(), callable()?) };
// INVARIANT:
// - We increase `init`.
// - We write the valid value `2` to `init`.
// - We release our exclusive access to `self.value` and it is now valid for shared
// access.
self.init.store(2, Release);
- true
+ Ok(true)
} else {
- false
+ Ok(false)
}
}
---
base-commit: 05f7e89ab9731565d8a62e3b5d1ec206485eeb0b
change-id: 20260215-set-once-lazy-c73fc34a55d9
Best regards,
--
Andreas Hindborg <a.hindborg@kernel.org>
| null | null | null | [PATCH] rust: sync: add lazy initialization methods to SetOnce | On Sun Feb 15, 2026 at 8:27 PM GMT, Andreas Hindborg wrote:
Hi Andreas, in an earlier call I mentioned that I'm working on getting SetOnce
to work with pin-init, the capability of which I think is a superset of you have
here.
The API I have is
impl<T> SetOnce<T> {
pub fn init<E>(&self, init: impl Init<T, E>) -> Result<&T, InitError<E>>;
pub fn pin_init<E>(self, Pin<&Self>, init: impl PinInit<T, E>) -> Result<&T, InitError<E>>;
}
To achieve what you need with a function, you can simply write:
set_once.init(pin_init::init_scope(your_fn))
The patch that implement the API is here:
https://github.com/nbdd0121/linux/commit/4aabdbcf20b11626c253f203745b1d55c37ab2ee
in tree
https://github.com/nbdd0121/linux/tree/lazy_revocable_nova_wip/
which I haven't submitted to the list as the user side of this API isn't ready.
Best,
Gary | {
"author": "\"Gary Guo\" <gary@garyguo.net>",
"date": "Fri, 27 Feb 2026 14:56:25 +0000",
"is_openbsd": false,
"thread_id": "DGPTYBO26YBT.3S14I9F5YT1PW@garyguo.net.mbox.gz"
} |
lkml_critique | lkml | The ADE9000_ST_ERROR macro references ADE9000_ST1_ERROR0 through
ADE9000_ST1_ERROR3, but the actual defined symbols use the _BIT
suffix. Fix the references to use the correct macro names.
Signed-off-by: Giorgi Tchankvetadze <giorgitchankvetadze1997@gmail.com>
---
drivers/iio/adc/ade9000.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/drivers/iio/adc/ade9000.c b/drivers/iio/adc/ade9000.c
index 5dcc26a08970..0dbfc079e115 100644
--- a/drivers/iio/adc/ade9000.c
+++ b/drivers/iio/adc/ade9000.c
@@ -219,8 +219,8 @@
#define ADE9000_ST1_ERROR2_BIT BIT(30)
#define ADE9000_ST1_ERROR3_BIT BIT(31)
#define ADE9000_ST_ERROR \
- (ADE9000_ST1_ERROR0 | ADE9000_ST1_ERROR1 | \
- ADE9000_ST1_ERROR2 | ADE9000_ST1_ERROR3)
+ (ADE9000_ST1_ERROR0_BIT | ADE9000_ST1_ERROR1_BIT | \
+ ADE9000_ST1_ERROR2_BIT | ADE9000_ST1_ERROR3_BIT)
#define ADE9000_ST1_CROSSING_FIRST 6
#define ADE9000_ST1_CROSSING_DEPTH 25
--
2.52.0
| null | null | null | [PATCH] iio: adc: ade9000: fix wrong macro names in ADE9000_ST_ERROR | On Fri, Feb 27, 2026 at 02:09:01PM +0400, Giorgi Tchankvetadze wrote:
BIT
(It's okay to drop "_" as "suffix" implies the position of the "BIT".)
What about the current code that uses it? Is it even in use currently?
Please, elaborate more in the commit message that we clearly understand
that you spent time and investigated code and/or datasheet before crafting
this change.
--
With Best Regards,
Andy Shevchenko | {
"author": "Andy Shevchenko <andriy.shevchenko@intel.com>",
"date": "Fri, 27 Feb 2026 12:33:00 +0200",
"is_openbsd": false,
"thread_id": "aaGt38ePGhonQRmd@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | The ADE9000_ST_ERROR macro references ADE9000_ST1_ERROR0 through
ADE9000_ST1_ERROR3, but the actual defined symbols use the _BIT
suffix. Fix the references to use the correct macro names.
Signed-off-by: Giorgi Tchankvetadze <giorgitchankvetadze1997@gmail.com>
---
drivers/iio/adc/ade9000.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/drivers/iio/adc/ade9000.c b/drivers/iio/adc/ade9000.c
index 5dcc26a08970..0dbfc079e115 100644
--- a/drivers/iio/adc/ade9000.c
+++ b/drivers/iio/adc/ade9000.c
@@ -219,8 +219,8 @@
#define ADE9000_ST1_ERROR2_BIT BIT(30)
#define ADE9000_ST1_ERROR3_BIT BIT(31)
#define ADE9000_ST_ERROR \
- (ADE9000_ST1_ERROR0 | ADE9000_ST1_ERROR1 | \
- ADE9000_ST1_ERROR2 | ADE9000_ST1_ERROR3)
+ (ADE9000_ST1_ERROR0_BIT | ADE9000_ST1_ERROR1_BIT | \
+ ADE9000_ST1_ERROR2_BIT | ADE9000_ST1_ERROR3_BIT)
#define ADE9000_ST1_CROSSING_FIRST 6
#define ADE9000_ST1_CROSSING_DEPTH 25
--
2.52.0
| null | null | null | [PATCH] iio: adc: ade9000: fix wrong macro names in ADE9000_ST_ERROR | On Fri, Feb 27, 2026 at 2:33 PM Andy Shevchenko
<andriy.shevchenko@intel.com> wrote:
Hi Andy. Thanks for the feedback !
The macro is currently unused in the driver, so this does not cause
a build failure.
Reference: ADE9000 datasheet (Rev. B, Page 61), STATUS1 register (0x403),
bits 28-31 define ERROR0 through ERROR3 status flags. | {
"author": "Giorgi Tchankvetadze <giorgitchankvetadze1997@gmail.com>",
"date": "Fri, 27 Feb 2026 14:52:45 +0400",
"is_openbsd": false,
"thread_id": "aaGt38ePGhonQRmd@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | The ADE9000_ST_ERROR macro references ADE9000_ST1_ERROR0 through
ADE9000_ST1_ERROR3, but the actual defined symbols use the _BIT
suffix. Fix the references to use the correct macro names.
Signed-off-by: Giorgi Tchankvetadze <giorgitchankvetadze1997@gmail.com>
---
drivers/iio/adc/ade9000.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/drivers/iio/adc/ade9000.c b/drivers/iio/adc/ade9000.c
index 5dcc26a08970..0dbfc079e115 100644
--- a/drivers/iio/adc/ade9000.c
+++ b/drivers/iio/adc/ade9000.c
@@ -219,8 +219,8 @@
#define ADE9000_ST1_ERROR2_BIT BIT(30)
#define ADE9000_ST1_ERROR3_BIT BIT(31)
#define ADE9000_ST_ERROR \
- (ADE9000_ST1_ERROR0 | ADE9000_ST1_ERROR1 | \
- ADE9000_ST1_ERROR2 | ADE9000_ST1_ERROR3)
+ (ADE9000_ST1_ERROR0_BIT | ADE9000_ST1_ERROR1_BIT | \
+ ADE9000_ST1_ERROR2_BIT | ADE9000_ST1_ERROR3_BIT)
#define ADE9000_ST1_CROSSING_FIRST 6
#define ADE9000_ST1_CROSSING_DEPTH 25
--
2.52.0
| null | null | null | [PATCH] iio: adc: ade9000: fix wrong macro names in ADE9000_ST_ERROR | On Fri, Feb 27, 2026 at 02:52:45PM +0400, Giorgi Tchankvetadze wrote:
Drop it then?
Yes, good, this should be in the commit message.
--
With Best Regards,
Andy Shevchenko | {
"author": "Andy Shevchenko <andriy.shevchenko@intel.com>",
"date": "Fri, 27 Feb 2026 16:44:47 +0200",
"is_openbsd": false,
"thread_id": "aaGt38ePGhonQRmd@ashevche-desk.local.mbox.gz"
} |
lkml_critique | lkml | This series introduces the hierarchical tree counter (hpcc) to increase
accuracy of approximated RSS counters exposed through proc interfaces.
With a test program hopping across CPUs doing frequent mmap/munmap
operations, the upstream implementation approximation reaches a 1GB
delta from the precise value after a few minutes, compared to a 80MB
delta with the hierarchical counter. The hierarchical counter provides a
guaranteed maximum approximation inaccuracy of 192MB on that hardware
topology.
This series is based on tag v7.0-rc1.
The main changes since v17:
- Fix patch series bissectability.
- Export GPL symbols for kunit tests.
- Improve kunit tests coverage.
- Fix kunit tests wait queue head reinit bug.
- Fix an out-of-bound on bootup on configurations where nr_cpu_ids is
close to NR_CPUS.
Andrew, this series targets 7.1.
Thanks!
Mathieu
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: "Paul E. McKenney" <paulmck@kernel.org>
Cc: Steven Rostedt <rostedt@goodmis.org>
Cc: Masami Hiramatsu <mhiramat@kernel.org>
Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Dennis Zhou <dennis@kernel.org>
Cc: Tejun Heo <tj@kernel.org>
Cc: Christoph Lameter <cl@linux.com>
Cc: Martin Liu <liumartin@google.com>
Cc: David Rientjes <rientjes@google.com>
Cc: christian.koenig@amd.com
Cc: Shakeel Butt <shakeel.butt@linux.dev>
Cc: SeongJae Park <sj@kernel.org>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Johannes Weiner <hannes@cmpxchg.org>
Cc: Sweet Tea Dorminy <sweettea-kernel@dorminy.me>
Cc: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Cc: "Liam R . Howlett" <liam.howlett@oracle.com>
Cc: Mike Rapoport <rppt@kernel.org>
Cc: Suren Baghdasaryan <surenb@google.com>
Cc: Vlastimil Babka <vbabka@suse.cz>
Cc: Christian Brauner <brauner@kernel.org>
Cc: Wei Yang <richard.weiyang@gmail.com>
Cc: David Hildenbrand <david@redhat.com>
Cc: Miaohe Lin <linmiaohe@huawei.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: linux-mm@kvack.org
Cc: linux-trace-kernel@vger.kernel.org
Cc: Yu Zhao <yuzhao@google.com>
Cc: Roman Gushchin <roman.gushchin@linux.dev>
Cc: Mateusz Guzik <mjguzik@gmail.com>
Cc: Matthew Wilcox <willy@infradead.org>
Cc: Baolin Wang <baolin.wang@linux.alibaba.com>
Cc: Aboorva Devarajan <aboorvad@linux.ibm.com>
Mathieu Desnoyers (3):
lib: Introduce hierarchical per-cpu counters
lib: Test hierarchical per-cpu counters
mm: Improve RSS counter approximation accuracy for proc interfaces
.../core-api/percpu-counter-tree.rst | 75 ++
include/linux/mm.h | 19 +-
include/linux/mm_types.h | 54 +-
include/linux/percpu_counter_tree.h | 367 +++++++++
include/trace/events/kmem.h | 2 +-
init/main.c | 2 +
kernel/fork.c | 22 +-
lib/Kconfig | 12 +
lib/Makefile | 1 +
lib/percpu_counter_tree.c | 702 ++++++++++++++++++
lib/tests/Makefile | 2 +
lib/tests/percpu_counter_tree_kunit.c | 399 ++++++++++
12 files changed, 1627 insertions(+), 30 deletions(-)
create mode 100644 Documentation/core-api/percpu-counter-tree.rst
create mode 100644 include/linux/percpu_counter_tree.h
create mode 100644 lib/percpu_counter_tree.c
create mode 100644 lib/tests/percpu_counter_tree_kunit.c
--
2.39.5
| null | null | null | [PATCH v18 0/3] Improve proc RSS accuracy | Introduce Kunit tests for hierarchical per-cpu counters.
Keep track of two sets of hierarchical counters, each meant to
have the same precise sum at any time, but distributed differently
across the topology.
Keep track of an atomic counter along with each hierarchical
counter, for sum validation.
Those tests cover:
- Single-threaded (no concurrency) updates.
- Concurrent updates of counters from various CPUs.
Perform the following validations:
- Compare the precise sum of counters with the sum tracked by
an atomic counter.
- Compare the precise sum of two sets of hierarchical counters.
- Approximated comparison of hierarchical counter with atomic counter.
- Approximated comparison of two sets of hierarchical counters.
- Validate the bounds of approximation ranges.
Run with the following .kunit/.kunitconfig:
CONFIG_KUNIT=y
CONFIG_SMP=y
CONFIG_PREEMPT=y
CONFIG_NR_CPUS=32
CONFIG_HOTPLUG_CPU=y
CONFIG_PERCPU_COUNTER_TREE_TEST=y
With the following execution (to use SMP):
./tools/testing/kunit/kunit.py run --arch=x86_64 --qemu_args="-smp 12"
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: "Paul E. McKenney" <paulmck@kernel.org>
Cc: Steven Rostedt <rostedt@goodmis.org>
Cc: Masami Hiramatsu <mhiramat@kernel.org>
Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Dennis Zhou <dennis@kernel.org>
Cc: Tejun Heo <tj@kernel.org>
Cc: Christoph Lameter <cl@linux.com>
Cc: Martin Liu <liumartin@google.com>
Cc: David Rientjes <rientjes@google.com>
Cc: christian.koenig@amd.com
Cc: Shakeel Butt <shakeel.butt@linux.dev>
Cc: SeongJae Park <sj@kernel.org>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Johannes Weiner <hannes@cmpxchg.org>
Cc: Sweet Tea Dorminy <sweettea-kernel@dorminy.me>
Cc: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Cc: "Liam R . Howlett" <liam.howlett@oracle.com>
Cc: Mike Rapoport <rppt@kernel.org>
Cc: Suren Baghdasaryan <surenb@google.com>
Cc: Vlastimil Babka <vbabka@suse.cz>
Cc: Christian Brauner <brauner@kernel.org>
Cc: Wei Yang <richard.weiyang@gmail.com>
Cc: David Hildenbrand <david@redhat.com>
Cc: Miaohe Lin <linmiaohe@huawei.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: linux-mm@kvack.org
Cc: linux-trace-kernel@vger.kernel.org
Cc: Yu Zhao <yuzhao@google.com>
Cc: Roman Gushchin <roman.gushchin@linux.dev>
Cc: Mateusz Guzik <mjguzik@gmail.com>
Cc: Matthew Wilcox <willy@infradead.org>
Cc: Baolin Wang <baolin.wang@linux.alibaba.com>
Cc: Aboorva Devarajan <aboorvad@linux.ibm.com>
---
Changes since v17:
- Use percpu_counter_tree_{init,destroy}_many,
- Add coverage for percpu_counter_tree_{init,destroy},
- Add coverage for percpu_counter_tree_set.
- Fix wait queue head reinit bug. Use DECLARE_WAIT_QUEUE_HEAD
instead.
---
lib/Kconfig | 12 +
lib/tests/Makefile | 2 +
lib/tests/percpu_counter_tree_kunit.c | 399 ++++++++++++++++++++++++++
3 files changed, 413 insertions(+)
create mode 100644 lib/tests/percpu_counter_tree_kunit.c
diff --git a/lib/Kconfig b/lib/Kconfig
index 0f2fb9610647..0b8241e5b548 100644
--- a/lib/Kconfig
+++ b/lib/Kconfig
@@ -52,6 +52,18 @@ config PACKING_KUNIT_TEST
When in doubt, say N.
+config PERCPU_COUNTER_TREE_TEST
+ tristate "Hierarchical Per-CPU counter test" if !KUNIT_ALL_TESTS
+ depends on KUNIT
+ default KUNIT_ALL_TESTS
+ help
+ This builds Kunit tests for the hierarchical per-cpu counters.
+
+ For more information on KUnit and unit tests in general,
+ please refer to the KUnit documentation in Documentation/dev-tools/kunit/.
+
+ When in doubt, say N.
+
config BITREVERSE
tristate
diff --git a/lib/tests/Makefile b/lib/tests/Makefile
index 05f74edbc62b..d282aa23d273 100644
--- a/lib/tests/Makefile
+++ b/lib/tests/Makefile
@@ -56,4 +56,6 @@ obj-$(CONFIG_UTIL_MACROS_KUNIT) += util_macros_kunit.o
obj-$(CONFIG_RATELIMIT_KUNIT_TEST) += test_ratelimit.o
obj-$(CONFIG_UUID_KUNIT_TEST) += uuid_kunit.o
+obj-$(CONFIG_PERCPU_COUNTER_TREE_TEST) += percpu_counter_tree_kunit.o
+
obj-$(CONFIG_TEST_RUNTIME_MODULE) += module/
diff --git a/lib/tests/percpu_counter_tree_kunit.c b/lib/tests/percpu_counter_tree_kunit.c
new file mode 100644
index 000000000000..a79176655c4b
--- /dev/null
+++ b/lib/tests/percpu_counter_tree_kunit.c
@@ -0,0 +1,399 @@
+// SPDX-License-Identifier: GPL-2.0+ OR MIT
+// SPDX-FileCopyrightText: 2026 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+
+#include <kunit/test.h>
+#include <linux/percpu_counter_tree.h>
+#include <linux/kthread.h>
+#include <linux/wait.h>
+#include <linux/random.h>
+
+struct multi_thread_test_data {
+ long increment;
+ int nr_inc;
+ int counter_index;
+};
+
+#define NR_COUNTERS 2
+
+/* Hierarchical per-CPU counter instances. */
+static struct percpu_counter_tree counter[NR_COUNTERS];
+static struct percpu_counter_tree_level_item *items;
+
+/* Global atomic counters for validation. */
+static atomic_long_t global_counter[NR_COUNTERS];
+
+static DECLARE_WAIT_QUEUE_HEAD(kernel_threads_wq);
+static atomic_t kernel_threads_to_run;
+
+static void complete_work(void)
+{
+ if (atomic_dec_and_test(&kernel_threads_to_run))
+ wake_up(&kernel_threads_wq);
+}
+
+static void hpcc_print_info(struct kunit *test)
+{
+ kunit_info(test, "Running test with %d CPUs\n", num_online_cpus());
+}
+
+static void add_to_counter(int counter_index, unsigned int nr_inc, long increment)
+{
+ unsigned int i;
+
+ for (i = 0; i < nr_inc; i++) {
+ percpu_counter_tree_add(&counter[counter_index], increment);
+ atomic_long_add(increment, &global_counter[counter_index]);
+ }
+}
+
+static void check_counters(struct kunit *test)
+{
+ int counter_index;
+
+ /* Compare each counter with its global counter. */
+ for (counter_index = 0; counter_index < NR_COUNTERS; counter_index++) {
+ long v = atomic_long_read(&global_counter[counter_index]);
+ long approx_sum = percpu_counter_tree_approximate_sum(&counter[counter_index]);
+ unsigned long under_accuracy = 0, over_accuracy = 0;
+ long precise_min, precise_max;
+
+ /* Precise comparison. */
+ KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&counter[counter_index]), v);
+ KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_precise_compare_value(&counter[counter_index], v));
+
+ /* Approximate comparison. */
+ KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(&counter[counter_index], v));
+
+ /* Accuracy limits checks. */
+ percpu_counter_tree_approximate_accuracy_range(&counter[counter_index], &under_accuracy, &over_accuracy);
+
+ KUNIT_EXPECT_GE(test, (long)(approx_sum - (v - under_accuracy)), 0);
+ KUNIT_EXPECT_LE(test, (long)(approx_sum - (v + over_accuracy)), 0);
+ KUNIT_EXPECT_GT(test, (long)(approx_sum - (v - under_accuracy - 1)), 0);
+ KUNIT_EXPECT_LT(test, (long)(approx_sum - (v + over_accuracy + 1)), 0);
+
+ /* Precise min/max range check. */
+ percpu_counter_tree_approximate_min_max_range(approx_sum, under_accuracy, over_accuracy, &precise_min, &precise_max);
+
+ KUNIT_EXPECT_GE(test, v - precise_min, 0);
+ KUNIT_EXPECT_LE(test, v - precise_max, 0);
+ KUNIT_EXPECT_GT(test, v - (precise_min - 1), 0);
+ KUNIT_EXPECT_LT(test, v - (precise_max + 1), 0);
+ }
+ /* Compare each counter with the second counter. */
+ KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&counter[0]), percpu_counter_tree_precise_sum(&counter[1]));
+ KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_precise_compare(&counter[0], &counter[1]));
+ KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare(&counter[0], &counter[1]));
+}
+
+static int multi_thread_worker_fn(void *data)
+{
+ struct multi_thread_test_data *td = data;
+
+ add_to_counter(td->counter_index, td->nr_inc, td->increment);
+ complete_work();
+ kfree(td);
+ return 0;
+}
+
+static void test_run_on_specific_cpu(struct kunit *test, int target_cpu, int counter_index, unsigned int nr_inc, long increment)
+{
+ struct task_struct *task;
+ struct multi_thread_test_data *td = kzalloc(sizeof(struct multi_thread_test_data), GFP_KERNEL);
+
+ KUNIT_EXPECT_PTR_NE(test, td, NULL);
+ td->increment = increment;
+ td->nr_inc = nr_inc;
+ td->counter_index = counter_index;
+ atomic_inc(&kernel_threads_to_run);
+ task = kthread_run_on_cpu(multi_thread_worker_fn, td, target_cpu, "kunit_multi_thread_worker");
+ KUNIT_ASSERT_NOT_ERR_OR_NULL(test, task);
+}
+
+static void init_kthreads(void)
+{
+ atomic_set(&kernel_threads_to_run, 1);
+}
+
+static void fini_kthreads(void)
+{
+ /* Release our own reference. */
+ complete_work();
+ /* Wait for all others threads to run. */
+ wait_event(kernel_threads_wq, (atomic_read(&kernel_threads_to_run) == 0));
+}
+
+static void test_sync_kthreads(void)
+{
+ fini_kthreads();
+ init_kthreads();
+}
+
+static void init_counters(struct kunit *test, unsigned long batch_size)
+{
+ int i, ret;
+
+ items = kzalloc(percpu_counter_tree_items_size() * NR_COUNTERS, GFP_KERNEL);
+ KUNIT_EXPECT_PTR_NE(test, items, NULL);
+ ret = percpu_counter_tree_init_many(counter, items, NR_COUNTERS, batch_size, GFP_KERNEL);
+ KUNIT_EXPECT_EQ(test, ret, 0);
+
+ for (i = 0; i < NR_COUNTERS; i++)
+ atomic_long_set(&global_counter[i], 0);
+}
+
+static void fini_counters(void)
+{
+ percpu_counter_tree_destroy_many(counter, NR_COUNTERS);
+ kfree(items);
+}
+
+enum up_test_inc_type {
+ INC_ONE,
+ INC_MINUS_ONE,
+ INC_RANDOM,
+};
+
+/*
+ * Single-threaded tests. Those use many threads to run on various CPUs,
+ * but synchronize for completion of each thread before running the
+ * next, effectively making sure there are no concurrent updates.
+ */
+static void do_hpcc_test_single_thread(struct kunit *test, int _cpu0, int _cpu1, enum up_test_inc_type type)
+{
+ unsigned long batch_size_order = 5;
+ int cpu0 = _cpu0;
+ int cpu1 = _cpu1;
+ int i;
+
+ init_counters(test, 1UL << batch_size_order);
+ init_kthreads();
+ for (i = 0; i < 10000; i++) {
+ long increment;
+
+ switch (type) {
+ case INC_ONE:
+ increment = 1;
+ break;
+ case INC_MINUS_ONE:
+ increment = -1;
+ break;
+ case INC_RANDOM:
+ increment = (long) get_random_long() % 50000;
+ break;
+ }
+ if (_cpu0 < 0)
+ cpu0 = cpumask_any_distribute(cpu_online_mask);
+ if (_cpu1 < 0)
+ cpu1 = cpumask_any_distribute(cpu_online_mask);
+ test_run_on_specific_cpu(test, cpu0, 0, 1, increment);
+ test_sync_kthreads();
+ test_run_on_specific_cpu(test, cpu1, 1, 1, increment);
+ test_sync_kthreads();
+ check_counters(test);
+ }
+ fini_kthreads();
+ fini_counters();
+}
+
+static void hpcc_test_single_thread_first(struct kunit *test)
+{
+ int cpu = cpumask_first(cpu_online_mask);
+
+ do_hpcc_test_single_thread(test, cpu, cpu, INC_ONE);
+ do_hpcc_test_single_thread(test, cpu, cpu, INC_MINUS_ONE);
+ do_hpcc_test_single_thread(test, cpu, cpu, INC_RANDOM);
+}
+
+static void hpcc_test_single_thread_first_random(struct kunit *test)
+{
+ int cpu = cpumask_first(cpu_online_mask);
+
+ do_hpcc_test_single_thread(test, cpu, -1, INC_ONE);
+ do_hpcc_test_single_thread(test, cpu, -1, INC_MINUS_ONE);
+ do_hpcc_test_single_thread(test, cpu, -1, INC_RANDOM);
+}
+
+static void hpcc_test_single_thread_random(struct kunit *test)
+{
+ do_hpcc_test_single_thread(test, -1, -1, INC_ONE);
+ do_hpcc_test_single_thread(test, -1, -1, INC_MINUS_ONE);
+ do_hpcc_test_single_thread(test, -1, -1, INC_RANDOM);
+}
+
+/* Multi-threaded SMP tests. */
+
+static void do_hpcc_multi_thread_increment_each_cpu(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)
+{
+ int cpu;
+
+ init_counters(test, batch_size);
+ init_kthreads();
+ for_each_online_cpu(cpu) {
+ test_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);
+ test_run_on_specific_cpu(test, cpu, 1, nr_inc, increment);
+ }
+ fini_kthreads();
+ check_counters(test);
+ fini_counters();
+}
+
+static void do_hpcc_multi_thread_increment_even_cpus(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)
+{
+ int cpu;
+
+ init_counters(test, batch_size);
+ init_kthreads();
+ for_each_online_cpu(cpu) {
+ test_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);
+ test_run_on_specific_cpu(test, cpu & ~1, 1, nr_inc, increment); /* even cpus. */
+ }
+ fini_kthreads();
+ check_counters(test);
+ fini_counters();
+}
+
+static void do_hpcc_multi_thread_increment_single_cpu(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)
+{
+ int cpu;
+
+ init_counters(test, batch_size);
+ init_kthreads();
+ for_each_online_cpu(cpu) {
+ test_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);
+ test_run_on_specific_cpu(test, cpumask_first(cpu_online_mask), 1, nr_inc, increment);
+ }
+ fini_kthreads();
+ check_counters(test);
+ fini_counters();
+}
+
+static void do_hpcc_multi_thread_increment_random_cpu(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)
+{
+ int cpu;
+
+ init_counters(test, batch_size);
+ init_kthreads();
+ for_each_online_cpu(cpu) {
+ test_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);
+ test_run_on_specific_cpu(test, cpumask_any_distribute(cpu_online_mask), 1, nr_inc, increment);
+ }
+ fini_kthreads();
+ check_counters(test);
+ fini_counters();
+}
+
+static void hpcc_test_multi_thread_batch_increment(struct kunit *test)
+{
+ unsigned long batch_size_order;
+
+ for (batch_size_order = 2; batch_size_order < 10; batch_size_order++) {
+ unsigned int nr_inc;
+
+ for (nr_inc = 1; nr_inc < 1024; nr_inc *= 2) {
+ long increment;
+
+ for (increment = 1; increment < 100000; increment *= 10) {
+ do_hpcc_multi_thread_increment_each_cpu(test, 1UL << batch_size_order, nr_inc, increment);
+ do_hpcc_multi_thread_increment_even_cpus(test, 1UL << batch_size_order, nr_inc, increment);
+ do_hpcc_multi_thread_increment_single_cpu(test, 1UL << batch_size_order, nr_inc, increment);
+ do_hpcc_multi_thread_increment_random_cpu(test, 1UL << batch_size_order, nr_inc, increment);
+ }
+ }
+ }
+}
+
+static void hpcc_test_multi_thread_random_walk(struct kunit *test)
+{
+ unsigned long batch_size_order = 5;
+ int loop;
+
+ for (loop = 0; loop < 100; loop++) {
+ int i;
+
+ init_counters(test, 1UL << batch_size_order);
+ init_kthreads();
+ for (i = 0; i < 1000; i++) {
+ long increment = (long) get_random_long() % 512;
+ unsigned int nr_inc = ((unsigned long) get_random_long()) % 1024;
+
+ test_run_on_specific_cpu(test, cpumask_any_distribute(cpu_online_mask), 0, nr_inc, increment);
+ test_run_on_specific_cpu(test, cpumask_any_distribute(cpu_online_mask), 1, nr_inc, increment);
+ }
+ fini_kthreads();
+ check_counters(test);
+ fini_counters();
+ }
+}
+
+static void hpcc_test_init_one(struct kunit *test)
+{
+ struct percpu_counter_tree pct;
+ struct percpu_counter_tree_level_item *counter_items;
+ int ret;
+
+ counter_items = kzalloc(percpu_counter_tree_items_size(), GFP_KERNEL);
+ KUNIT_EXPECT_PTR_NE(test, counter_items, NULL);
+ ret = percpu_counter_tree_init(&pct, counter_items, 32, GFP_KERNEL);
+ KUNIT_EXPECT_EQ(test, ret, 0);
+
+ percpu_counter_tree_destroy(&pct);
+ kfree(counter_items);
+}
+
+static void hpcc_test_set(struct kunit *test)
+{
+ static long values[] = {
+ 5, 100, 127, 128, 255, 256, 4095, 4096, 500000, 0,
+ -5, -100, -127, -128, -255, -256, -4095, -4096, -500000,
+ };
+ struct percpu_counter_tree pct;
+ struct percpu_counter_tree_level_item *counter_items;
+ int i, ret;
+
+ counter_items = kzalloc(percpu_counter_tree_items_size(), GFP_KERNEL);
+ KUNIT_EXPECT_PTR_NE(test, counter_items, NULL);
+ ret = percpu_counter_tree_init(&pct, counter_items, 32, GFP_KERNEL);
+ KUNIT_EXPECT_EQ(test, ret, 0);
+
+ for (i = 0; i < ARRAY_SIZE(values); i++) {
+ long v = values[i];
+
+ percpu_counter_tree_set(&pct, v);
+ KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&pct), v);
+ KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(&pct, v));
+
+ percpu_counter_tree_add(&pct, v);
+ KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&pct), 2 * v);
+ KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(&pct, 2 * v));
+
+ percpu_counter_tree_add(&pct, -2 * v);
+ KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&pct), 0);
+ KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(&pct, 0));
+ }
+
+ percpu_counter_tree_destroy(&pct);
+ kfree(counter_items);
+}
+
+static struct kunit_case hpcc_test_cases[] = {
+ KUNIT_CASE(hpcc_print_info),
+ KUNIT_CASE(hpcc_test_single_thread_first),
+ KUNIT_CASE(hpcc_test_single_thread_first_random),
+ KUNIT_CASE(hpcc_test_single_thread_random),
+ KUNIT_CASE(hpcc_test_multi_thread_batch_increment),
+ KUNIT_CASE(hpcc_test_multi_thread_random_walk),
+ KUNIT_CASE(hpcc_test_init_one),
+ KUNIT_CASE(hpcc_test_set),
+ {}
+};
+
+static struct kunit_suite hpcc_test_suite = {
+ .name = "percpu_counter_tree",
+ .test_cases = hpcc_test_cases,
+};
+
+kunit_test_suite(hpcc_test_suite);
+
+MODULE_DESCRIPTION("Test cases for hierarchical per-CPU counters");
+MODULE_LICENSE("Dual MIT/GPL");
--
2.39.5 | {
"author": "Mathieu Desnoyers <mathieu.desnoyers@efficios.com>",
"date": "Fri, 27 Feb 2026 10:37:29 -0500",
"is_openbsd": false,
"thread_id": "20260227153730.1556542-4-mathieu.desnoyers@efficios.com.mbox.gz"
} |
lkml_critique | lkml | This series introduces the hierarchical tree counter (hpcc) to increase
accuracy of approximated RSS counters exposed through proc interfaces.
With a test program hopping across CPUs doing frequent mmap/munmap
operations, the upstream implementation approximation reaches a 1GB
delta from the precise value after a few minutes, compared to a 80MB
delta with the hierarchical counter. The hierarchical counter provides a
guaranteed maximum approximation inaccuracy of 192MB on that hardware
topology.
This series is based on tag v7.0-rc1.
The main changes since v17:
- Fix patch series bissectability.
- Export GPL symbols for kunit tests.
- Improve kunit tests coverage.
- Fix kunit tests wait queue head reinit bug.
- Fix an out-of-bound on bootup on configurations where nr_cpu_ids is
close to NR_CPUS.
Andrew, this series targets 7.1.
Thanks!
Mathieu
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: "Paul E. McKenney" <paulmck@kernel.org>
Cc: Steven Rostedt <rostedt@goodmis.org>
Cc: Masami Hiramatsu <mhiramat@kernel.org>
Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Dennis Zhou <dennis@kernel.org>
Cc: Tejun Heo <tj@kernel.org>
Cc: Christoph Lameter <cl@linux.com>
Cc: Martin Liu <liumartin@google.com>
Cc: David Rientjes <rientjes@google.com>
Cc: christian.koenig@amd.com
Cc: Shakeel Butt <shakeel.butt@linux.dev>
Cc: SeongJae Park <sj@kernel.org>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Johannes Weiner <hannes@cmpxchg.org>
Cc: Sweet Tea Dorminy <sweettea-kernel@dorminy.me>
Cc: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Cc: "Liam R . Howlett" <liam.howlett@oracle.com>
Cc: Mike Rapoport <rppt@kernel.org>
Cc: Suren Baghdasaryan <surenb@google.com>
Cc: Vlastimil Babka <vbabka@suse.cz>
Cc: Christian Brauner <brauner@kernel.org>
Cc: Wei Yang <richard.weiyang@gmail.com>
Cc: David Hildenbrand <david@redhat.com>
Cc: Miaohe Lin <linmiaohe@huawei.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: linux-mm@kvack.org
Cc: linux-trace-kernel@vger.kernel.org
Cc: Yu Zhao <yuzhao@google.com>
Cc: Roman Gushchin <roman.gushchin@linux.dev>
Cc: Mateusz Guzik <mjguzik@gmail.com>
Cc: Matthew Wilcox <willy@infradead.org>
Cc: Baolin Wang <baolin.wang@linux.alibaba.com>
Cc: Aboorva Devarajan <aboorvad@linux.ibm.com>
Mathieu Desnoyers (3):
lib: Introduce hierarchical per-cpu counters
lib: Test hierarchical per-cpu counters
mm: Improve RSS counter approximation accuracy for proc interfaces
.../core-api/percpu-counter-tree.rst | 75 ++
include/linux/mm.h | 19 +-
include/linux/mm_types.h | 54 +-
include/linux/percpu_counter_tree.h | 367 +++++++++
include/trace/events/kmem.h | 2 +-
init/main.c | 2 +
kernel/fork.c | 22 +-
lib/Kconfig | 12 +
lib/Makefile | 1 +
lib/percpu_counter_tree.c | 702 ++++++++++++++++++
lib/tests/Makefile | 2 +
lib/tests/percpu_counter_tree_kunit.c | 399 ++++++++++
12 files changed, 1627 insertions(+), 30 deletions(-)
create mode 100644 Documentation/core-api/percpu-counter-tree.rst
create mode 100644 include/linux/percpu_counter_tree.h
create mode 100644 lib/percpu_counter_tree.c
create mode 100644 lib/tests/percpu_counter_tree_kunit.c
--
2.39.5
| null | null | null | [PATCH v18 0/3] Improve proc RSS accuracy | Use hierarchical per-cpu counters for RSS tracking to improve the
accuracy of per-mm RSS sum approximation on large many-core systems [1].
This improves the accuracy of the RSS values returned by proc
interfaces.
Here is a (possibly incomplete) list of the prior approaches that were
used or proposed, along with their downside:
1) Per-thread rss tracking: large error on many-thread processes.
2) Per-CPU counters: up to 12% slower for short-lived processes and 9%
increased system time in make test workloads [1]. Moreover, the
inaccuracy increases with O(n^2) with the number of CPUs.
3) Per-NUMA-node counters: requires atomics on fast-path (overhead),
error is high with systems that have lots of NUMA nodes (32 times
the number of NUMA nodes).
4) Use a percise per-cpu counter sum for each counter value query:
Requires iteration on each possible CPUs for each sum, which
adds overhead on large many-core systems running many processes.
The approach proposed here is to replace the per-cpu counters by the
hierarchical per-cpu counters, which bounds the inaccuracy based on the
system topology with O(N*logN).
* Testing results:
Test hardware: 2 sockets AMD EPYC 9654 96-Core Processor (384 logical CPUs total)
Methodology:
Comparing the current upstream implementation with the hierarchical
counters is done by keeping both implementations wired up in parallel,
and running a single-process, single-threaded program which hops
randomly across CPUs in the system, calling mmap(2) and munmap(2) on
random CPUs, keeping track of an array of allocated mappings, randomly
choosing entries to either map or unmap.
get_mm_counter() is instrumented to compare the upstream counter
approximation to the precise value, and print the delta when going over
a given threshold. The delta of the hierarchical counter approximation
to the precise value is also printed for comparison.
After a few minutes running this test, the upstream implementation
counter approximation reaches a 1GB delta from the
precise value, compared to 80MB delta with the hierarchical counter.
The hierarchical counter provides a guaranteed maximum approximation
inaccuracy of 192MB on that hardware topology.
* Fast path implementation comparison
The new inline percpu_counter_tree_add() uses a this_cpu_add_return()
for the fast path (under a certain allocation size threshold). Above
that, it calls a slow path which "trickles up" the carry to upper level
counters with atomic_add_return.
In comparison, the upstream counters implementation calls
percpu_counter_add_batch which uses this_cpu_try_cmpxchg() on the fast
path, and does a raw_spin_lock_irqsave above a certain threshold.
The hierarchical implementation is therefore expected to have less
contention on mid-sized allocations than the upstream counters because
the atomic counters tracking those bits are only shared across nearby
CPUs. In comparison, the upstream counters immediately use a global
spinlock when reaching the threshold.
* Benchmarks
Using will-it-scale page_fault1 benchmarks to compare the upstream
counters to the hierarchical counters. This is done with hyperthreading
disabled. The speedup is within the standard deviation of the upstream
runs, so the overhead is not significant.
upstream hierarchical speedup
page_fault1_processes -s 100 -t 1 614783 615558 +0.1%
page_fault1_threads -s 100 -t 1 612788 612447 -0.1%
page_fault1_processes -s 100 -t 96 37994977 37932035 -0.2%
page_fault1_threads -s 100 -t 96 2484130 2504860 +0.8%
page_fault1_processes -s 100 -t 192 71262917 71118830 -0.2%
page_fault1_threads -s 100 -t 192 2446437 2469296 +0.1%
* Memory Use
The most important parts in terms of memory use are the per-cpu counters
and the tree items which propagate the carry.
In the proposed implementation, the per-cpu counters are allocated
within per-cpu data structures, so they end up using:
nr_possible_cpus * sizeof(unsigned long)
This is in addition to the tree items. The size of those items is
defined by the per_nr_cpu_order_config table "nr_items" field.
Each item is aligned on cacheline size (typically 64 bytes) to minimize
false sharing.
Here is the footprint for a few nr_cpu_ids on a 64-bit arch:
nr_cpu_ids percpu counters (bytes) nr_items items size (bytes) total (bytes)
2 16 1 64 80
4 32 3 192 224
8 64 7 448 512
64 512 21 1344 1856
128 1024 21 1344 2368
256 2048 37 2368 4416
512 4096 73 4672 8768
Compared to this, the upstream percpu counters use a 32-bit integer per-cpu
(4 bytes), and accumulate within a 64-bit global value.
So there is an extra memory footprint added by the current hpcc
implementation, but if it's an issue we have various options to consider
to reduce its footprint.
Link: https://lore.kernel.org/lkml/20250331223516.7810-2-sweettea-kernel@dorminy.me/ # [1]
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: "Paul E. McKenney" <paulmck@kernel.org>
Cc: Steven Rostedt <rostedt@goodmis.org>
Cc: Masami Hiramatsu <mhiramat@kernel.org>
Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Dennis Zhou <dennis@kernel.org>
Cc: Tejun Heo <tj@kernel.org>
Cc: Christoph Lameter <cl@linux.com>
Cc: Martin Liu <liumartin@google.com>
Cc: David Rientjes <rientjes@google.com>
Cc: christian.koenig@amd.com
Cc: Shakeel Butt <shakeel.butt@linux.dev>
Cc: SeongJae Park <sj@kernel.org>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Johannes Weiner <hannes@cmpxchg.org>
Cc: Sweet Tea Dorminy <sweettea-kernel@dorminy.me>
Cc: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Cc: "Liam R . Howlett" <liam.howlett@oracle.com>
Cc: Mike Rapoport <rppt@kernel.org>
Cc: Suren Baghdasaryan <surenb@google.com>
Cc: Vlastimil Babka <vbabka@suse.cz>
Cc: Christian Brauner <brauner@kernel.org>
Cc: Wei Yang <richard.weiyang@gmail.com>
Cc: David Hildenbrand <david@redhat.com>
Cc: Miaohe Lin <linmiaohe@huawei.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: linux-mm@kvack.org
Cc: linux-trace-kernel@vger.kernel.org
Cc: Yu Zhao <yuzhao@google.com>
Cc: Roman Gushchin <roman.gushchin@linux.dev>
Cc: Mateusz Guzik <mjguzik@gmail.com>
Cc: Matthew Wilcox <willy@infradead.org>
Cc: Baolin Wang <baolin.wang@linux.alibaba.com>
Cc: Aboorva Devarajan <aboorvad@linux.ibm.com>
---
Changes since v17:
- MM_STRUCT_FLEXIBLE_ARRAY_INIT needs to multiply PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE
by NR_MM_COUNTERS. Fix an out-of-bound on bootup on configurations
where nr_cpu_ids is close to NR_CPUS.
Changes since v16:
- Remove references to 2-pass OOM killer algorithm.
Changes since v15:
- Update the commit message to explain that this change is an
improvement to the accuracy of proc interfaces approximated RSS
values, and a preparation step for reducing OOM killer latency.
- Rebase on v2 of "mm: Fix OOM killer and proc stats inaccuracy on
large many-core systems".
Changes since v14:
- This change becomes the preparation for reducing the OOM killer latency.
Changes since v13:
- Change check_mm print format from %d to %ld.
Changes since v10:
- Rebase on top of mm_struct static init fixes.
- Change the alignment of mm_struct flexible array to the alignment of
the rss counters items (which are cacheline aligned on SMP).
- Move the rss counters items to first position within the flexible
array at the end of the mm_struct to place content in decreasing
alignment requirement order.
Changes since v8:
- Use percpu_counter_tree_init_many and
percpu_counter_tree_destroy_many APIs.
- Remove percpu tree items allocation. Extend mm_struct size to include
rss items. Those are handled through the new helpers
get_rss_stat_items() and get_rss_stat_items_size() and passed
as parameter to percpu_counter_tree_init_many().
Changes since v7:
- Use precise sum positive API to handle a scenario where an unlucky
precise sum iteration would observe negative counter values due to
concurrent updates.
Changes since v6:
- Rebased on v6.18-rc3.
- Implement get_mm_counter_sum as percpu_counter_tree_precise_sum for
/proc virtual files memory state queries.
Changes since v5:
- Use percpu_counter_tree_approximate_sum_positive.
Change since v4:
- get_mm_counter needs to return 0 or a positive value.
---
include/linux/mm.h | 19 ++++++++++----
include/linux/mm_types.h | 50 +++++++++++++++++++++++++++----------
include/trace/events/kmem.h | 2 +-
kernel/fork.c | 22 +++++++++-------
4 files changed, 65 insertions(+), 28 deletions(-)
diff --git a/include/linux/mm.h b/include/linux/mm.h
index 5be3d8a8f806..94f54a40b480 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -3057,38 +3057,47 @@ static inline bool get_user_page_fast_only(unsigned long addr,
{
return get_user_pages_fast_only(addr, 1, gup_flags, pagep) == 1;
}
+
+static inline struct percpu_counter_tree_level_item *get_rss_stat_items(struct mm_struct *mm)
+{
+ unsigned long ptr = (unsigned long)mm;
+
+ ptr += offsetof(struct mm_struct, flexible_array);
+ return (struct percpu_counter_tree_level_item *)ptr;
+}
+
/*
* per-process(per-mm_struct) statistics.
*/
static inline unsigned long get_mm_counter(struct mm_struct *mm, int member)
{
- return percpu_counter_read_positive(&mm->rss_stat[member]);
+ return percpu_counter_tree_approximate_sum_positive(&mm->rss_stat[member]);
}
static inline unsigned long get_mm_counter_sum(struct mm_struct *mm, int member)
{
- return percpu_counter_sum_positive(&mm->rss_stat[member]);
+ return percpu_counter_tree_precise_sum_positive(&mm->rss_stat[member]);
}
void mm_trace_rss_stat(struct mm_struct *mm, int member);
static inline void add_mm_counter(struct mm_struct *mm, int member, long value)
{
- percpu_counter_add(&mm->rss_stat[member], value);
+ percpu_counter_tree_add(&mm->rss_stat[member], value);
mm_trace_rss_stat(mm, member);
}
static inline void inc_mm_counter(struct mm_struct *mm, int member)
{
- percpu_counter_inc(&mm->rss_stat[member]);
+ percpu_counter_tree_add(&mm->rss_stat[member], 1);
mm_trace_rss_stat(mm, member);
}
static inline void dec_mm_counter(struct mm_struct *mm, int member)
{
- percpu_counter_dec(&mm->rss_stat[member]);
+ percpu_counter_tree_add(&mm->rss_stat[member], -1);
mm_trace_rss_stat(mm, member);
}
diff --git a/include/linux/mm_types.h b/include/linux/mm_types.h
index c8db9d69a826..1a808d78245d 100644
--- a/include/linux/mm_types.h
+++ b/include/linux/mm_types.h
@@ -18,7 +18,7 @@
#include <linux/page-flags-layout.h>
#include <linux/workqueue.h>
#include <linux/seqlock.h>
-#include <linux/percpu_counter.h>
+#include <linux/percpu_counter_tree.h>
#include <linux/types.h>
#include <linux/rseq_types.h>
#include <linux/bitmap.h>
@@ -1118,6 +1118,19 @@ typedef struct {
DECLARE_BITMAP(__mm_flags, NUM_MM_FLAG_BITS);
} __private mm_flags_t;
+/*
+ * The alignment of the mm_struct flexible array is based on the largest
+ * alignment of its content:
+ * __alignof__(struct percpu_counter_tree_level_item) provides a
+ * cacheline aligned alignment on SMP systems, else alignment on
+ * unsigned long on UP systems.
+ */
+#ifdef CONFIG_SMP
+# define __mm_struct_flexible_array_aligned __aligned(__alignof__(struct percpu_counter_tree_level_item))
+#else
+# define __mm_struct_flexible_array_aligned __aligned(__alignof__(unsigned long))
+#endif
+
struct kioctx_table;
struct iommu_mm_data;
struct mm_struct {
@@ -1263,7 +1276,7 @@ struct mm_struct {
unsigned long saved_e_flags;
#endif
- struct percpu_counter rss_stat[NR_MM_COUNTERS];
+ struct percpu_counter_tree rss_stat[NR_MM_COUNTERS];
struct linux_binfmt *binfmt;
@@ -1374,10 +1387,13 @@ struct mm_struct {
} __randomize_layout;
/*
- * The mm_cpumask needs to be at the end of mm_struct, because it
- * is dynamically sized based on nr_cpu_ids.
+ * The rss hierarchical counter items, mm_cpumask, and mm_cid
+ * masks need to be at the end of mm_struct, because they are
+ * dynamically sized based on nr_cpu_ids.
+ * The content of the flexible array needs to be placed in
+ * decreasing alignment requirement order.
*/
- char flexible_array[] __aligned(__alignof__(unsigned long));
+ char flexible_array[] __mm_struct_flexible_array_aligned;
};
/* Copy value to the first system word of mm flags, non-atomically. */
@@ -1416,22 +1432,28 @@ extern struct mm_struct init_mm;
#define MM_STRUCT_FLEXIBLE_ARRAY_INIT \
{ \
- [0 ... sizeof(cpumask_t) + MM_CID_STATIC_SIZE - 1] = 0 \
+ [0 ... (PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE * NR_MM_COUNTERS) + sizeof(cpumask_t) + MM_CID_STATIC_SIZE - 1] = 0 \
}
-/* Pointer magic because the dynamic array size confuses some compilers. */
-static inline void mm_init_cpumask(struct mm_struct *mm)
+static inline size_t get_rss_stat_items_size(void)
{
- unsigned long cpu_bitmap = (unsigned long)mm;
-
- cpu_bitmap += offsetof(struct mm_struct, flexible_array);
- cpumask_clear((struct cpumask *)cpu_bitmap);
+ return percpu_counter_tree_items_size() * NR_MM_COUNTERS;
}
/* Future-safe accessor for struct mm_struct's cpu_vm_mask. */
static inline cpumask_t *mm_cpumask(struct mm_struct *mm)
{
- return (struct cpumask *)&mm->flexible_array;
+ unsigned long ptr = (unsigned long)mm;
+
+ ptr += offsetof(struct mm_struct, flexible_array);
+ /* Skip RSS stats counters. */
+ ptr += get_rss_stat_items_size();
+ return (struct cpumask *)ptr;
+}
+
+static inline void mm_init_cpumask(struct mm_struct *mm)
+{
+ cpumask_clear((struct cpumask *)mm_cpumask(mm));
}
#ifdef CONFIG_LRU_GEN
@@ -1523,6 +1545,8 @@ static inline cpumask_t *mm_cpus_allowed(struct mm_struct *mm)
unsigned long bitmap = (unsigned long)mm;
bitmap += offsetof(struct mm_struct, flexible_array);
+ /* Skip RSS stats counters. */
+ bitmap += get_rss_stat_items_size();
/* Skip cpu_bitmap */
bitmap += cpumask_size();
return (struct cpumask *)bitmap;
diff --git a/include/trace/events/kmem.h b/include/trace/events/kmem.h
index 7f93e754da5c..91c81c44f884 100644
--- a/include/trace/events/kmem.h
+++ b/include/trace/events/kmem.h
@@ -442,7 +442,7 @@ TRACE_EVENT(rss_stat,
__entry->mm_id = mm_ptr_to_hash(mm);
__entry->curr = !!(current->mm == mm);
__entry->member = member;
- __entry->size = (percpu_counter_sum_positive(&mm->rss_stat[member])
+ __entry->size = (percpu_counter_tree_approximate_sum_positive(&mm->rss_stat[member])
<< PAGE_SHIFT);
),
diff --git a/kernel/fork.c b/kernel/fork.c
index e832da9d15a4..bb0c2613a560 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -134,6 +134,11 @@
*/
#define MAX_THREADS FUTEX_TID_MASK
+/*
+ * Batch size of rss stat approximation
+ */
+#define RSS_STAT_BATCH_SIZE 32
+
/*
* Protected counters by write_lock_irq(&tasklist_lock)
*/
@@ -627,14 +632,12 @@ static void check_mm(struct mm_struct *mm)
"Please make sure 'struct resident_page_types[]' is updated as well");
for (i = 0; i < NR_MM_COUNTERS; i++) {
- long x = percpu_counter_sum(&mm->rss_stat[i]);
-
- if (unlikely(x)) {
+ if (unlikely(percpu_counter_tree_precise_compare_value(&mm->rss_stat[i], 0) != 0))
pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld Comm:%s Pid:%d\n",
- mm, resident_page_types[i], x,
+ mm, resident_page_types[i],
+ percpu_counter_tree_precise_sum(&mm->rss_stat[i]),
current->comm,
task_pid_nr(current));
- }
}
if (mm_pgtables_bytes(mm))
@@ -732,7 +735,7 @@ void __mmdrop(struct mm_struct *mm)
put_user_ns(mm->user_ns);
mm_pasid_drop(mm);
mm_destroy_cid(mm);
- percpu_counter_destroy_many(mm->rss_stat, NR_MM_COUNTERS);
+ percpu_counter_tree_destroy_many(mm->rss_stat, NR_MM_COUNTERS);
free_mm(mm);
}
@@ -1124,8 +1127,9 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
if (mm_alloc_cid(mm, p))
goto fail_cid;
- if (percpu_counter_init_many(mm->rss_stat, 0, GFP_KERNEL_ACCOUNT,
- NR_MM_COUNTERS))
+ if (percpu_counter_tree_init_many(mm->rss_stat, get_rss_stat_items(mm),
+ NR_MM_COUNTERS, RSS_STAT_BATCH_SIZE,
+ GFP_KERNEL_ACCOUNT))
goto fail_pcpu;
mm->user_ns = get_user_ns(user_ns);
@@ -3009,7 +3013,7 @@ void __init mm_cache_init(void)
* dynamically sized based on the maximum CPU number this system
* can have, taking hotplug into account (nr_cpu_ids).
*/
- mm_size = sizeof(struct mm_struct) + cpumask_size() + mm_cid_size();
+ mm_size = sizeof(struct mm_struct) + cpumask_size() + mm_cid_size() + get_rss_stat_items_size();
mm_cachep = kmem_cache_create_usercopy("mm_struct",
mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
--
2.39.5 | {
"author": "Mathieu Desnoyers <mathieu.desnoyers@efficios.com>",
"date": "Fri, 27 Feb 2026 10:37:30 -0500",
"is_openbsd": false,
"thread_id": "20260227153730.1556542-4-mathieu.desnoyers@efficios.com.mbox.gz"
} |
lkml_critique | lkml | This series introduces the hierarchical tree counter (hpcc) to increase
accuracy of approximated RSS counters exposed through proc interfaces.
With a test program hopping across CPUs doing frequent mmap/munmap
operations, the upstream implementation approximation reaches a 1GB
delta from the precise value after a few minutes, compared to a 80MB
delta with the hierarchical counter. The hierarchical counter provides a
guaranteed maximum approximation inaccuracy of 192MB on that hardware
topology.
This series is based on tag v7.0-rc1.
The main changes since v17:
- Fix patch series bissectability.
- Export GPL symbols for kunit tests.
- Improve kunit tests coverage.
- Fix kunit tests wait queue head reinit bug.
- Fix an out-of-bound on bootup on configurations where nr_cpu_ids is
close to NR_CPUS.
Andrew, this series targets 7.1.
Thanks!
Mathieu
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: "Paul E. McKenney" <paulmck@kernel.org>
Cc: Steven Rostedt <rostedt@goodmis.org>
Cc: Masami Hiramatsu <mhiramat@kernel.org>
Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Dennis Zhou <dennis@kernel.org>
Cc: Tejun Heo <tj@kernel.org>
Cc: Christoph Lameter <cl@linux.com>
Cc: Martin Liu <liumartin@google.com>
Cc: David Rientjes <rientjes@google.com>
Cc: christian.koenig@amd.com
Cc: Shakeel Butt <shakeel.butt@linux.dev>
Cc: SeongJae Park <sj@kernel.org>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Johannes Weiner <hannes@cmpxchg.org>
Cc: Sweet Tea Dorminy <sweettea-kernel@dorminy.me>
Cc: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Cc: "Liam R . Howlett" <liam.howlett@oracle.com>
Cc: Mike Rapoport <rppt@kernel.org>
Cc: Suren Baghdasaryan <surenb@google.com>
Cc: Vlastimil Babka <vbabka@suse.cz>
Cc: Christian Brauner <brauner@kernel.org>
Cc: Wei Yang <richard.weiyang@gmail.com>
Cc: David Hildenbrand <david@redhat.com>
Cc: Miaohe Lin <linmiaohe@huawei.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: linux-mm@kvack.org
Cc: linux-trace-kernel@vger.kernel.org
Cc: Yu Zhao <yuzhao@google.com>
Cc: Roman Gushchin <roman.gushchin@linux.dev>
Cc: Mateusz Guzik <mjguzik@gmail.com>
Cc: Matthew Wilcox <willy@infradead.org>
Cc: Baolin Wang <baolin.wang@linux.alibaba.com>
Cc: Aboorva Devarajan <aboorvad@linux.ibm.com>
Mathieu Desnoyers (3):
lib: Introduce hierarchical per-cpu counters
lib: Test hierarchical per-cpu counters
mm: Improve RSS counter approximation accuracy for proc interfaces
.../core-api/percpu-counter-tree.rst | 75 ++
include/linux/mm.h | 19 +-
include/linux/mm_types.h | 54 +-
include/linux/percpu_counter_tree.h | 367 +++++++++
include/trace/events/kmem.h | 2 +-
init/main.c | 2 +
kernel/fork.c | 22 +-
lib/Kconfig | 12 +
lib/Makefile | 1 +
lib/percpu_counter_tree.c | 702 ++++++++++++++++++
lib/tests/Makefile | 2 +
lib/tests/percpu_counter_tree_kunit.c | 399 ++++++++++
12 files changed, 1627 insertions(+), 30 deletions(-)
create mode 100644 Documentation/core-api/percpu-counter-tree.rst
create mode 100644 include/linux/percpu_counter_tree.h
create mode 100644 lib/percpu_counter_tree.c
create mode 100644 lib/tests/percpu_counter_tree_kunit.c
--
2.39.5
| null | null | null | [PATCH v18 0/3] Improve proc RSS accuracy | * Motivation
The purpose of this hierarchical split-counter scheme is to:
- Minimize contention when incrementing and decrementing counters,
- Provide fast access to a sum approximation,
- Provide a sum approximation with an acceptable accuracy level when
scaling to many-core systems.
- Provide approximate and precise comparison of two counters, and
between a counter and a value.
- Provide possible precise sum ranges for a given sum approximation.
Its goals are twofold:
- Improve the accuracy of the approximated RSS counter values returned
by proc interfaces [1],
- Reduce the latency of the OOM killer on large many-core systems.
* Design
The hierarchical per-CPU counters propagate a sum approximation through
a N-way tree. When reaching the batch size, the carry is propagated
through a binary tree which consists of logN(nr_cpu_ids) levels. The
batch size for each level is twice the batch size of the prior level.
Example propagation diagram with 8 cpus through a binary tree:
Level 0: 0 1 2 3 4 5 6 7
| / | / | / | /
| / | / | / | /
| / | / | / | /
Level 1: 0 1 2 3
| / | /
| / | /
| / | /
Level 2: 0 1
| /
| /
| /
Level 3: 0
For a binary tree, the maximum inaccuracy is bound by:
batch_size * log2(nr_cpu_ids) * nr_cpu_ids
which evolves with O(n*log(n)) as the number of CPUs increases.
For a N-way tree, the maximum inaccuracy can be pre-calculated
based on the the N-arity of each level and the batch size.
* Memory Use
The most important parts in terms of memory use are the per-cpu counters
and the tree items which propagate the carry.
In the proposed implementation, the per-cpu counters are allocated
within per-cpu data structures, so they end up using:
nr_possible_cpus * sizeof(unsigned long)
This is in addition to the tree items. The size of those items is
defined by the per_nr_cpu_order_config table "nr_items" field.
Each item is aligned on cacheline size (typically 64 bytes) to minimize
false sharing.
Here is the footprint for a few nr_cpu_ids on a 64-bit arch:
nr_cpu_ids percpu counters (bytes) nr_items items size (bytes) total (bytes)
2 16 1 64 80
4 32 3 192 224
8 64 7 448 512
64 512 21 1344 1856
128 1024 21 1344 2368
256 2048 37 2368 4416
512 4096 73 4672 8768
There are of course various trade offs we can make here. We can:
* Increase the n-arity of the intermediate items to shrink the nr_items
required for a given nr_cpus. This will increase contention of carry
propagation across more cores.
* Remove cacheline alignment of intermediate tree items. This will
shrink the memory needed for tree items, but will increase false
sharing.
* Represent intermediate tree items on a byte rather than long.
This further reduces the memory required for intermediate tree
items, but further increases false sharing.
* Represent per-cpu counters on bytes rather than long. This makes
the "sum" operation trickier, because it needs to iterate on the
intermediate carry propagation nodes as well and synchronize with
ongoing "tree add" operations. It further reduces memory use.
* Implement a custom strided allocator for intermediate items carry
propagation bytes. This shares cachelines across different tree
instances, keeping good locality. This ensures that all accesses
from a given location in the machine topology touch the same
cacheline for the various tree instances. This adds complexity,
but provides compactness as well as minimal false-sharing.
Compared to this, the upstream percpu counters use a 32-bit integer per-cpu
(4 bytes), and accumulate within a 64-bit global value.
So there is an extra memory footprint added by the current hpcc
implementation, but if it's an issue we have various options to consider
to reduce its footprint.
Link: https://lore.kernel.org/lkml/20250331223516.7810-2-sweettea-kernel@dorminy.me/ # [1]
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: "Paul E. McKenney" <paulmck@kernel.org>
Cc: Steven Rostedt <rostedt@goodmis.org>
Cc: Masami Hiramatsu <mhiramat@kernel.org>
Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Dennis Zhou <dennis@kernel.org>
Cc: Tejun Heo <tj@kernel.org>
Cc: Christoph Lameter <cl@linux.com>
Cc: Martin Liu <liumartin@google.com>
Cc: David Rientjes <rientjes@google.com>
Cc: christian.koenig@amd.com
Cc: Shakeel Butt <shakeel.butt@linux.dev>
Cc: SeongJae Park <sj@kernel.org>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Johannes Weiner <hannes@cmpxchg.org>
Cc: Sweet Tea Dorminy <sweettea-kernel@dorminy.me>
Cc: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Cc: "Liam R . Howlett" <liam.howlett@oracle.com>
Cc: Mike Rapoport <rppt@kernel.org>
Cc: Suren Baghdasaryan <surenb@google.com>
Cc: Vlastimil Babka <vbabka@suse.cz>
Cc: Christian Brauner <brauner@kernel.org>
Cc: Wei Yang <richard.weiyang@gmail.com>
Cc: David Hildenbrand <david@redhat.com>
Cc: Miaohe Lin <linmiaohe@huawei.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: linux-mm@kvack.org
Cc: linux-trace-kernel@vger.kernel.org
Cc: Yu Zhao <yuzhao@google.com>
Cc: Roman Gushchin <roman.gushchin@linux.dev>
Cc: Mateusz Guzik <mjguzik@gmail.com>
Cc: Matthew Wilcox <willy@infradead.org>
Cc: Baolin Wang <baolin.wang@linux.alibaba.com>
Cc: Aboorva Devarajan <aboorvad@linux.ibm.com>
---
Change since v17:
- Remove PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE from
MM_STRUCT_FLEXIBLE_ARRAY_INIT. This is introduced is a later patch
and adding it here breaks bissectability.
- Export GPL symbols for kunit tests.
Changes since v16:
- Only perform atomic increments of intermediate tree nodes when
bits which are significant for carry propagation are being changed.
Changes since v15:
- Rebase on v2 of "mm: Fix OOM killer inaccuracy on large many-core systems".
- Update the commit message to explain the two goals of hpcc:
provide a more accurate approximation, and reduce OOM killer latency.
- Change percpu_counter_tree_approximate_accuracy_range to increment the
under/over parameters rather than set them. This requires callers to
initialize them to 0, but facilitates scenarios where accuracy needs to
be summed over many counters.
- Clarify comments above percpu_counter_tree_approximate_accuracy_range.
Changes since v14:
- Add Documentation/core-api/percpu-counter-tree.rst.
- Make percpu_counter_tree_approximate_accuracy_range static inline.
Changes since v12:
- Use atomic_long_set for percpu_counter_tree_set in UP build.
- percpu_counter_tree_precise_sum returns long type.
Changes since v11:
- Reduce level0 per-cpu memory allocation to the size required by those
percpu counters.
- Use unsigned long type rather than unsigned int.
- Introduce functions to return the min/max range of possible
precise sums.
Changes since v10:
- Fold "mm: Take into account hierarchical percpu tree items for static
mm_struct definitions".
Changes since v9:
- Introduce kerneldoc documentation.
- Document structure fields.
- Remove inline from percpu_counter_tree_add().
- Reject batch_size==1 which makes no sense.
- Fix copy-paste bug in percpu_counter_tree_precise_compare()
(wrong inequality comparison).
- Rename "inaccuracy" to "accuracy", which makes it easier to
document.
- Track accuracy limits more precisely. In two's complement
signed integers, the range before a n-bit underflow is one
unit larger than the range before a n-bit overflow. This sums
for all the counters within the tree. Therefore the "under"
vs "over" accuracy is not symmetrical.
Changes since v8:
- Remove migrate guard from the fast path. It does not
matter through which path the carry is propagated up
the tree.
- Rebase on top of v6.18-rc6.
- Introduce percpu_counter_tree_init_many and
percpu_counter_tree_destroy_many APIs.
- Move tree items allocation to the caller.
- Introduce percpu_counter_tree_items_size().
- Move percpu_counter_tree_subsystem_init() call before mm_core_init()
so percpu_counter_tree_items_size() is initialized before it is used.
Changes since v7:
- Explicitly initialize the subsystem from start_kernel() right
after mm_core_init() so it is up and running before the creation of
the first mm at boot.
- Remove the module.h include which is not needed with the explicit
initialization.
- Only consider levels>0 items for order={0,1} nr_items. No
functional change except to allocate only the amount of memory
which is strictly needed.
- Introduce positive precise sum API to handle a scenario where an
unlucky precise sum iteration would hit negative counter values
concurrently with counter updates.
Changes since v5:
- Introduce percpu_counter_tree_approximate_sum_positive.
- Introduce !CONFIG_SMP static inlines for UP build.
- Remove percpu_counter_tree_set_bias from the public API and make it
static.
Changes since v3:
- Add gfp flags to init function.
Changes since v2:
- Introduce N-way tree to reduce tree depth on larger systems.
Changes since v1:
- Remove percpu_counter_tree_precise_sum_unbiased from public header,
make this function static,
- Introduce precise and approximate comparisons between two counters,
- Reorder the struct percpu_counter_tree fields,
- Introduce approx_sum field, which points to the approximate sum
for the percpu_counter_tree_approximate_sum() fast path.
---
.../core-api/percpu-counter-tree.rst | 75 ++
include/linux/mm_types.h | 4 +-
include/linux/percpu_counter_tree.h | 367 +++++++++
init/main.c | 2 +
lib/Makefile | 1 +
lib/percpu_counter_tree.c | 702 ++++++++++++++++++
6 files changed, 1149 insertions(+), 2 deletions(-)
create mode 100644 Documentation/core-api/percpu-counter-tree.rst
create mode 100644 include/linux/percpu_counter_tree.h
create mode 100644 lib/percpu_counter_tree.c
diff --git a/Documentation/core-api/percpu-counter-tree.rst b/Documentation/core-api/percpu-counter-tree.rst
new file mode 100644
index 000000000000..196da056e7b4
--- /dev/null
+++ b/Documentation/core-api/percpu-counter-tree.rst
@@ -0,0 +1,75 @@
+========================================
+The Hierarchical Per-CPU Counters (HPCC)
+========================================
+
+:Author: Mathieu Desnoyers
+
+Introduction
+============
+
+Counters come in many varieties, each with their own trade offs:
+
+ * A global atomic counter provides a fast read access to the current
+ sum, at the expense of cache-line bouncing on updates. This leads to
+ poor performance of frequent updates from various cores on large SMP
+ systems.
+
+ * A per-cpu split counter provides fast updates to per-cpu counters,
+ at the expense of a slower aggregation (sum). The sum operation needs
+ to iterate over all per-cpu counters to calculate the current total.
+
+The hierarchical per-cpu counters attempt to provide the best of both
+worlds (fast updates, and fast sum) by relaxing requirements on the sum
+accuracy. It allows quickly querying an approximated sum value, along
+with the possible min/max ranges of the associated precise sum. The
+exact precise sum can still be calculated with an iteration on all
+per-cpu counter, but the availability of an approximated sum value with
+possible precise sum min/max ranges allows eliminating candidates which
+are certainly outside of a known target range without the overhead of
+precise sums.
+
+Overview
+========
+
+The herarchical per-cpu counters are organized as a tree with the tree
+root at the bottom (last level) and the first level of the tree
+consisting of per-cpu counters.
+
+The intermediate tree levels contain carry propagation counters. When
+reaching a threshold (batch size), the carry is propagated down the
+tree.
+
+This allows reading an approximated value at the root, which has a
+bounded accuracy (minimum/maximum possible precise sum range) determined
+by the tree topology.
+
+Use Cases
+=========
+
+Use cases HPCC is meant to handle invove tracking resources which are
+used across many CPUs to quickly sum as feedback for decision making to
+apply throttling, quota limits, sort tasks, and perform memory or task
+migration decisions. When considering approximated sums within the
+accuracy range of the decision threshold, the user can either:
+
+ * Be conservative and fast: Consider that the sum has reached the
+ limit as soon as the given limit is within the approximation range.
+
+ * Be aggressive and fast: Consider that the sum is over the
+ limit only when the approximation range is over the given limit.
+
+ * Be precise and slow: Do a precise comparison with the limit, which
+ requires a precise sum when the limit is within the approximated
+ range.
+
+One use-case for these hierarchical counters is to implement a two-pass
+algorithm to speed up sorting picking a maximum/minimunm sum value from
+a set. A first pass compares the approximated values, and then a second
+pass only needs the precise sum for counter trees which are within the
+possible precise sum range of the counter tree chosen by the first pass.
+
+Functions and structures
+========================
+
+.. kernel-doc:: include/linux/percpu_counter_tree.h
+.. kernel-doc:: lib/percpu_counter_tree.c
diff --git a/include/linux/mm_types.h b/include/linux/mm_types.h
index 3cc8ae722886..c8db9d69a826 100644
--- a/include/linux/mm_types.h
+++ b/include/linux/mm_types.h
@@ -1414,8 +1414,8 @@ static inline void __mm_flags_set_mask_bits_word(struct mm_struct *mm,
MT_FLAGS_USE_RCU)
extern struct mm_struct init_mm;
-#define MM_STRUCT_FLEXIBLE_ARRAY_INIT \
-{ \
+#define MM_STRUCT_FLEXIBLE_ARRAY_INIT \
+{ \
[0 ... sizeof(cpumask_t) + MM_CID_STATIC_SIZE - 1] = 0 \
}
diff --git a/include/linux/percpu_counter_tree.h b/include/linux/percpu_counter_tree.h
new file mode 100644
index 000000000000..828c763edd4a
--- /dev/null
+++ b/include/linux/percpu_counter_tree.h
@@ -0,0 +1,367 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+/* SPDX-FileCopyrightText: 2025 Mathieu Desnoyers <mathieu.desnoyers@efficios.com> */
+
+#ifndef _PERCPU_COUNTER_TREE_H
+#define _PERCPU_COUNTER_TREE_H
+
+#include <linux/preempt.h>
+#include <linux/atomic.h>
+#include <linux/percpu.h>
+
+#ifdef CONFIG_SMP
+
+#if NR_CPUS == (1U << 0)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 0
+#elif NR_CPUS <= (1U << 1)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 1
+#elif NR_CPUS <= (1U << 2)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 3
+#elif NR_CPUS <= (1U << 3)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 7
+#elif NR_CPUS <= (1U << 4)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 7
+#elif NR_CPUS <= (1U << 5)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 11
+#elif NR_CPUS <= (1U << 6)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 21
+#elif NR_CPUS <= (1U << 7)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 21
+#elif NR_CPUS <= (1U << 8)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 37
+#elif NR_CPUS <= (1U << 9)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 73
+#elif NR_CPUS <= (1U << 10)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 149
+#elif NR_CPUS <= (1U << 11)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 293
+#elif NR_CPUS <= (1U << 12)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 585
+#elif NR_CPUS <= (1U << 13)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 1173
+#elif NR_CPUS <= (1U << 14)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 2341
+#elif NR_CPUS <= (1U << 15)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 4681
+#elif NR_CPUS <= (1U << 16)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 4681
+#elif NR_CPUS <= (1U << 17)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 8777
+#elif NR_CPUS <= (1U << 18)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 17481
+#elif NR_CPUS <= (1U << 19)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 34953
+#elif NR_CPUS <= (1U << 20)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS 69905
+#else
+# error "Unsupported number of CPUs."
+#endif
+
+struct percpu_counter_tree_level_item {
+ atomic_long_t count; /*
+ * Count the number of carry for this tree item.
+ * The carry counter is kept at the order of the
+ * carry accounted for at this tree level.
+ */
+} ____cacheline_aligned_in_smp;
+
+#define PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE \
+ (PERCPU_COUNTER_TREE_STATIC_NR_ITEMS * sizeof(struct percpu_counter_tree_level_item))
+
+struct percpu_counter_tree {
+ /* Fast-path fields. */
+ unsigned long __percpu *level0; /* Pointer to per-CPU split counters (tree level 0). */
+ unsigned long level0_bit_mask; /* Bit mask to apply to detect carry propagation from tree level 0. */
+ union {
+ unsigned long *i; /* Approximate sum for single-CPU topology. */
+ atomic_long_t *a; /* Approximate sum for SMP topology. */
+ } approx_sum;
+ long bias; /* Bias to apply to counter precise and approximate values. */
+
+ /* Slow-path fields. */
+ struct percpu_counter_tree_level_item *items; /* Array of tree items for levels 1 to N. */
+ unsigned long batch_size; /*
+ * The batch size is the increment step at level 0 which
+ * triggers a carry propagation. The batch size is required
+ * to be greater than 1, and a power of 2.
+ */
+ /*
+ * The tree approximate sum is guaranteed to be within this accuracy range:
+ * (precise_sum - approx_accuracy_range.under) <= approx_sum <= (precise_sum + approx_accuracy_range.over).
+ * This accuracy is derived from the hardware topology and the tree batch_size.
+ * The "under" accuracy is larger than the "over" accuracy because the negative range of a
+ * two's complement signed integer is one unit larger than the positive range. This delta
+ * is summed for each tree item, which leads to a significantly larger "under" accuracy range
+ * compared to the "over" accuracy range.
+ */
+ struct {
+ unsigned long under;
+ unsigned long over;
+ } approx_accuracy_range;
+};
+
+size_t percpu_counter_tree_items_size(void);
+int percpu_counter_tree_init_many(struct percpu_counter_tree *counters, struct percpu_counter_tree_level_item *items,
+ unsigned int nr_counters, unsigned long batch_size, gfp_t gfp_flags);
+int percpu_counter_tree_init(struct percpu_counter_tree *counter, struct percpu_counter_tree_level_item *items,
+ unsigned long batch_size, gfp_t gfp_flags);
+void percpu_counter_tree_destroy_many(struct percpu_counter_tree *counter, unsigned int nr_counters);
+void percpu_counter_tree_destroy(struct percpu_counter_tree *counter);
+void percpu_counter_tree_add(struct percpu_counter_tree *counter, long inc);
+long percpu_counter_tree_precise_sum(struct percpu_counter_tree *counter);
+int percpu_counter_tree_approximate_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b);
+int percpu_counter_tree_approximate_compare_value(struct percpu_counter_tree *counter, long v);
+int percpu_counter_tree_precise_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b);
+int percpu_counter_tree_precise_compare_value(struct percpu_counter_tree *counter, long v);
+void percpu_counter_tree_set(struct percpu_counter_tree *counter, long v);
+int percpu_counter_tree_subsystem_init(void);
+
+/**
+ * percpu_counter_tree_approximate_sum() - Return approximate counter sum.
+ * @counter: The counter to sum.
+ *
+ * Querying the approximate sum is fast, but it is only accurate within
+ * the bounds delimited by percpu_counter_tree_approximate_accuracy_range().
+ * This is meant to be used when speed is preferred over accuracy.
+ *
+ * Return: The current approximate counter sum.
+ */
+static inline
+long percpu_counter_tree_approximate_sum(struct percpu_counter_tree *counter)
+{
+ unsigned long v;
+
+ if (!counter->level0_bit_mask)
+ v = READ_ONCE(*counter->approx_sum.i);
+ else
+ v = atomic_long_read(counter->approx_sum.a);
+ return (long) (v + (unsigned long)READ_ONCE(counter->bias));
+}
+
+/**
+ * percpu_counter_tree_approximate_accuracy_range - Query the accuracy range for a counter tree.
+ * @counter: Counter to query.
+ * @under: Pointer to a variable to be incremented of the approximation
+ * accuracy range below the precise sum.
+ * @over: Pointer to a variable to be incremented of the approximation
+ * accuracy range above the precise sum.
+ *
+ * Query the accuracy range limits for the counter.
+ * Because of two's complement binary representation, the "under" range is typically
+ * slightly larger than the "over" range.
+ * Those values are derived from the hardware topology and the counter tree batch size.
+ * They are invariant for a given counter tree.
+ * Using this function should not be typically required, see the following functions instead:
+ * * percpu_counter_tree_approximate_compare(),
+ * * percpu_counter_tree_approximate_compare_value(),
+ * * percpu_counter_tree_precise_compare(),
+ * * percpu_counter_tree_precise_compare_value().
+ */
+static inline
+void percpu_counter_tree_approximate_accuracy_range(struct percpu_counter_tree *counter,
+ unsigned long *under, unsigned long *over)
+{
+ *under += counter->approx_accuracy_range.under;
+ *over += counter->approx_accuracy_range.over;
+}
+
+#else /* !CONFIG_SMP */
+
+#define PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE 0
+
+struct percpu_counter_tree_level_item;
+
+struct percpu_counter_tree {
+ atomic_long_t count;
+};
+
+static inline
+size_t percpu_counter_tree_items_size(void)
+{
+ return 0;
+}
+
+static inline
+int percpu_counter_tree_init_many(struct percpu_counter_tree *counters, struct percpu_counter_tree_level_item *items,
+ unsigned int nr_counters, unsigned long batch_size, gfp_t gfp_flags)
+{
+ for (unsigned int i = 0; i < nr_counters; i++)
+ atomic_long_set(&counters[i].count, 0);
+ return 0;
+}
+
+static inline
+int percpu_counter_tree_init(struct percpu_counter_tree *counter, struct percpu_counter_tree_level_item *items,
+ unsigned long batch_size, gfp_t gfp_flags)
+{
+ return percpu_counter_tree_init_many(counter, items, 1, batch_size, gfp_flags);
+}
+
+static inline
+void percpu_counter_tree_destroy_many(struct percpu_counter_tree *counter, unsigned int nr_counters)
+{
+}
+
+static inline
+void percpu_counter_tree_destroy(struct percpu_counter_tree *counter)
+{
+}
+
+static inline
+long percpu_counter_tree_precise_sum(struct percpu_counter_tree *counter)
+{
+ return atomic_long_read(&counter->count);
+}
+
+static inline
+int percpu_counter_tree_precise_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)
+{
+ long count_a = percpu_counter_tree_precise_sum(a),
+ count_b = percpu_counter_tree_precise_sum(b);
+
+ if (count_a == count_b)
+ return 0;
+ if (count_a < count_b)
+ return -1;
+ return 1;
+}
+
+static inline
+int percpu_counter_tree_precise_compare_value(struct percpu_counter_tree *counter, long v)
+{
+ long count = percpu_counter_tree_precise_sum(counter);
+
+ if (count == v)
+ return 0;
+ if (count < v)
+ return -1;
+ return 1;
+}
+
+static inline
+int percpu_counter_tree_approximate_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)
+{
+ return percpu_counter_tree_precise_compare(a, b);
+}
+
+static inline
+int percpu_counter_tree_approximate_compare_value(struct percpu_counter_tree *counter, long v)
+{
+ return percpu_counter_tree_precise_compare_value(counter, v);
+}
+
+static inline
+void percpu_counter_tree_set(struct percpu_counter_tree *counter, long v)
+{
+ atomic_long_set(&counter->count, v);
+}
+
+static inline
+void percpu_counter_tree_approximate_accuracy_range(struct percpu_counter_tree *counter,
+ unsigned long *under, unsigned long *over)
+{
+}
+
+static inline
+void percpu_counter_tree_add(struct percpu_counter_tree *counter, long inc)
+{
+ atomic_long_add(inc, &counter->count);
+}
+
+static inline
+long percpu_counter_tree_approximate_sum(struct percpu_counter_tree *counter)
+{
+ return percpu_counter_tree_precise_sum(counter);
+}
+
+static inline
+int percpu_counter_tree_subsystem_init(void)
+{
+ return 0;
+}
+
+#endif /* CONFIG_SMP */
+
+/**
+ * percpu_counter_tree_approximate_sum_positive() - Return a positive approximate counter sum.
+ * @counter: The counter to sum.
+ *
+ * Return an approximate counter sum which is guaranteed to be greater
+ * or equal to 0.
+ *
+ * Return: The current positive approximate counter sum.
+ */
+static inline
+long percpu_counter_tree_approximate_sum_positive(struct percpu_counter_tree *counter)
+{
+ long v = percpu_counter_tree_approximate_sum(counter);
+ return v > 0 ? v : 0;
+}
+
+/**
+ * percpu_counter_tree_precise_sum_positive() - Return a positive precise counter sum.
+ * @counter: The counter to sum.
+ *
+ * Return a precise counter sum which is guaranteed to be greater
+ * or equal to 0.
+ *
+ * Return: The current positive precise counter sum.
+ */
+static inline
+long percpu_counter_tree_precise_sum_positive(struct percpu_counter_tree *counter)
+{
+ long v = percpu_counter_tree_precise_sum(counter);
+ return v > 0 ? v : 0;
+}
+
+/**
+ * percpu_counter_tree_approximate_min_max_range() - Return the approximation min and max precise values.
+ * @approx_sum: Approximated sum.
+ * @under: Tree accuracy range (under).
+ * @over: Tree accuracy range (over).
+ * @precise_min: Minimum possible value for precise sum (output).
+ * @precise_max: Maximum possible value for precise sum (output).
+ *
+ * Calculate the minimum and maximum precise values for a given
+ * approximation and (under, over) accuracy range.
+ *
+ * The range of the approximation as a function of the precise sum is expressed as:
+ *
+ * approx_sum >= precise_sum - approx_accuracy_range.under
+ * approx_sum <= precise_sum + approx_accuracy_range.over
+ *
+ * Therefore, the range of the precise sum as a function of the approximation is expressed as:
+ *
+ * precise_sum <= approx_sum + approx_accuracy_range.under
+ * precise_sum >= approx_sum - approx_accuracy_range.over
+ */
+static inline
+void percpu_counter_tree_approximate_min_max_range(long approx_sum, unsigned long under, unsigned long over,
+ long *precise_min, long *precise_max)
+{
+ *precise_min = approx_sum - over;
+ *precise_max = approx_sum + under;
+}
+
+/**
+ * percpu_counter_tree_approximate_min_max() - Return the tree approximation, min and max possible precise values.
+ * @counter: The counter to sum.
+ * @approx_sum: Approximate sum (output).
+ * @precise_min: Minimum possible value for precise sum (output).
+ * @precise_max: Maximum possible value for precise sum (output).
+ *
+ * Return the approximate sum, minimum and maximum precise values for
+ * a counter.
+ */
+static inline
+void percpu_counter_tree_approximate_min_max(struct percpu_counter_tree *counter,
+ long *approx_sum, long *precise_min, long *precise_max)
+{
+ unsigned long under = 0, over = 0;
+ long v = percpu_counter_tree_approximate_sum(counter);
+
+ percpu_counter_tree_approximate_accuracy_range(counter, &under, &over);
+ percpu_counter_tree_approximate_min_max_range(v, under, over, precise_min, precise_max);
+ *approx_sum = v;
+}
+
+#endif /* _PERCPU_COUNTER_TREE_H */
diff --git a/init/main.c b/init/main.c
index 1cb395dd94e4..13aeb7834111 100644
--- a/init/main.c
+++ b/init/main.c
@@ -105,6 +105,7 @@
#include <linux/ptdump.h>
#include <linux/time_namespace.h>
#include <linux/unaligned.h>
+#include <linux/percpu_counter_tree.h>
#include <net/net_namespace.h>
#include <asm/io.h>
@@ -1067,6 +1068,7 @@ void start_kernel(void)
vfs_caches_init_early();
sort_main_extable();
trap_init();
+ percpu_counter_tree_subsystem_init();
mm_core_init();
maple_tree_init();
poking_init();
diff --git a/lib/Makefile b/lib/Makefile
index 1b9ee167517f..abc32420b581 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -181,6 +181,7 @@ obj-$(CONFIG_TEXTSEARCH_KMP) += ts_kmp.o
obj-$(CONFIG_TEXTSEARCH_BM) += ts_bm.o
obj-$(CONFIG_TEXTSEARCH_FSM) += ts_fsm.o
obj-$(CONFIG_SMP) += percpu_counter.o
+obj-$(CONFIG_SMP) += percpu_counter_tree.o
obj-$(CONFIG_AUDIT_GENERIC) += audit.o
obj-$(CONFIG_AUDIT_COMPAT_GENERIC) += compat_audit.o
diff --git a/lib/percpu_counter_tree.c b/lib/percpu_counter_tree.c
new file mode 100644
index 000000000000..5c8fc2dcdc16
--- /dev/null
+++ b/lib/percpu_counter_tree.c
@@ -0,0 +1,702 @@
+// SPDX-License-Identifier: GPL-2.0+ OR MIT
+// SPDX-FileCopyrightText: 2025 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+
+/*
+ * Split Counters With Tree Approximation Propagation
+ *
+ * * Propagation diagram when reaching batch size thresholds (± batch size):
+ *
+ * Example diagram for 8 CPUs:
+ *
+ * log2(8) = 3 levels
+ *
+ * At each level, each pair propagates its values to the next level when
+ * reaching the batch size thresholds.
+ *
+ * Counters at levels 0, 1, 2 can be kept on a single byte ([-128 .. +127] range),
+ * although it may be relevant to keep them on "long" counters for
+ * simplicity. (complexity vs memory footprint tradeoff)
+ *
+ * Counter at level 3 can be kept on a "long" counter.
+ *
+ * Level 0: 0 1 2 3 4 5 6 7
+ * | / | / | / | /
+ * | / | / | / | /
+ * | / | / | / | /
+ * Level 1: 0 1 2 3
+ * | / | /
+ * | / | /
+ * | / | /
+ * Level 2: 0 1
+ * | /
+ * | /
+ * | /
+ * Level 3: 0
+ *
+ * * Approximation accuracy:
+ *
+ * BATCH(level N): Level N batch size.
+ *
+ * Example for BATCH(level 0) = 32.
+ *
+ * BATCH(level 0) = 32
+ * BATCH(level 1) = 64
+ * BATCH(level 2) = 128
+ * BATCH(level N) = BATCH(level 0) * 2^N
+ *
+ * per-counter global
+ * accuracy accuracy
+ * Level 0: [ -32 .. +31] ±256 (8 * 32)
+ * Level 1: [ -64 .. +63] ±256 (4 * 64)
+ * Level 2: [-128 .. +127] ±256 (2 * 128)
+ * Total: ------ ±768 (log2(nr_cpu_ids) * BATCH(level 0) * nr_cpu_ids)
+ *
+ * Note that the global accuracy can be calculated more precisely
+ * by taking into account that the positive accuracy range is
+ * 31 rather than 32.
+ *
+ * -----
+ *
+ * Approximate Sum Carry Propagation
+ *
+ * Let's define a number of counter bits for each level, e.g.:
+ *
+ * log2(BATCH(level 0)) = log2(32) = 5
+ * Let's assume, for this example, a 32-bit architecture (sizeof(long) == 4).
+ *
+ * nr_bit value_mask range
+ * Level 0: 5 bits v 0 .. +31
+ * Level 1: 1 bit (v & ~((1UL << 5) - 1)) 0 .. +63
+ * Level 2: 1 bit (v & ~((1UL << 6) - 1)) 0 .. +127
+ * Level 3: 25 bits (v & ~((1UL << 7) - 1)) 0 .. 2^32-1
+ *
+ * Note: Use a "long" per-cpu counter at level 0 to allow precise sum.
+ *
+ * Note: Use cacheline aligned counters at levels above 0 to prevent false sharing.
+ * If memory footprint is an issue, a specialized allocator could be used
+ * to eliminate padding.
+ *
+ * Example with expanded values:
+ *
+ * counter_add(counter, inc):
+ *
+ * if (!inc)
+ * return;
+ *
+ * res = percpu_add_return(counter @ Level 0, inc);
+ * orig = res - inc;
+ * if (inc < 0) {
+ * inc = -(-inc & ~0b00011111); // Clear used bits
+ * // xor bit 5: underflow
+ * if ((inc ^ orig ^ res) & 0b00100000)
+ * inc -= 0b00100000;
+ * } else {
+ * inc &= ~0b00011111; // Clear used bits
+ * // xor bit 5: overflow
+ * if ((inc ^ orig ^ res) & 0b00100000)
+ * inc += 0b00100000;
+ * }
+ * if (!inc)
+ * return;
+ *
+ * res = atomic_long_add_return(counter @ Level 1, inc);
+ * orig = res - inc;
+ * if (inc < 0) {
+ * inc = -(-inc & ~0b00111111); // Clear used bits
+ * // xor bit 6: underflow
+ * if ((inc ^ orig ^ res) & 0b01000000)
+ * inc -= 0b01000000;
+ * } else {
+ * inc &= ~0b00111111; // Clear used bits
+ * // xor bit 6: overflow
+ * if ((inc ^ orig ^ res) & 0b01000000)
+ * inc += 0b01000000;
+ * }
+ * if (!inc)
+ * return;
+ *
+ * res = atomic_long_add_return(counter @ Level 2, inc);
+ * orig = res - inc;
+ * if (inc < 0) {
+ * inc = -(-inc & ~0b01111111); // Clear used bits
+ * // xor bit 7: underflow
+ * if ((inc ^ orig ^ res) & 0b10000000)
+ * inc -= 0b10000000;
+ * } else {
+ * inc &= ~0b01111111; // Clear used bits
+ * // xor bit 7: overflow
+ * if ((inc ^ orig ^ res) & 0b10000000)
+ * inc += 0b10000000;
+ * }
+ * if (!inc)
+ * return;
+ *
+ * atomic_long_add(counter @ Level 3, inc);
+ */
+
+#include <linux/percpu_counter_tree.h>
+#include <linux/cpumask.h>
+#include <linux/atomic.h>
+#include <linux/export.h>
+#include <linux/percpu.h>
+#include <linux/errno.h>
+#include <linux/slab.h>
+#include <linux/math.h>
+
+#define MAX_NR_LEVELS 5
+
+/*
+ * The counter configuration is selected at boot time based on the
+ * hardware topology.
+ */
+struct counter_config {
+ unsigned int nr_items; /*
+ * nr_items is the number of items in the tree for levels 1
+ * up to and including the final level (approximate sum).
+ * It excludes the level 0 per-CPU counters.
+ */
+ unsigned char nr_levels; /*
+ * nr_levels is the number of hierarchical counter tree levels.
+ * It excludes the final level (approximate sum).
+ */
+ unsigned char n_arity_order[MAX_NR_LEVELS]; /*
+ * n-arity of tree nodes for each level from
+ * 0 to (nr_levels - 1).
+ */
+};
+
+static const struct counter_config per_nr_cpu_order_config[] = {
+ [0] = { .nr_items = 0, .nr_levels = 0, .n_arity_order = { 0 } },
+ [1] = { .nr_items = 1, .nr_levels = 1, .n_arity_order = { 1 } },
+ [2] = { .nr_items = 3, .nr_levels = 2, .n_arity_order = { 1, 1 } },
+ [3] = { .nr_items = 7, .nr_levels = 3, .n_arity_order = { 1, 1, 1 } },
+ [4] = { .nr_items = 7, .nr_levels = 3, .n_arity_order = { 2, 1, 1 } },
+ [5] = { .nr_items = 11, .nr_levels = 3, .n_arity_order = { 2, 2, 1 } },
+ [6] = { .nr_items = 21, .nr_levels = 3, .n_arity_order = { 2, 2, 2 } },
+ [7] = { .nr_items = 21, .nr_levels = 3, .n_arity_order = { 3, 2, 2 } },
+ [8] = { .nr_items = 37, .nr_levels = 3, .n_arity_order = { 3, 3, 2 } },
+ [9] = { .nr_items = 73, .nr_levels = 3, .n_arity_order = { 3, 3, 3 } },
+ [10] = { .nr_items = 149, .nr_levels = 4, .n_arity_order = { 3, 3, 2, 2 } },
+ [11] = { .nr_items = 293, .nr_levels = 4, .n_arity_order = { 3, 3, 3, 2 } },
+ [12] = { .nr_items = 585, .nr_levels = 4, .n_arity_order = { 3, 3, 3, 3 } },
+ [13] = { .nr_items = 1173, .nr_levels = 5, .n_arity_order = { 3, 3, 3, 2, 2 } },
+ [14] = { .nr_items = 2341, .nr_levels = 5, .n_arity_order = { 3, 3, 3, 3, 2 } },
+ [15] = { .nr_items = 4681, .nr_levels = 5, .n_arity_order = { 3, 3, 3, 3, 3 } },
+ [16] = { .nr_items = 4681, .nr_levels = 5, .n_arity_order = { 4, 3, 3, 3, 3 } },
+ [17] = { .nr_items = 8777, .nr_levels = 5, .n_arity_order = { 4, 4, 3, 3, 3 } },
+ [18] = { .nr_items = 17481, .nr_levels = 5, .n_arity_order = { 4, 4, 4, 3, 3 } },
+ [19] = { .nr_items = 34953, .nr_levels = 5, .n_arity_order = { 4, 4, 4, 4, 3 } },
+ [20] = { .nr_items = 69905, .nr_levels = 5, .n_arity_order = { 4, 4, 4, 4, 4 } },
+};
+
+static const struct counter_config *counter_config; /* Hierarchical counter configuration for the hardware topology. */
+static unsigned int nr_cpus_order; /* Order of nr_cpu_ids. */
+static unsigned long accuracy_multiplier; /* Calculate accuracy for a given batch size (multiplication factor). */
+
+static
+int __percpu_counter_tree_init(struct percpu_counter_tree *counter,
+ unsigned long batch_size, gfp_t gfp_flags,
+ unsigned long __percpu *level0,
+ struct percpu_counter_tree_level_item *items)
+{
+ /* Batch size must be greater than 1, and a power of 2. */
+ if (WARN_ON(batch_size <= 1 || (batch_size & (batch_size - 1))))
+ return -EINVAL;
+ counter->batch_size = batch_size;
+ counter->bias = 0;
+ counter->level0 = level0;
+ counter->items = items;
+ if (!nr_cpus_order) {
+ counter->approx_sum.i = per_cpu_ptr(counter->level0, 0);
+ counter->level0_bit_mask = 0;
+ } else {
+ counter->approx_sum.a = &counter->items[counter_config->nr_items - 1].count;
+ counter->level0_bit_mask = 1UL << get_count_order(batch_size);
+ }
+ /*
+ * Each tree item signed integer has a negative range which is
+ * one unit greater than the positive range.
+ */
+ counter->approx_accuracy_range.under = batch_size * accuracy_multiplier;
+ counter->approx_accuracy_range.over = (batch_size - 1) * accuracy_multiplier;
+ return 0;
+}
+
+/**
+ * percpu_counter_tree_init_many() - Initialize many per-CPU counter trees.
+ * @counters: An array of @nr_counters counters to initialize.
+ * Their memory is provided by the caller.
+ * @items: Pointer to memory area where to store tree items.
+ * This memory is provided by the caller.
+ * Its size needs to be at least @nr_counters * percpu_counter_tree_items_size().
+ * @nr_counters: The number of counter trees to initialize
+ * @batch_size: The batch size is the increment step at level 0 which triggers a
+ * carry propagation.
+ * The batch size is required to be greater than 1, and a power of 2.
+ * @gfp_flags: gfp flags to pass to the per-CPU allocator.
+ *
+ * Initialize many per-CPU counter trees using a single per-CPU
+ * allocator invocation for @nr_counters counters.
+ *
+ * Return:
+ * * %0: Success
+ * * %-EINVAL: - Invalid @batch_size argument
+ * * %-ENOMEM: - Out of memory
+ */
+int percpu_counter_tree_init_many(struct percpu_counter_tree *counters, struct percpu_counter_tree_level_item *items,
+ unsigned int nr_counters, unsigned long batch_size, gfp_t gfp_flags)
+{
+ void __percpu *level0, *level0_iter;
+ size_t counter_size = sizeof(*counters->level0),
+ items_size = percpu_counter_tree_items_size();
+ void *items_iter;
+ unsigned int i;
+ int ret;
+
+ memset(items, 0, items_size * nr_counters);
+ level0 = __alloc_percpu_gfp(nr_counters * counter_size,
+ __alignof__(*counters->level0), gfp_flags);
+ if (!level0)
+ return -ENOMEM;
+ level0_iter = level0;
+ items_iter = items;
+ for (i = 0; i < nr_counters; i++) {
+ ret = __percpu_counter_tree_init(&counters[i], batch_size, gfp_flags, level0_iter, items_iter);
+ if (ret)
+ goto free_level0;
+ level0_iter += counter_size;
+ items_iter += items_size;
+ }
+ return 0;
+
+free_level0:
+ free_percpu(level0);
+ return ret;
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_init_many);
+
+/**
+ * percpu_counter_tree_init() - Initialize one per-CPU counter tree.
+ * @counter: Counter to initialize.
+ * Its memory is provided by the caller.
+ * @items: Pointer to memory area where to store tree items.
+ * This memory is provided by the caller.
+ * Its size needs to be at least percpu_counter_tree_items_size().
+ * @batch_size: The batch size is the increment step at level 0 which triggers a
+ * carry propagation.
+ * The batch size is required to be greater than 1, and a power of 2.
+ * @gfp_flags: gfp flags to pass to the per-CPU allocator.
+ *
+ * Initialize one per-CPU counter tree.
+ *
+ * Return:
+ * * %0: Success
+ * * %-EINVAL: - Invalid @batch_size argument
+ * * %-ENOMEM: - Out of memory
+ */
+int percpu_counter_tree_init(struct percpu_counter_tree *counter, struct percpu_counter_tree_level_item *items,
+ unsigned long batch_size, gfp_t gfp_flags)
+{
+ return percpu_counter_tree_init_many(counter, items, 1, batch_size, gfp_flags);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_init);
+
+/**
+ * percpu_counter_tree_destroy_many() - Destroy many per-CPU counter trees.
+ * @counters: Array of counters trees to destroy.
+ * @nr_counters: The number of counter trees to destroy.
+ *
+ * Release internal resources allocated for @nr_counters per-CPU counter trees.
+ */
+
+void percpu_counter_tree_destroy_many(struct percpu_counter_tree *counters, unsigned int nr_counters)
+{
+ free_percpu(counters->level0);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_destroy_many);
+
+/**
+ * percpu_counter_tree_destroy() - Destroy one per-CPU counter tree.
+ * @counter: Counter to destroy.
+ *
+ * Release internal resources allocated for one per-CPU counter tree.
+ */
+void percpu_counter_tree_destroy(struct percpu_counter_tree *counter)
+{
+ return percpu_counter_tree_destroy_many(counter, 1);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_destroy);
+
+static
+long percpu_counter_tree_carry(long orig, long res, long inc, unsigned long bit_mask)
+{
+ if (inc < 0) {
+ inc = -(-inc & ~(bit_mask - 1));
+ /*
+ * xor bit_mask: underflow.
+ *
+ * If inc has bit set, decrement an additional bit if
+ * there is _no_ bit transition between orig and res.
+ * Else, inc has bit cleared, decrement an additional
+ * bit if there is a bit transition between orig and
+ * res.
+ */
+ if ((inc ^ orig ^ res) & bit_mask)
+ inc -= bit_mask;
+ } else {
+ inc &= ~(bit_mask - 1);
+ /*
+ * xor bit_mask: overflow.
+ *
+ * If inc has bit set, increment an additional bit if
+ * there is _no_ bit transition between orig and res.
+ * Else, inc has bit cleared, increment an additional
+ * bit if there is a bit transition between orig and
+ * res.
+ */
+ if ((inc ^ orig ^ res) & bit_mask)
+ inc += bit_mask;
+ }
+ return inc;
+}
+
+/*
+ * It does not matter through which path the carry propagates up the
+ * tree, therefore there is no need to disable preemption because the
+ * cpu number is only used to favor cache locality.
+ */
+static
+void percpu_counter_tree_add_slowpath(struct percpu_counter_tree *counter, long inc)
+{
+ unsigned int level_items, nr_levels = counter_config->nr_levels,
+ level, n_arity_order;
+ unsigned long bit_mask;
+ struct percpu_counter_tree_level_item *item = counter->items;
+ unsigned int cpu = raw_smp_processor_id();
+
+ WARN_ON_ONCE(!nr_cpus_order); /* Should never be called for 1 cpu. */
+
+ n_arity_order = counter_config->n_arity_order[0];
+ bit_mask = counter->level0_bit_mask << n_arity_order;
+ level_items = 1U << (nr_cpus_order - n_arity_order);
+
+ for (level = 1; level < nr_levels; level++) {
+ /*
+ * For the purpose of carry propagation, the
+ * intermediate level counters only need to keep track
+ * of the bits relevant for carry propagation. We
+ * therefore don't care about higher order bits.
+ * Note that this optimization is unwanted if the
+ * intended use is to track counters within intermediate
+ * levels of the topology.
+ */
+ if (abs(inc) & (bit_mask - 1)) {
+ atomic_long_t *count = &item[cpu & (level_items - 1)].count;
+ unsigned long orig, res;
+
+ res = atomic_long_add_return_relaxed(inc, count);
+ orig = res - inc;
+ inc = percpu_counter_tree_carry(orig, res, inc, bit_mask);
+ if (likely(!inc))
+ return;
+ }
+ item += level_items;
+ n_arity_order = counter_config->n_arity_order[level];
+ level_items >>= n_arity_order;
+ bit_mask <<= n_arity_order;
+ }
+ atomic_long_add(inc, counter->approx_sum.a);
+}
+
+/**
+ * percpu_counter_tree_add() - Add to a per-CPU counter tree.
+ * @counter: Counter added to.
+ * @inc: Increment value (either positive or negative).
+ *
+ * Add @inc to a per-CPU counter tree. This is a fast-path which will
+ * typically increment per-CPU counters as long as there is no carry
+ * greater or equal to the counter tree batch size.
+ */
+void percpu_counter_tree_add(struct percpu_counter_tree *counter, long inc)
+{
+ unsigned long bit_mask = counter->level0_bit_mask, orig, res;
+
+ res = this_cpu_add_return(*counter->level0, inc);
+ orig = res - inc;
+ inc = percpu_counter_tree_carry(orig, res, inc, bit_mask);
+ if (likely(!inc))
+ return;
+ percpu_counter_tree_add_slowpath(counter, inc);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_add);
+
+static
+long percpu_counter_tree_precise_sum_unbiased(struct percpu_counter_tree *counter)
+{
+ unsigned long sum = 0;
+ int cpu;
+
+ for_each_possible_cpu(cpu)
+ sum += *per_cpu_ptr(counter->level0, cpu);
+ return (long) sum;
+}
+
+/**
+ * percpu_counter_tree_precise_sum() - Return precise counter sum.
+ * @counter: The counter to sum.
+ *
+ * Querying the precise sum is relatively expensive because it needs to
+ * iterate over all CPUs.
+ * This is meant to be used when accuracy is preferred over speed.
+ *
+ * Return: The current precise counter sum.
+ */
+long percpu_counter_tree_precise_sum(struct percpu_counter_tree *counter)
+{
+ return percpu_counter_tree_precise_sum_unbiased(counter) + READ_ONCE(counter->bias);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_precise_sum);
+
+static
+int compare_delta(long delta, unsigned long accuracy_neg, unsigned long accuracy_pos)
+{
+ if (delta >= 0) {
+ if (delta <= accuracy_pos)
+ return 0;
+ else
+ return 1;
+ } else {
+ if (-delta <= accuracy_neg)
+ return 0;
+ else
+ return -1;
+ }
+}
+
+/**
+ * percpu_counter_tree_approximate_compare - Approximated comparison of two counter trees.
+ * @a: First counter to compare.
+ * @b: Second counter to compare.
+ *
+ * Evaluate an approximate comparison of two counter trees.
+ * This approximation comparison is fast, and provides an accurate
+ * answer if the counters are found to be either less than or greater
+ * than the other. However, if the approximated comparison returns
+ * 0, the counters respective sums are found to be within the two
+ * counters accuracy range.
+ *
+ * Return:
+ * * %0 - Counters @a and @b do not differ by more than the sum of their respective
+ * accuracy ranges.
+ * * %-1 - Counter @a less than counter @b.
+ * * %1 - Counter @a is greater than counter @b.
+ */
+int percpu_counter_tree_approximate_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)
+{
+ return compare_delta(percpu_counter_tree_approximate_sum(a) - percpu_counter_tree_approximate_sum(b),
+ a->approx_accuracy_range.over + b->approx_accuracy_range.under,
+ a->approx_accuracy_range.under + b->approx_accuracy_range.over);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_approximate_compare);
+
+/**
+ * percpu_counter_tree_approximate_compare_value - Approximated comparison of a counter tree against a given value.
+ * @counter: Counter to compare.
+ * @v: Value to compare.
+ *
+ * Evaluate an approximate comparison of a counter tree against a given value.
+ * This approximation comparison is fast, and provides an accurate
+ * answer if the counter is found to be either less than or greater
+ * than the value. However, if the approximated comparison returns
+ * 0, the value is within the counter accuracy range.
+ *
+ * Return:
+ * * %0 - The value @v is within the accuracy range of the counter.
+ * * %-1 - The value @v is less than the counter.
+ * * %1 - The value @v is greater than the counter.
+ */
+int percpu_counter_tree_approximate_compare_value(struct percpu_counter_tree *counter, long v)
+{
+ return compare_delta(v - percpu_counter_tree_approximate_sum(counter),
+ counter->approx_accuracy_range.under,
+ counter->approx_accuracy_range.over);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_approximate_compare_value);
+
+/**
+ * percpu_counter_tree_precise_compare - Precise comparison of two counter trees.
+ * @a: First counter to compare.
+ * @b: Second counter to compare.
+ *
+ * Evaluate a precise comparison of two counter trees.
+ * As an optimization, it uses the approximate counter comparison
+ * to quickly compare counters which are far apart. Only cases where
+ * counter sums are within the accuracy range require precise counter
+ * sums.
+ *
+ * Return:
+ * * %0 - Counters are equal.
+ * * %-1 - Counter @a less than counter @b.
+ * * %1 - Counter @a is greater than counter @b.
+ */
+int percpu_counter_tree_precise_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)
+{
+ long count_a = percpu_counter_tree_approximate_sum(a),
+ count_b = percpu_counter_tree_approximate_sum(b);
+ unsigned long accuracy_a, accuracy_b;
+ long delta = count_a - count_b;
+ int res;
+
+ res = compare_delta(delta,
+ a->approx_accuracy_range.over + b->approx_accuracy_range.under,
+ a->approx_accuracy_range.under + b->approx_accuracy_range.over);
+ /* The values are distanced enough for an accurate approximated comparison. */
+ if (res)
+ return res;
+
+ /*
+ * The approximated comparison is within the accuracy range, therefore at least one
+ * precise sum is needed. Sum the counter which has the largest accuracy first.
+ */
+ if (delta >= 0) {
+ accuracy_a = a->approx_accuracy_range.under;
+ accuracy_b = b->approx_accuracy_range.over;
+ } else {
+ accuracy_a = a->approx_accuracy_range.over;
+ accuracy_b = b->approx_accuracy_range.under;
+ }
+ if (accuracy_b < accuracy_a) {
+ count_a = percpu_counter_tree_precise_sum(a);
+ res = compare_delta(count_a - count_b,
+ b->approx_accuracy_range.under,
+ b->approx_accuracy_range.over);
+ if (res)
+ return res;
+ /* Precise sum of second counter is required. */
+ count_b = percpu_counter_tree_precise_sum(b);
+ } else {
+ count_b = percpu_counter_tree_precise_sum(b);
+ res = compare_delta(count_a - count_b,
+ a->approx_accuracy_range.over,
+ a->approx_accuracy_range.under);
+ if (res)
+ return res;
+ /* Precise sum of second counter is required. */
+ count_a = percpu_counter_tree_precise_sum(a);
+ }
+ if (count_a - count_b < 0)
+ return -1;
+ if (count_a - count_b > 0)
+ return 1;
+ return 0;
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_precise_compare);
+
+/**
+ * percpu_counter_tree_precise_compare_value - Precise comparison of a counter tree against a given value.
+ * @counter: Counter to compare.
+ * @v: Value to compare.
+ *
+ * Evaluate a precise comparison of a counter tree against a given value.
+ * As an optimization, it uses the approximate counter comparison
+ * to quickly identify whether the counter and value are far apart.
+ * Only cases where the value is within the counter accuracy range
+ * require a precise counter sum.
+ *
+ * Return:
+ * * %0 - The value @v is equal to the counter.
+ * * %-1 - The value @v is less than the counter.
+ * * %1 - The value @v is greater than the counter.
+ */
+int percpu_counter_tree_precise_compare_value(struct percpu_counter_tree *counter, long v)
+{
+ long count = percpu_counter_tree_approximate_sum(counter);
+ int res;
+
+ res = compare_delta(v - count,
+ counter->approx_accuracy_range.under,
+ counter->approx_accuracy_range.over);
+ /* The values are distanced enough for an accurate approximated comparison. */
+ if (res)
+ return res;
+
+ /* Precise sum is required. */
+ count = percpu_counter_tree_precise_sum(counter);
+ if (v - count < 0)
+ return -1;
+ if (v - count > 0)
+ return 1;
+ return 0;
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_precise_compare_value);
+
+static
+void percpu_counter_tree_set_bias(struct percpu_counter_tree *counter, long bias)
+{
+ WRITE_ONCE(counter->bias, bias);
+}
+
+/**
+ * percpu_counter_tree_set - Set the counter tree sum to a given value.
+ * @counter: Counter to set.
+ * @v: Value to set.
+ *
+ * Set the counter sum to a given value. It can be useful for instance
+ * to reset the counter sum to 0. Note that even after setting the
+ * counter sum to a given value, the counter sum approximation can
+ * return any value within the accuracy range around that value.
+ */
+void percpu_counter_tree_set(struct percpu_counter_tree *counter, long v)
+{
+ percpu_counter_tree_set_bias(counter,
+ v - percpu_counter_tree_precise_sum_unbiased(counter));
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_set);
+
+/*
+ * percpu_counter_tree_items_size - Query the size required for counter tree items.
+ *
+ * Query the size of the memory area required to hold the counter tree
+ * items. This depends on the hardware topology and is invariant after
+ * boot.
+ *
+ * Return: Size required to hold tree items.
+ */
+size_t percpu_counter_tree_items_size(void)
+{
+ if (!nr_cpus_order)
+ return 0;
+ return counter_config->nr_items * sizeof(struct percpu_counter_tree_level_item);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_items_size);
+
+static void __init calculate_accuracy_topology(void)
+{
+ unsigned int nr_levels = counter_config->nr_levels, level;
+ unsigned int level_items = 1U << nr_cpus_order;
+ unsigned long batch_size = 1;
+
+ for (level = 0; level < nr_levels; level++) {
+ unsigned int n_arity_order = counter_config->n_arity_order[level];
+
+ /*
+ * The accuracy multiplier is derived from a batch size of 1
+ * to speed up calculating the accuracy at tree initialization.
+ */
+ accuracy_multiplier += batch_size * level_items;
+ batch_size <<= n_arity_order;
+ level_items >>= n_arity_order;
+ }
+}
+
+int __init percpu_counter_tree_subsystem_init(void)
+{
+ nr_cpus_order = get_count_order(nr_cpu_ids);
+ if (WARN_ON_ONCE(nr_cpus_order >= ARRAY_SIZE(per_nr_cpu_order_config))) {
+ printk(KERN_ERR "Unsupported number of CPUs (%u)\n", nr_cpu_ids);
+ return -1;
+ }
+ counter_config = &per_nr_cpu_order_config[nr_cpus_order];
+ calculate_accuracy_topology();
+ return 0;
+}
--
2.39.5 | {
"author": "Mathieu Desnoyers <mathieu.desnoyers@efficios.com>",
"date": "Fri, 27 Feb 2026 10:37:28 -0500",
"is_openbsd": false,
"thread_id": "20260227153730.1556542-4-mathieu.desnoyers@efficios.com.mbox.gz"
} |
lkml_critique | lkml | Conversion from user_hz to jiffies broke with
commit 2dc164a48e6fd ("sysctl: Create converter functions with two new macros")
because the old overflow check in do_proc_dointvec_userhz_jiffies_conv()
to see if "*u_ptr" was too large got replaced by an unconditional:
+ if (USER_HZ < HZ)
+ return -EINVAL;
which will always be true on platforms with "USER_HZ < HZ".
We shouldn't need this extra check anyway, because clock_t_to_jiffies()
returns ULONG_MAX for the overflow case:
if (x >= ~0UL / (HZ / USER_HZ))
return ~0UL;
and proc_int_u2k_conv_uop() checks for "> INT_MAX" after conversion:
if (u > (ulong) INT_MAX)
return -EINVAL;
Fixes: 2dc164a48e6fd ("sysctl: Create converter functions with two new macros")
Reported-by: Colm Harrington <colm.harrington@oracle.com>
Signed-off-by: Gerd Rausch <gerd.rausch@oracle.com>
---
kernel/time/jiffies.c | 2 --
1 file changed, 2 deletions(-)
diff --git a/kernel/time/jiffies.c b/kernel/time/jiffies.c
index a5c7d15fce72..9daf8c5d9687 100644
--- a/kernel/time/jiffies.c
+++ b/kernel/time/jiffies.c
@@ -256,8 +256,6 @@ EXPORT_SYMBOL(proc_dointvec_jiffies);
int proc_dointvec_userhz_jiffies(const struct ctl_table *table, int dir,
void *buffer, size_t *lenp, loff_t *ppos)
{
- if (SYSCTL_USER_TO_KERN(dir) && USER_HZ < HZ)
- return -EINVAL;
return proc_dointvec_conv(table, dir, buffer, lenp, ppos,
do_proc_int_conv_userhz_jiffies);
}
--
2.39.3
| null | null | null | [PATCH 1/1] time/jiffies: Fix conversion breakage on systems where
USER_HZ < HZ | On Wed, Feb 25, 2026 at 03:37:49PM -0800, Gerd Rausch wrote:
The internal kernel conversion itself is unchanged, it is informing user
space about this conversion that broke. Right? In other words, you get
an error when you read a sysctl file instead of an incorrect converted
value.
This fix looks good. I'll put it in next to see if it breaks anything.
How did you see the bug? Was it trying to read a sysctl file?
Best
--
Joel Granados | {
"author": "Joel Granados <joel.granados@kernel.org>",
"date": "Fri, 27 Feb 2026 15:31:33 +0100",
"is_openbsd": false,
"thread_id": "png4vg76rrtjpk3k3es5knfrzelvjoebeeyaqii2lclxv5dcds@ujlxb4eg3lho.mbox.gz"
} |
lkml_critique | lkml | Conversion from user_hz to jiffies broke with
commit 2dc164a48e6fd ("sysctl: Create converter functions with two new macros")
because the old overflow check in do_proc_dointvec_userhz_jiffies_conv()
to see if "*u_ptr" was too large got replaced by an unconditional:
+ if (USER_HZ < HZ)
+ return -EINVAL;
which will always be true on platforms with "USER_HZ < HZ".
We shouldn't need this extra check anyway, because clock_t_to_jiffies()
returns ULONG_MAX for the overflow case:
if (x >= ~0UL / (HZ / USER_HZ))
return ~0UL;
and proc_int_u2k_conv_uop() checks for "> INT_MAX" after conversion:
if (u > (ulong) INT_MAX)
return -EINVAL;
Fixes: 2dc164a48e6fd ("sysctl: Create converter functions with two new macros")
Reported-by: Colm Harrington <colm.harrington@oracle.com>
Signed-off-by: Gerd Rausch <gerd.rausch@oracle.com>
---
kernel/time/jiffies.c | 2 --
1 file changed, 2 deletions(-)
diff --git a/kernel/time/jiffies.c b/kernel/time/jiffies.c
index a5c7d15fce72..9daf8c5d9687 100644
--- a/kernel/time/jiffies.c
+++ b/kernel/time/jiffies.c
@@ -256,8 +256,6 @@ EXPORT_SYMBOL(proc_dointvec_jiffies);
int proc_dointvec_userhz_jiffies(const struct ctl_table *table, int dir,
void *buffer, size_t *lenp, loff_t *ppos)
{
- if (SYSCTL_USER_TO_KERN(dir) && USER_HZ < HZ)
- return -EINVAL;
return proc_dointvec_conv(table, dir, buffer, lenp, ppos,
do_proc_int_conv_userhz_jiffies);
}
--
2.39.3
| null | null | null | [PATCH 1/1] time/jiffies: Fix conversion breakage on systems where
USER_HZ < HZ | On Wed, Feb 25, 2026 at 03:37:49PM -0800, Gerd Rausch wrote:
I changed the message of the patch a bit. You can take a look here [1]
Best
[1] https://git.kernel.org/pub/scm/linux/kernel/git/sysctl/sysctl.git/commit/?h=sysctl-next&id=a17a86da1c90b62866bf2f45560510f2f6f18503
--
Joel Granados | {
"author": "Joel Granados <joel.granados@kernel.org>",
"date": "Fri, 27 Feb 2026 16:03:44 +0100",
"is_openbsd": false,
"thread_id": "png4vg76rrtjpk3k3es5knfrzelvjoebeeyaqii2lclxv5dcds@ujlxb4eg3lho.mbox.gz"
} |
lkml_critique | lkml | I found the bash issue when running this new test on a SLE12-SP5. There
are still other issues that would need to be addressed, but with this
change, test-ftrace.sh can run on SLE12-SP5 withou issues.
Signed-off-by: Marcos Paulo de Souza <mpdesouza@suse.com>
---
Marcos Paulo de Souza (2):
selftests: livepatch: test-ftrace: livepatch a traced function
selftests: livepatch: functions.sh: Workaround heredoc on older bash
tools/testing/selftests/livepatch/functions.sh | 6 ++--
tools/testing/selftests/livepatch/test-ftrace.sh | 36 ++++++++++++++++++++++++
2 files changed, 38 insertions(+), 4 deletions(-)
---
base-commit: 6d6ad32e22f028c525d5df471c5522616e645a6b
change-id: 20260220-lp-test-trace-73b2f607960a
Best regards,
--
Marcos Paulo de Souza <mpdesouza@suse.com>
| null | null | null | [PATCH 0/2] kselftests: livepatch: One new test and one fix for
older bash | This is basically the inverse case of commit 474eecc882ae
("selftests: livepatch: test if ftrace can trace a livepatched function")
but ensuring that livepatch would work on a traced function.
Signed-off-by: Marcos Paulo de Souza <mpdesouza@suse.com>
---
tools/testing/selftests/livepatch/test-ftrace.sh | 36 ++++++++++++++++++++++++
1 file changed, 36 insertions(+)
diff --git a/tools/testing/selftests/livepatch/test-ftrace.sh b/tools/testing/selftests/livepatch/test-ftrace.sh
index 094176f1a46a..c6222cc037c5 100755
--- a/tools/testing/selftests/livepatch/test-ftrace.sh
+++ b/tools/testing/selftests/livepatch/test-ftrace.sh
@@ -95,4 +95,40 @@ livepatch: '$MOD_LIVEPATCH': completing unpatching transition
livepatch: '$MOD_LIVEPATCH': unpatching complete
% rmmod $MOD_LIVEPATCH"
+
+# - trace a function
+# - verify livepatch can load targgeting no the same traced function
+# - check if the livepatch is in effect
+# - reset trace and unload livepatch
+
+start_test "livepatch a traced function and check that the live patch remains in effect"
+
+FUNCTION_NAME="cmdline_proc_show"
+
+trace_function "$FUNCTION_NAME"
+load_lp $MOD_LIVEPATCH
+
+if [[ "$(cat /proc/cmdline)" == "$MOD_LIVEPATCH: this has been live patched" ]] ; then
+ log "livepatch: ok"
+fi
+
+check_traced_functions "$FUNCTION_NAME"
+
+disable_lp $MOD_LIVEPATCH
+unload_lp $MOD_LIVEPATCH
+
+check_result "% insmod test_modules/$MOD_LIVEPATCH.ko
+livepatch: enabling patch '$MOD_LIVEPATCH'
+livepatch: '$MOD_LIVEPATCH': initializing patching transition
+livepatch: '$MOD_LIVEPATCH': starting patching transition
+livepatch: '$MOD_LIVEPATCH': completing patching transition
+livepatch: '$MOD_LIVEPATCH': patching complete
+livepatch: ok
+% echo 0 > $SYSFS_KLP_DIR/$MOD_LIVEPATCH/enabled
+livepatch: '$MOD_LIVEPATCH': initializing unpatching transition
+livepatch: '$MOD_LIVEPATCH': starting unpatching transition
+livepatch: '$MOD_LIVEPATCH': completing unpatching transition
+livepatch: '$MOD_LIVEPATCH': unpatching complete
+% rmmod $MOD_LIVEPATCH"
+
exit 0
--
2.52.0 | {
"author": "Marcos Paulo de Souza <mpdesouza@suse.com>",
"date": "Fri, 20 Feb 2026 11:12:33 -0300",
"is_openbsd": false,
"thread_id": "42ab207746352197bc11fc9c2eafcb8663cd1362.camel@suse.com.mbox.gz"
} |
lkml_critique | lkml | I found the bash issue when running this new test on a SLE12-SP5. There
are still other issues that would need to be addressed, but with this
change, test-ftrace.sh can run on SLE12-SP5 withou issues.
Signed-off-by: Marcos Paulo de Souza <mpdesouza@suse.com>
---
Marcos Paulo de Souza (2):
selftests: livepatch: test-ftrace: livepatch a traced function
selftests: livepatch: functions.sh: Workaround heredoc on older bash
tools/testing/selftests/livepatch/functions.sh | 6 ++--
tools/testing/selftests/livepatch/test-ftrace.sh | 36 ++++++++++++++++++++++++
2 files changed, 38 insertions(+), 4 deletions(-)
---
base-commit: 6d6ad32e22f028c525d5df471c5522616e645a6b
change-id: 20260220-lp-test-trace-73b2f607960a
Best regards,
--
Marcos Paulo de Souza <mpdesouza@suse.com>
| null | null | null | [PATCH 0/2] kselftests: livepatch: One new test and one fix for
older bash | When running current selftests on older distributions like SLE12-SP5 that
contains an older bash trips over heredoc. Convert it to plain echo
calls, which ends up with the same result.
Signed-off-by: Marcos Paulo de Souza <mpdesouza@suse.com>
---
tools/testing/selftests/livepatch/functions.sh | 6 ++----
1 file changed, 2 insertions(+), 4 deletions(-)
diff --git a/tools/testing/selftests/livepatch/functions.sh b/tools/testing/selftests/livepatch/functions.sh
index 8ec0cb64ad94..45ed04c6296e 100644
--- a/tools/testing/selftests/livepatch/functions.sh
+++ b/tools/testing/selftests/livepatch/functions.sh
@@ -96,10 +96,8 @@ function pop_config() {
}
function set_dynamic_debug() {
- cat <<-EOF > "$SYSFS_DEBUG_DIR/dynamic_debug/control"
- file kernel/livepatch/* +p
- func klp_try_switch_task -p
- EOF
+ echo "file kernel/livepatch/* +p" > "$SYSFS_DEBUG_DIR/dynamic_debug/control"
+ echo "func klp_try_switch_task -p" > "$SYSFS_DEBUG_DIR/dynamic_debug/control"
}
function set_ftrace_enabled() {
--
2.52.0 | {
"author": "Marcos Paulo de Souza <mpdesouza@suse.com>",
"date": "Fri, 20 Feb 2026 11:12:34 -0300",
"is_openbsd": false,
"thread_id": "42ab207746352197bc11fc9c2eafcb8663cd1362.camel@suse.com.mbox.gz"
} |
lkml_critique | lkml | I found the bash issue when running this new test on a SLE12-SP5. There
are still other issues that would need to be addressed, but with this
change, test-ftrace.sh can run on SLE12-SP5 withou issues.
Signed-off-by: Marcos Paulo de Souza <mpdesouza@suse.com>
---
Marcos Paulo de Souza (2):
selftests: livepatch: test-ftrace: livepatch a traced function
selftests: livepatch: functions.sh: Workaround heredoc on older bash
tools/testing/selftests/livepatch/functions.sh | 6 ++--
tools/testing/selftests/livepatch/test-ftrace.sh | 36 ++++++++++++++++++++++++
2 files changed, 38 insertions(+), 4 deletions(-)
---
base-commit: 6d6ad32e22f028c525d5df471c5522616e645a6b
change-id: 20260220-lp-test-trace-73b2f607960a
Best regards,
--
Marcos Paulo de Souza <mpdesouza@suse.com>
| null | null | null | [PATCH 0/2] kselftests: livepatch: One new test and one fix for
older bash | On Fri, Feb 20, 2026 at 11:12:33AM -0300, Marcos Paulo de Souza wrote:
nitpick: s/targgeting no/targeting on/ ?
Otherwise LGTM,
Acked-by: Joe Lawrence <joe.lawrence@redhat.com>
--
Joe | {
"author": "Joe Lawrence <joe.lawrence@redhat.com>",
"date": "Mon, 23 Feb 2026 10:39:14 -0500",
"is_openbsd": false,
"thread_id": "42ab207746352197bc11fc9c2eafcb8663cd1362.camel@suse.com.mbox.gz"
} |
lkml_critique | lkml | I found the bash issue when running this new test on a SLE12-SP5. There
are still other issues that would need to be addressed, but with this
change, test-ftrace.sh can run on SLE12-SP5 withou issues.
Signed-off-by: Marcos Paulo de Souza <mpdesouza@suse.com>
---
Marcos Paulo de Souza (2):
selftests: livepatch: test-ftrace: livepatch a traced function
selftests: livepatch: functions.sh: Workaround heredoc on older bash
tools/testing/selftests/livepatch/functions.sh | 6 ++--
tools/testing/selftests/livepatch/test-ftrace.sh | 36 ++++++++++++++++++++++++
2 files changed, 38 insertions(+), 4 deletions(-)
---
base-commit: 6d6ad32e22f028c525d5df471c5522616e645a6b
change-id: 20260220-lp-test-trace-73b2f607960a
Best regards,
--
Marcos Paulo de Souza <mpdesouza@suse.com>
| null | null | null | [PATCH 0/2] kselftests: livepatch: One new test and one fix for
older bash | On Fri, Feb 20, 2026 at 11:12:34AM -0300, Marcos Paulo de Souza wrote:
Acked-by: Joe Lawrence <joe.lawrence@redhat.com>
Just curious, what's the bash/heredoc issue? All I could find via
google search was perhaps something to do with the temporary file
implementation under the hood.
--
Joe | {
"author": "Joe Lawrence <joe.lawrence@redhat.com>",
"date": "Mon, 23 Feb 2026 10:42:14 -0500",
"is_openbsd": false,
"thread_id": "42ab207746352197bc11fc9c2eafcb8663cd1362.camel@suse.com.mbox.gz"
} |
lkml_critique | lkml | I found the bash issue when running this new test on a SLE12-SP5. There
are still other issues that would need to be addressed, but with this
change, test-ftrace.sh can run on SLE12-SP5 withou issues.
Signed-off-by: Marcos Paulo de Souza <mpdesouza@suse.com>
---
Marcos Paulo de Souza (2):
selftests: livepatch: test-ftrace: livepatch a traced function
selftests: livepatch: functions.sh: Workaround heredoc on older bash
tools/testing/selftests/livepatch/functions.sh | 6 ++--
tools/testing/selftests/livepatch/test-ftrace.sh | 36 ++++++++++++++++++++++++
2 files changed, 38 insertions(+), 4 deletions(-)
---
base-commit: 6d6ad32e22f028c525d5df471c5522616e645a6b
change-id: 20260220-lp-test-trace-73b2f607960a
Best regards,
--
Marcos Paulo de Souza <mpdesouza@suse.com>
| null | null | null | [PATCH 0/2] kselftests: livepatch: One new test and one fix for
older bash | On Mon, 2026-02-23 at 10:42 -0500, Joe Lawrence wrote:
Thanks for the review Joe!
# ./test-ftrace.sh
cat: -: No such file or directory
TEST: livepatch interaction with ftrace_enabled sysctl ... ^CQEMU:
Terminated
Somehow it doesn't understand the heredoc, but maybe I'm wrong...
either way, the change has the same outcome, so I believe that it
wasn't bad if we could change the cat for two echoes :)
Either way, if Petr or you think that this should be left as it is,
it's fine by me as well, I was just testing the change with an older
rootfs/kernels. | {
"author": "Marcos Paulo de Souza <mpdesouza@suse.com>",
"date": "Mon, 23 Feb 2026 13:21:43 -0300",
"is_openbsd": false,
"thread_id": "42ab207746352197bc11fc9c2eafcb8663cd1362.camel@suse.com.mbox.gz"
} |
lkml_critique | lkml | I found the bash issue when running this new test on a SLE12-SP5. There
are still other issues that would need to be addressed, but with this
change, test-ftrace.sh can run on SLE12-SP5 withou issues.
Signed-off-by: Marcos Paulo de Souza <mpdesouza@suse.com>
---
Marcos Paulo de Souza (2):
selftests: livepatch: test-ftrace: livepatch a traced function
selftests: livepatch: functions.sh: Workaround heredoc on older bash
tools/testing/selftests/livepatch/functions.sh | 6 ++--
tools/testing/selftests/livepatch/test-ftrace.sh | 36 ++++++++++++++++++++++++
2 files changed, 38 insertions(+), 4 deletions(-)
---
base-commit: 6d6ad32e22f028c525d5df471c5522616e645a6b
change-id: 20260220-lp-test-trace-73b2f607960a
Best regards,
--
Marcos Paulo de Souza <mpdesouza@suse.com>
| null | null | null | [PATCH 0/2] kselftests: livepatch: One new test and one fix for
older bash | On Fri, 20 Feb 2026 11:12:34 -0300
Marcos Paulo de Souza <mpdesouza@suse.com> wrote:
Use printf so you can write both lines in one command.
David | {
"author": "David Laight <david.laight.linux@gmail.com>",
"date": "Mon, 23 Feb 2026 16:37:33 +0000",
"is_openbsd": false,
"thread_id": "42ab207746352197bc11fc9c2eafcb8663cd1362.camel@suse.com.mbox.gz"
} |
lkml_critique | lkml | I found the bash issue when running this new test on a SLE12-SP5. There
are still other issues that would need to be addressed, but with this
change, test-ftrace.sh can run on SLE12-SP5 withou issues.
Signed-off-by: Marcos Paulo de Souza <mpdesouza@suse.com>
---
Marcos Paulo de Souza (2):
selftests: livepatch: test-ftrace: livepatch a traced function
selftests: livepatch: functions.sh: Workaround heredoc on older bash
tools/testing/selftests/livepatch/functions.sh | 6 ++--
tools/testing/selftests/livepatch/test-ftrace.sh | 36 ++++++++++++++++++++++++
2 files changed, 38 insertions(+), 4 deletions(-)
---
base-commit: 6d6ad32e22f028c525d5df471c5522616e645a6b
change-id: 20260220-lp-test-trace-73b2f607960a
Best regards,
--
Marcos Paulo de Souza <mpdesouza@suse.com>
| null | null | null | [PATCH 0/2] kselftests: livepatch: One new test and one fix for
older bash | Hi,
On Fri, 20 Feb 2026, Marcos Paulo de Souza wrote:
with the typo fix that Joe mentioned
Acked-by: Miroslav Benes <mbenes@suse.cz>
M | {
"author": "Miroslav Benes <mbenes@suse.cz>",
"date": "Thu, 26 Feb 2026 13:14:23 +0100 (CET)",
"is_openbsd": false,
"thread_id": "42ab207746352197bc11fc9c2eafcb8663cd1362.camel@suse.com.mbox.gz"
} |
lkml_critique | lkml | I found the bash issue when running this new test on a SLE12-SP5. There
are still other issues that would need to be addressed, but with this
change, test-ftrace.sh can run on SLE12-SP5 withou issues.
Signed-off-by: Marcos Paulo de Souza <mpdesouza@suse.com>
---
Marcos Paulo de Souza (2):
selftests: livepatch: test-ftrace: livepatch a traced function
selftests: livepatch: functions.sh: Workaround heredoc on older bash
tools/testing/selftests/livepatch/functions.sh | 6 ++--
tools/testing/selftests/livepatch/test-ftrace.sh | 36 ++++++++++++++++++++++++
2 files changed, 38 insertions(+), 4 deletions(-)
---
base-commit: 6d6ad32e22f028c525d5df471c5522616e645a6b
change-id: 20260220-lp-test-trace-73b2f607960a
Best regards,
--
Marcos Paulo de Souza <mpdesouza@suse.com>
| null | null | null | [PATCH 0/2] kselftests: livepatch: One new test and one fix for
older bash | Hi,
On Mon, 23 Feb 2026, Marcos Paulo de Souza wrote:
I cannot reproduce it locally on SLE12-SP5. The patched test-ftrace.sh
runs smoothly without 2/2.
linux:~/linux/tools/testing/selftests/livepatch # ./test-ftrace.sh
TEST: livepatch interaction with ftrace_enabled sysctl ... ok
TEST: trace livepatched function and check that the live patch remains in effect ... ok
TEST: livepatch a traced function and check that the live patch remains in effect ... ok
GNU bash, version 4.3.48(1)-release (x86_64-suse-linux-gnu)
Does "set -x" in the script give you anything interesting?
Miroslav | {
"author": "Miroslav Benes <mbenes@suse.cz>",
"date": "Thu, 26 Feb 2026 13:40:07 +0100 (CET)",
"is_openbsd": false,
"thread_id": "42ab207746352197bc11fc9c2eafcb8663cd1362.camel@suse.com.mbox.gz"
} |
lkml_critique | lkml | I found the bash issue when running this new test on a SLE12-SP5. There
are still other issues that would need to be addressed, but with this
change, test-ftrace.sh can run on SLE12-SP5 withou issues.
Signed-off-by: Marcos Paulo de Souza <mpdesouza@suse.com>
---
Marcos Paulo de Souza (2):
selftests: livepatch: test-ftrace: livepatch a traced function
selftests: livepatch: functions.sh: Workaround heredoc on older bash
tools/testing/selftests/livepatch/functions.sh | 6 ++--
tools/testing/selftests/livepatch/test-ftrace.sh | 36 ++++++++++++++++++++++++
2 files changed, 38 insertions(+), 4 deletions(-)
---
base-commit: 6d6ad32e22f028c525d5df471c5522616e645a6b
change-id: 20260220-lp-test-trace-73b2f607960a
Best regards,
--
Marcos Paulo de Souza <mpdesouza@suse.com>
| null | null | null | [PATCH 0/2] kselftests: livepatch: One new test and one fix for
older bash | On Thu, 2026-02-26 at 13:40 +0100, Miroslav Benes wrote:
Nope:
boot_livepatch:/mnt/tools/testing/selftests/livepatch # ./test-trace.sh
+ cat
cat: -: No such file or directory
+ set_ftrace_enabled 1
+ local can_fail=0
Same version here:
GNU bash, version 4.3.48(1)-release (x86_64-suse-linux-gnu)
I'm using virtme-ng, so I'm not sure if this is related. At the same
time it works on SLE15-SP4, using the same virtme-ng, but with a
different bash:
GNU bash, version 4.4.23(1)-release (x86_64-suse-linux-gnu)
So I was blaming bash for this issue... | {
"author": "Marcos Paulo de Souza <mpdesouza@suse.com>",
"date": "Thu, 26 Feb 2026 11:34:28 -0300",
"is_openbsd": false,
"thread_id": "42ab207746352197bc11fc9c2eafcb8663cd1362.camel@suse.com.mbox.gz"
} |
lkml_critique | lkml | I found the bash issue when running this new test on a SLE12-SP5. There
are still other issues that would need to be addressed, but with this
change, test-ftrace.sh can run on SLE12-SP5 withou issues.
Signed-off-by: Marcos Paulo de Souza <mpdesouza@suse.com>
---
Marcos Paulo de Souza (2):
selftests: livepatch: test-ftrace: livepatch a traced function
selftests: livepatch: functions.sh: Workaround heredoc on older bash
tools/testing/selftests/livepatch/functions.sh | 6 ++--
tools/testing/selftests/livepatch/test-ftrace.sh | 36 ++++++++++++++++++++++++
2 files changed, 38 insertions(+), 4 deletions(-)
---
base-commit: 6d6ad32e22f028c525d5df471c5522616e645a6b
change-id: 20260220-lp-test-trace-73b2f607960a
Best regards,
--
Marcos Paulo de Souza <mpdesouza@suse.com>
| null | null | null | [PATCH 0/2] kselftests: livepatch: One new test and one fix for
older bash | On Thu, 2026-02-26 at 11:34 -0300, Marcos Paulo de Souza wrote:
This patch can be skipped. For the record, I discovered that it only
happens when vng is called using --rw, making it to fail on older bash
since it doesn't create overlays for /tmp. If the overlay is added the
issue is gone.
So, this patch can be skipped. Thanks Miroslav for testing! | {
"author": "Marcos Paulo de Souza <mpdesouza@suse.com>",
"date": "Fri, 27 Feb 2026 11:28:37 -0300",
"is_openbsd": false,
"thread_id": "42ab207746352197bc11fc9c2eafcb8663cd1362.camel@suse.com.mbox.gz"
} |
lkml_critique | lkml | Hi all,
There were various suggestions in the September 2025 thread "[TECH
TOPIC] vfio, iommufd: Enabling user space drivers to vend more
granular access to client processes" [0], and LPC discussions, around
improving the situation for multi-process userspace driver designs.
This RFC series implements some of these ideas.
Background: Multi-process USDs
==============================
The userspace driver scenario discussed in that thread involves a
primary process driving a PCIe function through VFIO/iommufd, which
manages the function-wide ownership/lifecycle. The function is
designed to provide multiple distinct programming interfaces (for
example, several independent MMIO register frames in one function),
and the primary process delegates control of these interfaces to
multiple independent client processes (which do the actual work).
This scenario clearly relies on a HW design that provides appropriate
isolation between the programming interfaces.
The two key needs are:
1. Mechanisms to safely delegate a subset of the device MMIO
resources to a client process without over-sharing wider access
(or influence over whole-device activities, such as reset).
2. Mechanisms to allow a client process to do its own iommufd
management w.r.t. its address space, in a way that's isolated
from DMA relating to other clients.
mmap() of VFIO DMABUFs
======================
First, this RFC addresses #1, implementing the proposals in [0] to add
mmap() support to the existing VFIO DMABUF exporter.
This enables a userspace driver to define DMABUF ranges corresponding
to sub-ranges of a BAR, and grant a given client (via a shared fd)
the capability to access (only) those sub-ranges. The VFIO device fds
would be kept private to the primary process. All the client can do
with that fd is map (or iomap via iommufd) that specific subset of
resources, and the impact of bugs/malice is contained.
(We'll follow up on #2 separately, as a related-but-distinct problem.
PASIDs are one way to achieve per-client isolation of DMA; another
could be sharing of a single IOVA space via 'constrained' iommufds.)
Revocation/reclaim
==================
That's useful as-is, but then the lifetime of access granted to a
client needs to be managed well. For example, a protocol between the
primary process and the client can indicate when the client is done,
and when it's safe to reuse the resources elsewhere.
Resources could be released cooperatively, but it's much more robust
to enable the driver to make the resources guaranteed-inaccessible
when it chooses, so that it can re-assign them to other uses in
future.
So, second, I've suggested a PoC/example mechanism for reclaiming
ranges shared with clients: a new DMABUF ioctl, DMA_BUF_IOCTL_REVOKE,
is routed to a DMABUF exporter callback. The VFIO DMABUF exporter's
implementation permanently revokes a DMABUF (notifying importers, and
zapping PTEs for any mappings). This makes the DMABUF defunct and any
client (or third party the client has shared the buffer onto!) cannot
be used to access the BAR ranges, whether via DMABUF import or mmap().
A primary driver process would do this operation when the client's
tenure ends to reclaim "loaned-out" MMIO interfaces, at which point
the interfaces could be safely re-used.
This ioctl is one of several possible approaches to achieve buffer
revocation, but I wanted to demonstrate something here as it's an
important part of the buffer lifecycle in this driver scenario. An
alternative implementation could be some VFIO-specific operation to
search for a DMABUF (by address?) and kill it, but if the server keeps
hold of the DMABUF fd that's already a clean way to locate it later.
BAR mapping access attributes
=============================
Third, inspired by Alex [Mastro] and Jason's comments in [0], and
Mahmoud's work in [1] with the goal of controlling CPU access
attributes for VFIO BAR mappings (e.g. WC) I noticed that once we can
mmap() VFIO DMABUFs representing BAR sub-spans, it's straightforward
to decorate them with access attributes for the VMA.
I've proposed reserving a field in struct
vfio_device_feature_dma_buf's flags to specify an attribute for its
ranges. Although that keeps the (UAPI) struct unchanged, it means all
ranges in a DMABUF share the same attribute. I feel a single
attribute-to-mmap() relation is logical/reasonable. An application
can also create multiple DMABUFs to describe any BAR layout and mix of
attributes.
Tests
=====
I've included an [RFC ONLY] userspace test program which I am _not_
proposing to merge, but am sharing for context. It illustrates &
tests various map/revoke cases, but doesn't use the existing VFIO
selftests and relies on a (tweaked) QEMU EDU function. I'm working on
integrating the scenarios into the existing VFIO selftests.
This code has been tested in mapping DMABUFs of single/multiple
ranges, aliasing mmap()s, aliasing ranges across DMABUFs, vm_pgoff >
0, revocation, shutdown/cleanup scenarios, and hugepage mappings seem
to work correctly. I've lightly tested WC mappings also (by observing
resulting PTEs as having the correct attributes...).
(The first two commits are a couple of tiny bugfixes which I can send
separately, should reviewers prefer.)
This series is based on v6.19 but I expect to rebase, at least onto
Leon's recent work [2] ("vfio: Wait for dma-buf invalidation to
complete").
What are people's thoughts? I'll respin to de-RFC and capture
comments, if we think this approach is appropriate.
Thanks,
Matt
References:
[0]: https://lore.kernel.org/linux-iommu/20250918214425.2677057-1-amastro@fb.com/
[1]: https://lore.kernel.org/all/20250804104012.87915-1-mngyadam@amazon.de/
[2]: https://lore.kernel.org/linux-iommu/20260205-nocturnal-poetic-chamois-f566ad@houat/T/#m310cd07011e3a1461b6fda45e3f9b886ba76571a
Matt Evans (7):
vfio/pci: Ensure VFIO barmap is set up before creating a DMABUF
vfio/pci: Clean up DMABUFs before disabling function
vfio/pci: Support mmap() of a DMABUF
dma-buf: uapi: Mechanism to revoke DMABUFs via ioctl()
vfio/pci: Permanently revoke a DMABUF on request
vfio/pci: Add mmap() attributes to DMABUF feature
[RFC ONLY] selftests: vfio: Add standalone vfio_dmabuf_mmap_test
drivers/dma-buf/dma-buf.c | 5 +
drivers/vfio/pci/vfio_pci_core.c | 4 +-
drivers/vfio/pci/vfio_pci_dmabuf.c | 300 ++++++-
include/linux/dma-buf.h | 22 +
include/uapi/linux/dma-buf.h | 1 +
include/uapi/linux/vfio.h | 12 +-
tools/testing/selftests/vfio/Makefile | 1 +
.../vfio/standalone/vfio_dmabuf_mmap_test.c | 822 ++++++++++++++++++
8 files changed, 1153 insertions(+), 14 deletions(-)
create mode 100644 tools/testing/selftests/vfio/standalone/vfio_dmabuf_mmap_test.c
--
2.47.3
| null | null | null | [RFC PATCH 0/7] vfio/pci: Add mmap() for DMABUFs | On device shutdown, make vfio_pci_core_close_device() call
vfio_pci_dma_buf_cleanup() before the function is disabled via
vfio_pci_core_disable(). This ensures that any access to DMABUFs is
revoked (and importers act on move_notify()) before the function's
BARs become inaccessible.
This fixes an issue where, if the function is disabled first, a tiny
window exists in which the function's MSE is cleared and yet BARs
could still be accessed via the DMABUF. Worse, the resources would
also be free/up for grabs by a different driver.
Fixes: 5d74781ebc86c ("vfio/pci: Add dma-buf export support for MMIO regions")
Signed-off-by: Matt Evans <mattev@meta.com>
---
drivers/vfio/pci/vfio_pci_core.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/drivers/vfio/pci/vfio_pci_core.c b/drivers/vfio/pci/vfio_pci_core.c
index 3a11e6f450f7..8d0e3605fbc7 100644
--- a/drivers/vfio/pci/vfio_pci_core.c
+++ b/drivers/vfio/pci/vfio_pci_core.c
@@ -726,10 +726,10 @@ void vfio_pci_core_close_device(struct vfio_device *core_vdev)
#if IS_ENABLED(CONFIG_EEH)
eeh_dev_release(vdev->pdev);
#endif
- vfio_pci_core_disable(vdev);
-
vfio_pci_dma_buf_cleanup(vdev);
+ vfio_pci_core_disable(vdev);
+
mutex_lock(&vdev->igate);
vfio_pci_eventfd_replace_locked(vdev, &vdev->err_trigger, NULL);
vfio_pci_eventfd_replace_locked(vdev, &vdev->req_trigger, NULL);
--
2.47.3 | {
"author": "Matt Evans <mattev@meta.com>",
"date": "Thu, 26 Feb 2026 12:21:58 -0800",
"is_openbsd": false,
"thread_id": "a006b938-cd53-4c56-8131-30f557919ec6@amd.com.mbox.gz"
} |
lkml_critique | lkml | Hi all,
There were various suggestions in the September 2025 thread "[TECH
TOPIC] vfio, iommufd: Enabling user space drivers to vend more
granular access to client processes" [0], and LPC discussions, around
improving the situation for multi-process userspace driver designs.
This RFC series implements some of these ideas.
Background: Multi-process USDs
==============================
The userspace driver scenario discussed in that thread involves a
primary process driving a PCIe function through VFIO/iommufd, which
manages the function-wide ownership/lifecycle. The function is
designed to provide multiple distinct programming interfaces (for
example, several independent MMIO register frames in one function),
and the primary process delegates control of these interfaces to
multiple independent client processes (which do the actual work).
This scenario clearly relies on a HW design that provides appropriate
isolation between the programming interfaces.
The two key needs are:
1. Mechanisms to safely delegate a subset of the device MMIO
resources to a client process without over-sharing wider access
(or influence over whole-device activities, such as reset).
2. Mechanisms to allow a client process to do its own iommufd
management w.r.t. its address space, in a way that's isolated
from DMA relating to other clients.
mmap() of VFIO DMABUFs
======================
First, this RFC addresses #1, implementing the proposals in [0] to add
mmap() support to the existing VFIO DMABUF exporter.
This enables a userspace driver to define DMABUF ranges corresponding
to sub-ranges of a BAR, and grant a given client (via a shared fd)
the capability to access (only) those sub-ranges. The VFIO device fds
would be kept private to the primary process. All the client can do
with that fd is map (or iomap via iommufd) that specific subset of
resources, and the impact of bugs/malice is contained.
(We'll follow up on #2 separately, as a related-but-distinct problem.
PASIDs are one way to achieve per-client isolation of DMA; another
could be sharing of a single IOVA space via 'constrained' iommufds.)
Revocation/reclaim
==================
That's useful as-is, but then the lifetime of access granted to a
client needs to be managed well. For example, a protocol between the
primary process and the client can indicate when the client is done,
and when it's safe to reuse the resources elsewhere.
Resources could be released cooperatively, but it's much more robust
to enable the driver to make the resources guaranteed-inaccessible
when it chooses, so that it can re-assign them to other uses in
future.
So, second, I've suggested a PoC/example mechanism for reclaiming
ranges shared with clients: a new DMABUF ioctl, DMA_BUF_IOCTL_REVOKE,
is routed to a DMABUF exporter callback. The VFIO DMABUF exporter's
implementation permanently revokes a DMABUF (notifying importers, and
zapping PTEs for any mappings). This makes the DMABUF defunct and any
client (or third party the client has shared the buffer onto!) cannot
be used to access the BAR ranges, whether via DMABUF import or mmap().
A primary driver process would do this operation when the client's
tenure ends to reclaim "loaned-out" MMIO interfaces, at which point
the interfaces could be safely re-used.
This ioctl is one of several possible approaches to achieve buffer
revocation, but I wanted to demonstrate something here as it's an
important part of the buffer lifecycle in this driver scenario. An
alternative implementation could be some VFIO-specific operation to
search for a DMABUF (by address?) and kill it, but if the server keeps
hold of the DMABUF fd that's already a clean way to locate it later.
BAR mapping access attributes
=============================
Third, inspired by Alex [Mastro] and Jason's comments in [0], and
Mahmoud's work in [1] with the goal of controlling CPU access
attributes for VFIO BAR mappings (e.g. WC) I noticed that once we can
mmap() VFIO DMABUFs representing BAR sub-spans, it's straightforward
to decorate them with access attributes for the VMA.
I've proposed reserving a field in struct
vfio_device_feature_dma_buf's flags to specify an attribute for its
ranges. Although that keeps the (UAPI) struct unchanged, it means all
ranges in a DMABUF share the same attribute. I feel a single
attribute-to-mmap() relation is logical/reasonable. An application
can also create multiple DMABUFs to describe any BAR layout and mix of
attributes.
Tests
=====
I've included an [RFC ONLY] userspace test program which I am _not_
proposing to merge, but am sharing for context. It illustrates &
tests various map/revoke cases, but doesn't use the existing VFIO
selftests and relies on a (tweaked) QEMU EDU function. I'm working on
integrating the scenarios into the existing VFIO selftests.
This code has been tested in mapping DMABUFs of single/multiple
ranges, aliasing mmap()s, aliasing ranges across DMABUFs, vm_pgoff >
0, revocation, shutdown/cleanup scenarios, and hugepage mappings seem
to work correctly. I've lightly tested WC mappings also (by observing
resulting PTEs as having the correct attributes...).
(The first two commits are a couple of tiny bugfixes which I can send
separately, should reviewers prefer.)
This series is based on v6.19 but I expect to rebase, at least onto
Leon's recent work [2] ("vfio: Wait for dma-buf invalidation to
complete").
What are people's thoughts? I'll respin to de-RFC and capture
comments, if we think this approach is appropriate.
Thanks,
Matt
References:
[0]: https://lore.kernel.org/linux-iommu/20250918214425.2677057-1-amastro@fb.com/
[1]: https://lore.kernel.org/all/20250804104012.87915-1-mngyadam@amazon.de/
[2]: https://lore.kernel.org/linux-iommu/20260205-nocturnal-poetic-chamois-f566ad@houat/T/#m310cd07011e3a1461b6fda45e3f9b886ba76571a
Matt Evans (7):
vfio/pci: Ensure VFIO barmap is set up before creating a DMABUF
vfio/pci: Clean up DMABUFs before disabling function
vfio/pci: Support mmap() of a DMABUF
dma-buf: uapi: Mechanism to revoke DMABUFs via ioctl()
vfio/pci: Permanently revoke a DMABUF on request
vfio/pci: Add mmap() attributes to DMABUF feature
[RFC ONLY] selftests: vfio: Add standalone vfio_dmabuf_mmap_test
drivers/dma-buf/dma-buf.c | 5 +
drivers/vfio/pci/vfio_pci_core.c | 4 +-
drivers/vfio/pci/vfio_pci_dmabuf.c | 300 ++++++-
include/linux/dma-buf.h | 22 +
include/uapi/linux/dma-buf.h | 1 +
include/uapi/linux/vfio.h | 12 +-
tools/testing/selftests/vfio/Makefile | 1 +
.../vfio/standalone/vfio_dmabuf_mmap_test.c | 822 ++++++++++++++++++
8 files changed, 1153 insertions(+), 14 deletions(-)
create mode 100644 tools/testing/selftests/vfio/standalone/vfio_dmabuf_mmap_test.c
--
2.47.3
| null | null | null | [RFC PATCH 0/7] vfio/pci: Add mmap() for DMABUFs | A DMABUF exports access to BAR resources which need to be requested
before the DMABUF is handed out. Usually the resources are requested
when setting up the barmap when the VFIO device fd is mmap()ed, but
there's no guarantee that happens before a DMABUF is created.
Set up the barmap (and so request resources) in the DMABUF-creation
path.
Fixes: 5d74781ebc86c ("vfio/pci: Add dma-buf export support for MMIO regions")
Signed-off-by: Matt Evans <mattev@meta.com>
---
drivers/vfio/pci/vfio_pci_dmabuf.c | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/drivers/vfio/pci/vfio_pci_dmabuf.c b/drivers/vfio/pci/vfio_pci_dmabuf.c
index 4be4a85005cb..46ab64fbeb19 100644
--- a/drivers/vfio/pci/vfio_pci_dmabuf.c
+++ b/drivers/vfio/pci/vfio_pci_dmabuf.c
@@ -258,6 +258,17 @@ int vfio_pci_core_feature_dma_buf(struct vfio_pci_core_device *vdev, u32 flags,
goto err_free_priv;
}
+ /*
+ * Just like the vfio_pci_core_mmap() path, we need to ensure
+ * PCI regions have been requested before returning DMABUFs
+ * that reference them. It's possible to create a DMABUF for
+ * a BAR without the BAR having already been mmap()ed. The
+ * barmap setup requests the regions for us:
+ */
+ ret = vfio_pci_core_setup_barmap(vdev, get_dma_buf.region_index);
+ if (ret)
+ goto err_free_phys;
+
priv->vdev = vdev;
priv->nr_ranges = get_dma_buf.nr_ranges;
priv->size = length;
--
2.47.3 | {
"author": "Matt Evans <mattev@meta.com>",
"date": "Thu, 26 Feb 2026 12:21:57 -0800",
"is_openbsd": false,
"thread_id": "a006b938-cd53-4c56-8131-30f557919ec6@amd.com.mbox.gz"
} |
lkml_critique | lkml | Hi all,
There were various suggestions in the September 2025 thread "[TECH
TOPIC] vfio, iommufd: Enabling user space drivers to vend more
granular access to client processes" [0], and LPC discussions, around
improving the situation for multi-process userspace driver designs.
This RFC series implements some of these ideas.
Background: Multi-process USDs
==============================
The userspace driver scenario discussed in that thread involves a
primary process driving a PCIe function through VFIO/iommufd, which
manages the function-wide ownership/lifecycle. The function is
designed to provide multiple distinct programming interfaces (for
example, several independent MMIO register frames in one function),
and the primary process delegates control of these interfaces to
multiple independent client processes (which do the actual work).
This scenario clearly relies on a HW design that provides appropriate
isolation between the programming interfaces.
The two key needs are:
1. Mechanisms to safely delegate a subset of the device MMIO
resources to a client process without over-sharing wider access
(or influence over whole-device activities, such as reset).
2. Mechanisms to allow a client process to do its own iommufd
management w.r.t. its address space, in a way that's isolated
from DMA relating to other clients.
mmap() of VFIO DMABUFs
======================
First, this RFC addresses #1, implementing the proposals in [0] to add
mmap() support to the existing VFIO DMABUF exporter.
This enables a userspace driver to define DMABUF ranges corresponding
to sub-ranges of a BAR, and grant a given client (via a shared fd)
the capability to access (only) those sub-ranges. The VFIO device fds
would be kept private to the primary process. All the client can do
with that fd is map (or iomap via iommufd) that specific subset of
resources, and the impact of bugs/malice is contained.
(We'll follow up on #2 separately, as a related-but-distinct problem.
PASIDs are one way to achieve per-client isolation of DMA; another
could be sharing of a single IOVA space via 'constrained' iommufds.)
Revocation/reclaim
==================
That's useful as-is, but then the lifetime of access granted to a
client needs to be managed well. For example, a protocol between the
primary process and the client can indicate when the client is done,
and when it's safe to reuse the resources elsewhere.
Resources could be released cooperatively, but it's much more robust
to enable the driver to make the resources guaranteed-inaccessible
when it chooses, so that it can re-assign them to other uses in
future.
So, second, I've suggested a PoC/example mechanism for reclaiming
ranges shared with clients: a new DMABUF ioctl, DMA_BUF_IOCTL_REVOKE,
is routed to a DMABUF exporter callback. The VFIO DMABUF exporter's
implementation permanently revokes a DMABUF (notifying importers, and
zapping PTEs for any mappings). This makes the DMABUF defunct and any
client (or third party the client has shared the buffer onto!) cannot
be used to access the BAR ranges, whether via DMABUF import or mmap().
A primary driver process would do this operation when the client's
tenure ends to reclaim "loaned-out" MMIO interfaces, at which point
the interfaces could be safely re-used.
This ioctl is one of several possible approaches to achieve buffer
revocation, but I wanted to demonstrate something here as it's an
important part of the buffer lifecycle in this driver scenario. An
alternative implementation could be some VFIO-specific operation to
search for a DMABUF (by address?) and kill it, but if the server keeps
hold of the DMABUF fd that's already a clean way to locate it later.
BAR mapping access attributes
=============================
Third, inspired by Alex [Mastro] and Jason's comments in [0], and
Mahmoud's work in [1] with the goal of controlling CPU access
attributes for VFIO BAR mappings (e.g. WC) I noticed that once we can
mmap() VFIO DMABUFs representing BAR sub-spans, it's straightforward
to decorate them with access attributes for the VMA.
I've proposed reserving a field in struct
vfio_device_feature_dma_buf's flags to specify an attribute for its
ranges. Although that keeps the (UAPI) struct unchanged, it means all
ranges in a DMABUF share the same attribute. I feel a single
attribute-to-mmap() relation is logical/reasonable. An application
can also create multiple DMABUFs to describe any BAR layout and mix of
attributes.
Tests
=====
I've included an [RFC ONLY] userspace test program which I am _not_
proposing to merge, but am sharing for context. It illustrates &
tests various map/revoke cases, but doesn't use the existing VFIO
selftests and relies on a (tweaked) QEMU EDU function. I'm working on
integrating the scenarios into the existing VFIO selftests.
This code has been tested in mapping DMABUFs of single/multiple
ranges, aliasing mmap()s, aliasing ranges across DMABUFs, vm_pgoff >
0, revocation, shutdown/cleanup scenarios, and hugepage mappings seem
to work correctly. I've lightly tested WC mappings also (by observing
resulting PTEs as having the correct attributes...).
(The first two commits are a couple of tiny bugfixes which I can send
separately, should reviewers prefer.)
This series is based on v6.19 but I expect to rebase, at least onto
Leon's recent work [2] ("vfio: Wait for dma-buf invalidation to
complete").
What are people's thoughts? I'll respin to de-RFC and capture
comments, if we think this approach is appropriate.
Thanks,
Matt
References:
[0]: https://lore.kernel.org/linux-iommu/20250918214425.2677057-1-amastro@fb.com/
[1]: https://lore.kernel.org/all/20250804104012.87915-1-mngyadam@amazon.de/
[2]: https://lore.kernel.org/linux-iommu/20260205-nocturnal-poetic-chamois-f566ad@houat/T/#m310cd07011e3a1461b6fda45e3f9b886ba76571a
Matt Evans (7):
vfio/pci: Ensure VFIO barmap is set up before creating a DMABUF
vfio/pci: Clean up DMABUFs before disabling function
vfio/pci: Support mmap() of a DMABUF
dma-buf: uapi: Mechanism to revoke DMABUFs via ioctl()
vfio/pci: Permanently revoke a DMABUF on request
vfio/pci: Add mmap() attributes to DMABUF feature
[RFC ONLY] selftests: vfio: Add standalone vfio_dmabuf_mmap_test
drivers/dma-buf/dma-buf.c | 5 +
drivers/vfio/pci/vfio_pci_core.c | 4 +-
drivers/vfio/pci/vfio_pci_dmabuf.c | 300 ++++++-
include/linux/dma-buf.h | 22 +
include/uapi/linux/dma-buf.h | 1 +
include/uapi/linux/vfio.h | 12 +-
tools/testing/selftests/vfio/Makefile | 1 +
.../vfio/standalone/vfio_dmabuf_mmap_test.c | 822 ++++++++++++++++++
8 files changed, 1153 insertions(+), 14 deletions(-)
create mode 100644 tools/testing/selftests/vfio/standalone/vfio_dmabuf_mmap_test.c
--
2.47.3
| null | null | null | [RFC PATCH 0/7] vfio/pci: Add mmap() for DMABUFs | Expand the VFIO DMABUF revocation state to three states:
Not revoked, temporarily revoked, and permanently revoked.
The first two are for existing transient revocation, e.g. across a
function reset, and the DMABUF is put into the last in response to an
ioctl(DMA_BUF_IOCTL_REVOKE) request.
When triggered, dynamic imports are removed, PTEs zapped, and the
state changed such that no future mappings/imports are allowed.
This is useful to reclaim VFIO PCI BAR ranges previously delegated to
a subordinate process: The driver process can ensure that the loans
are closed down before repurposing exported ranges.
Signed-off-by: Matt Evans <mattev@meta.com>
---
drivers/vfio/pci/vfio_pci_dmabuf.c | 64 +++++++++++++++++++++++++-----
1 file changed, 53 insertions(+), 11 deletions(-)
diff --git a/drivers/vfio/pci/vfio_pci_dmabuf.c b/drivers/vfio/pci/vfio_pci_dmabuf.c
index bebb496bd0f2..af30ca205f31 100644
--- a/drivers/vfio/pci/vfio_pci_dmabuf.c
+++ b/drivers/vfio/pci/vfio_pci_dmabuf.c
@@ -9,6 +9,17 @@
MODULE_IMPORT_NS("DMA_BUF");
+enum vfio_pci_dma_buf_status {
+ /*
+ * A buffer can move freely between OK/accessible and revoked
+ * states (for example, a device reset will temporarily revoke
+ * it). It can also be permanently revoked.
+ */
+ VFIO_PCI_DMABUF_OK = 0,
+ VFIO_PCI_DMABUF_TEMP_REVOKED = 1,
+ VFIO_PCI_DMABUF_PERM_REVOKED = 2,
+};
+
struct vfio_pci_dma_buf {
struct dma_buf *dmabuf;
struct vfio_pci_core_device *vdev;
@@ -17,9 +28,11 @@ struct vfio_pci_dma_buf {
struct dma_buf_phys_vec *phys_vec;
struct p2pdma_provider *provider;
u32 nr_ranges;
- u8 revoked : 1;
+ enum vfio_pci_dma_buf_status status;
};
+static int vfio_pci_dma_buf_revoke(struct dma_buf *dmabuf);
+
static int vfio_pci_dma_buf_pin(struct dma_buf_attachment *attachment)
{
return -EOPNOTSUPP;
@@ -38,7 +51,7 @@ static int vfio_pci_dma_buf_attach(struct dma_buf *dmabuf,
if (!attachment->peer2peer)
return -EOPNOTSUPP;
- if (priv->revoked)
+ if (priv->status != VFIO_PCI_DMABUF_OK)
return -ENODEV;
return 0;
@@ -52,7 +65,7 @@ vfio_pci_dma_buf_map(struct dma_buf_attachment *attachment,
dma_resv_assert_held(priv->dmabuf->resv);
- if (priv->revoked)
+ if (priv->status != VFIO_PCI_DMABUF_OK)
return ERR_PTR(-ENODEV);
return dma_buf_phys_vec_to_sgt(attachment, priv->provider,
@@ -205,7 +218,7 @@ static vm_fault_t vfio_pci_dma_buf_mmap_huge_fault(struct vm_fault *vmf,
* revocation/unmap and status change occurs
* whilst holding memory_lock.
*/
- if (priv->revoked)
+ if (priv->status != VFIO_PCI_DMABUF_OK)
ret = VM_FAULT_SIGBUS;
else
ret = vfio_pci_vmf_insert_pfn(vdev, vmf, pfn, order);
@@ -246,7 +259,7 @@ static bool vfio_pci_dma_buf_is_mappable(struct dma_buf *dmabuf)
* on: for example, users should not be mmap()ing a buffer
* that's being moved [by a user-triggered activity].
*/
- if (priv->revoked)
+ if (priv->status != VFIO_PCI_DMABUF_OK)
return false;
return true;
@@ -296,6 +309,7 @@ static const struct dma_buf_ops vfio_pci_dmabuf_ops = {
.unmap_dma_buf = vfio_pci_dma_buf_unmap,
.release = vfio_pci_dma_buf_release,
.mmap = vfio_pci_dma_buf_mmap,
+ .revoke = vfio_pci_dma_buf_revoke,
};
/*
@@ -320,7 +334,7 @@ int vfio_pci_dma_buf_iommufd_map(struct dma_buf_attachment *attachment,
return -EOPNOTSUPP;
priv = attachment->dmabuf->priv;
- if (priv->revoked)
+ if (priv->status != VFIO_PCI_DMABUF_OK)
return -ENODEV;
/* More than one range to iommufd will require proper DMABUF support */
@@ -506,7 +520,8 @@ int vfio_pci_core_feature_dma_buf(struct vfio_pci_core_device *vdev, u32 flags,
INIT_LIST_HEAD(&priv->dmabufs_elm);
down_write(&vdev->memory_lock);
dma_resv_lock(priv->dmabuf->resv, NULL);
- priv->revoked = !__vfio_pci_memory_enabled(vdev);
+ priv->status = __vfio_pci_memory_enabled(vdev) ? VFIO_PCI_DMABUF_OK :
+ VFIO_PCI_DMABUF_TEMP_REVOKED;
list_add_tail(&priv->dmabufs_elm, &vdev->dmabufs);
dma_resv_unlock(priv->dmabuf->resv);
up_write(&vdev->memory_lock);
@@ -541,7 +556,7 @@ void vfio_pci_dma_buf_move(struct vfio_pci_core_device *vdev, bool revoked)
lockdep_assert_held_write(&vdev->memory_lock);
/*
* Holding memory_lock ensures a racing
- * vfio_pci_dma_buf_mmap_*_fault() observes priv->revoked
+ * vfio_pci_dma_buf_mmap_*_fault() observes priv->status
* properly.
*/
@@ -549,9 +564,11 @@ void vfio_pci_dma_buf_move(struct vfio_pci_core_device *vdev, bool revoked)
if (!get_file_active(&priv->dmabuf->file))
continue;
- if (priv->revoked != revoked) {
+ if ((priv->status == VFIO_PCI_DMABUF_OK && revoked) ||
+ (priv->status == VFIO_PCI_DMABUF_TEMP_REVOKED && !revoked)) {
dma_resv_lock(priv->dmabuf->resv, NULL);
- priv->revoked = revoked;
+ priv->status = revoked ? VFIO_PCI_DMABUF_TEMP_REVOKED :
+ VFIO_PCI_DMABUF_OK;
dma_buf_move_notify(priv->dmabuf);
dma_resv_unlock(priv->dmabuf->resv);
@@ -580,7 +597,7 @@ void vfio_pci_dma_buf_cleanup(struct vfio_pci_core_device *vdev)
dma_resv_lock(priv->dmabuf->resv, NULL);
list_del_init(&priv->dmabufs_elm);
priv->vdev = NULL;
- priv->revoked = true;
+ priv->status = VFIO_PCI_DMABUF_PERM_REVOKED;
dma_buf_move_notify(priv->dmabuf);
dma_resv_unlock(priv->dmabuf->resv);
unmap_mapping_range(priv->dmabuf->file->f_mapping,
@@ -590,3 +607,28 @@ void vfio_pci_dma_buf_cleanup(struct vfio_pci_core_device *vdev)
}
up_write(&vdev->memory_lock);
}
+
+static int vfio_pci_dma_buf_revoke(struct dma_buf *dmabuf)
+{
+ struct vfio_pci_dma_buf *priv = dmabuf->priv;
+ struct vfio_pci_core_device *vdev;
+
+ vdev = READ_ONCE(priv->vdev);
+
+ if (!vdev)
+ return -ENODEV;
+
+ scoped_guard(rwsem_read, &vdev->memory_lock) {
+ if (priv->status == VFIO_PCI_DMABUF_PERM_REVOKED)
+ return -EBADFD;
+
+ dma_resv_lock(priv->dmabuf->resv, NULL);
+ priv->status = VFIO_PCI_DMABUF_PERM_REVOKED;
+ dma_buf_move_notify(priv->dmabuf);
+ dma_resv_unlock(priv->dmabuf->resv);
+
+ unmap_mapping_range(priv->dmabuf->file->f_mapping,
+ 0, priv->size, 1);
+ }
+ return 0;
+}
--
2.47.3 | {
"author": "Matt Evans <mattev@meta.com>",
"date": "Thu, 26 Feb 2026 12:22:01 -0800",
"is_openbsd": false,
"thread_id": "a006b938-cd53-4c56-8131-30f557919ec6@amd.com.mbox.gz"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.