Skip to contentSkip to conversation

alloc_tag: introduce IOCTL-based filtering for MAP

PATCH Superseded Abhishek Bapat 4 participants 29 messages Jun 5 – Jun 9

Subsystems (7)

v3 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v3 cover alloc_tag: introduce IOCTL-based filtering for MAP

Currently, memory allocation profiling data is primarily exposed through /proc/allocinfo. While useful for manual inspection, this text-based interface poses challenges for production monitoring and large-scale analysis:

1. Userspace must parse large amounts of text to extract specific fields.
2. To find specific tags, userspace must read the entire dataset, requiring many context switches and high data copying.
3. The kernel currently aggregates per-CPU counters for every allocation size, even those the user intends to filter out immediately.

This series introduces a new IOCTL-based binary interface for allocinfo that supports kernel-side filtering. By allowing the user to specify a filter mask, we significantly reduce the work performed in-kernel and the amount of data transferred to userspace.

Performance measurements were conducted on an Intel Xeon Platinum 8481C (224 CPUs) with caches dropped before each run.

The IOCTL mechanism shows a ~20x performance improvement for filtered queries. The kernel avoids the expensive per-CPU counter aggregation (alloc_tag_read) for any tags that fail the initial string or location filters.

Scenario 1: Specific File Filtering (arch/x86/events/rapl.c)
1. Traditional (cat /proc/allocinfo | grep): 22ms (sys)
2. IOCTL Interface: 1ms (sys)

Scenario 2: Compound Filtering (Filename + Size)
1. Traditional: (cat ... | grep | awk): 21ms (sys)
2. IOCTL Interface: 1ms (sys)

Scenario 3: Size-Based Filtering (min_size = 1MB)
1. Traditional: (cat ... | awk): 21ms (sys)
2. IOCTL Interface: 14ms (sys)

v2 changes:
- Patch 1/6: Introduced locking for m->private. Also included the new uapi header file in MAINTAINERS list.
- Patch 2/6: Handled the case where ALLOCINFO_FILTER_MASK_MODNAME is passed but ct->modname is NULL.
- Patch 3/6: Moved min_size and max_size outside of struct allocinfo_tag into struct allocinfo_filter. Added validation that min_size <= max_size. Prefetched alloc_tag_counters if size based filter masks are provided to avoid assimilating per-cpu counters twice.
- Patch 5/6: Removed the hardcoded logic to skip the header, instead the test will skip lines that don't match the format. Also included the newly added alloc_tag selftests directory in MAINTAINERS list.

v3 changes:
- Patch 1/6: Modified Documentation to indicate that map supports ioctl(). Modified struct allocinfo_count to use
__attribute__((aligned(8))) instead of manual padding. Removed redundance type-casting. Added comments for static functions in lib/alloc_tag.c. Introduced a new seq counter for content_id that gets bumped every time module is loaded / unloaded. Introduced logic to validate user specified position is not greater than number of allocation tags and return early if it is. Changed strscpy to strscpy_pad to not echo arbitrary user data back to the user.
- Patch 2/6: Handled the case where user wants to specifically filter for built-in modules. Included some comments for static functions.
- Patch 3/6: Modified logic to only fetch per-CPU counters for codetags that satisfy other filters. Included some comments for static
functions.

Abhishek Bapat (5):
alloc_tag: add ioctl filters to /proc/allocinfo
alloc_tag: add size-based filtering to ioctl
alloc_tag: add accuracy based filtering to ioctl
kselftest: alloc_tag: add kselftest for ioctl interface
kselftest: alloc_tag: extend the allocinfo ioctl kselftest

Suren Baghdasaryan (1):
alloc_tag: add ioctl to /proc/allocinfo

 Documentation/mm/allocation-profiling.rst     |   5 +
 .../userspace-api/ioctl/ioctl-number.rst      |   2 +
 MAINTAINERS                                   |   2 +
 include/linux/codetag.h                       |   2 +
 include/uapi/linux/alloc_tag.h                |  87 +++
 lib/alloc_tag.c                               | 342 +++++++++++-
 lib/codetag.c                                 |  18 +
 tools/testing/selftests/alloc_tag/Makefile    |   9 +
 .../alloc_tag/allocinfo_ioctl_test.c          | 505 ++++++++++++++++++
 9 files changed, 970 insertions(+), 2 deletions(-)
 create mode 100644 include/uapi/linux/alloc_tag.h
 create mode 100644 tools/testing/selftests/alloc_tag/Makefile
 create mode 100644 tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
#1 lore raw

PATCH v3 1/6 alloc_tag: add ioctl to /proc/allocinfo

From: Suren Baghdasaryan <[email protected]>

Add the following ioctl commands for /proc/allocinfo file:

ALLOCINFO_IOC_CONTENT_ID - gets content identifier which can be used to check whether the file content has changed specifically due to module load/unload. Every time a module is loaded / unloaded, the returned value will be different. By comparing the identifier value at the beginning and at the end of the content retrieval operation, users can validate retrieved information for consistency.

ALLOCINFO_IOC_GET_AT - gets the record at the specified position. This is the position of a record in /proc/allocinfo.

ALLOCINFO_IOC_GET_NEXT - gets the record next to the last retrieved one. If no records were previously retrieved, returns the first record.

---
 Documentation/mm/allocation-profiling.rst     |   5 +
 .../userspace-api/ioctl/ioctl-number.rst      |   2 +
 MAINTAINERS                                   |   1 +
 include/linux/codetag.h                       |   2 +
 include/uapi/linux/alloc_tag.h                |  54 ++++
 lib/alloc_tag.c                               | 232 +++++++++++++++++-
 lib/codetag.c                                 |  18 ++
 7 files changed, 312 insertions(+), 2 deletions(-)
 create mode 100644 include/uapi/linux/alloc_tag.h
Documentation/mm/allocation-profiling.rst +5 -0
index 5389d241176a..c3a28467955f 100644
@@ -46,6 +46,11 @@ sysctl:
 Runtime info:
   /proc/allocinfo
 
+  Profiling data can be retrieved either by reading `/proc/allocinfo` directly as
+  text or programmatically via `ioctl()` calls defined in `<uapi/linux/alloc_tag.h>`.
+  The ioctl interface supports structured binary data extraction as well as filtering
+  by module name, function, file, line number, accuracy, or allocation size limits.
+
 Example output::
 
   root@moria-kvm:~# sort -g /proc/allocinfo|tail|numfmt --to=iec
Documentation/userspace-api/ioctl/ioctl-number.rst +2 -0
index 331223761fff..84f6808a8578 100644
@@ -349,6 +349,8 @@ Code  Seq#    Include File                                             Comments
                                                                        <mailto:[email protected]>
 0xA5  20-2F  linux/surface_aggregator/dtx.h                            Microsoft Surface DTX driver
                                                                        <mailto:[email protected]>
+0xA6  00-0F  uapi/linux/alloc_tag.h                                    Memory allocation profiling
+                                                                       <mailto:[email protected]>
 0xAA  00-3F  linux/uapi/linux/userfaultfd.h
 0xAB  00-1F  linux/nbd.h
 0xAC  00-1F  linux/raw.h
MAINTAINERS +1 -0
index a31f6f207afd..77f3fc487691 100644
@@ -16711,6 +16711,7 @@ S:	Maintained
 F:	Documentation/mm/allocation-profiling.rst
 F:	include/linux/alloc_tag.h
 F:	include/linux/pgalloc_tag.h
+F:	include/uapi/linux/alloc_tag.h
 F:	lib/alloc_tag.c
 
 MEMORY CONTROLLER DRIVERS
include/linux/codetag.h +2 -0
index ddae7484ca45..a25a085c2df1 100644
@@ -77,6 +77,8 @@ struct codetag_iterator {
 void codetag_lock_module_list(struct codetag_type *cttype);
 bool codetag_trylock_module_list(struct codetag_type *cttype);
 void codetag_unlock_module_list(struct codetag_type *cttype);
+unsigned long codetag_get_content_id(struct codetag_type *cttype);
+unsigned int codetag_get_count(struct codetag_type *cttype);
 struct codetag_iterator codetag_get_ct_iter(struct codetag_type *cttype);
 struct codetag *codetag_next_ct(struct codetag_iterator *iter);
 
include/uapi/linux/alloc_tag.h new file +54 -0

54 lines not on this page · raw message

lib/alloc_tag.c +230 -2

262 lines not on this page · raw message

lib/codetag.c +18 -0
index 4001a7ea6675..a9cda4c962a3 100644
@@ -19,6 +19,8 @@ struct codetag_type {
 	struct codetag_type_desc desc;
 	/* generates unique sequence number for module load */
 	unsigned long next_mod_seq;
+	/* bumped on every module load and unload */
+	unsigned long content_id;
 };
 
 struct codetag_range {
@@ -50,6 +52,20 @@ void codetag_unlock_module_list(struct codetag_type *cttype)
 	up_read(&cttype->mod_lock);
 }
 
+unsigned long codetag_get_content_id(struct codetag_type *cttype)
+{
+	lockdep_assert_held(&cttype->mod_lock);
+
+	return cttype->content_id;
+}
+
+unsigned int codetag_get_count(struct codetag_type *cttype)
+{
+	lockdep_assert_held(&cttype->mod_lock);
+
+	return cttype->count;
+}
+
 struct codetag_iterator codetag_get_ct_iter(struct codetag_type *cttype)
 {
 	struct codetag_iterator iter = {
@@ -204,6 +220,7 @@ static int codetag_module_init(struct codetag_type *cttype, struct module *mod)
 
 	down_write(&cttype->mod_lock);
 	cmod->mod_seq = ++cttype->next_mod_seq;
+	++cttype->content_id;
 	mod_id = idr_alloc(&cttype->mod_idr, cmod, 0, 0, GFP_KERNEL);
 	if (mod_id >= 0) {
 		if (cttype->desc.module_load) {
@@ -368,6 +385,7 @@ void codetag_unload_module(struct module *mod)
 			cttype->count -= range_size(cttype, &cmod->range);
 			idr_remove(&cttype->mod_idr, mod_id);
 			kfree(cmod);
+			++cttype->content_id;
 		}
 		up_write(&cttype->mod_lock);
 		if (found && cttype->desc.free_section_mem)
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
#8 lore raw

PATCH v3 2/6 alloc_tag: add ioctl filters to /proc/allocinfo

In reply to Abhishek Bapat

Extend the capability of the IOCTL mechanism to filter allocations based on tag's module name, function name, file name and line number.

---
 include/uapi/linux/alloc_tag.h | 26 ++++++++++++-
 lib/alloc_tag.c                | 68 ++++++++++++++++++++++++++++++++--
 2 files changed, 89 insertions(+), 5 deletions(-)
include/uapi/linux/alloc_tag.h +25 -1
index 901199bad514..cffb0c46e0b1 100644
@@ -34,8 +34,32 @@ struct allocinfo_tag_data {
 	struct allocinfo_counter counter;
 };
 
+enum {
+	ALLOCINFO_FILTER_MODNAME,
+	ALLOCINFO_FILTER_FUNCTION,
+	ALLOCINFO_FILTER_FILENAME,
+	ALLOCINFO_FILTER_LINENO,
+	__ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_LINENO
+};
+
+#define ALLOCINFO_FILTER_MASK_MODNAME		(1 << ALLOCINFO_FILTER_MODNAME)
+#define ALLOCINFO_FILTER_MASK_FUNCTION		(1 << ALLOCINFO_FILTER_FUNCTION)
+#define ALLOCINFO_FILTER_MASK_FILENAME		(1 << ALLOCINFO_FILTER_FILENAME)
+#define ALLOCINFO_FILTER_MASK_LINENO		(1 << ALLOCINFO_FILTER_LINENO)
+
+#define ALLOCINFO_FILTER_MASKS \
+	((1 << (__ALLOCINFO_FILTER_LAST + 1)) - 1)
+
+struct allocinfo_filter {
+	__u64 mask; /* bitmask of the filter fields used */
+	struct allocinfo_tag fields;
+};
+
 struct allocinfo_get_at {
-	__u64 pos;	/* input */
+	/* inputs */
+	__u64 pos;
+	struct allocinfo_filter filter;
+	/* output */
 	struct allocinfo_tag_data data;
 };
 
lib/alloc_tag.c +64 -4

117 lines not on this page · raw message

Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
#10 lore raw

PATCH v3 3/6 alloc_tag: add size-based filtering to ioctl

In reply to Abhishek Bapat

Extend the allocinfo filtering mechanism to allow users to filter tags based on the total number of bytes allocated [min_size, max_size]. The size range is inclusive.

Filtering by size involves retrieving allocinfo per-CPU counters, which is an expensive operation. Hence, the performance of size-based filtering will be worse than other filters.

---
 include/uapi/linux/alloc_tag.h |  8 +++-
 lib/alloc_tag.c                | 68 +++++++++++++++++++++++++++-------
 2 files changed, 62 insertions(+), 14 deletions(-)
include/uapi/linux/alloc_tag.h +7 -1
index cffb0c46e0b1..0e648192df4d 100644
@@ -39,13 +39,17 @@ enum {
 	ALLOCINFO_FILTER_FUNCTION,
 	ALLOCINFO_FILTER_FILENAME,
 	ALLOCINFO_FILTER_LINENO,
-	__ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_LINENO
+	ALLOCINFO_FILTER_MIN_SIZE,
+	ALLOCINFO_FILTER_MAX_SIZE,
+	__ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
 };
 
 #define ALLOCINFO_FILTER_MASK_MODNAME		(1 << ALLOCINFO_FILTER_MODNAME)
 #define ALLOCINFO_FILTER_MASK_FUNCTION		(1 << ALLOCINFO_FILTER_FUNCTION)
 #define ALLOCINFO_FILTER_MASK_FILENAME		(1 << ALLOCINFO_FILTER_FILENAME)
 #define ALLOCINFO_FILTER_MASK_LINENO		(1 << ALLOCINFO_FILTER_LINENO)
+#define ALLOCINFO_FILTER_MASK_MIN_SIZE		(1 << ALLOCINFO_FILTER_MIN_SIZE)
+#define ALLOCINFO_FILTER_MASK_MAX_SIZE		(1 << ALLOCINFO_FILTER_MAX_SIZE)
 
 #define ALLOCINFO_FILTER_MASKS \
 	((1 << (__ALLOCINFO_FILTER_LAST + 1)) - 1)
@@ -53,6 +57,8 @@ enum {
 struct allocinfo_filter {
 	__u64 mask; /* bitmask of the filter fields used */
 	struct allocinfo_tag fields;
+	__u64 min_size;
+	__u64 max_size;
 };
 
 struct allocinfo_get_at {
lib/alloc_tag.c +55 -13

148 lines not on this page · raw message

Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
#12 lore raw

PATCH v3 4/6 alloc_tag: add accuracy based filtering to ioctl

In reply to Abhishek Bapat

Extend the allocinfo filtering mechanism to allow users to filter tags based on their accuracy.

---
 include/uapi/linux/alloc_tag.h | 3 +++
 lib/alloc_tag.c                | 8 ++++++++
 2 files changed, 11 insertions(+)
include/uapi/linux/alloc_tag.h +3 -0
index 0e648192df4d..42445bdb11c5 100644
@@ -20,6 +20,7 @@ struct allocinfo_tag {
 	char function[ALLOCINFO_STR_SIZE];
 	char filename[ALLOCINFO_STR_SIZE];
 	__u64 lineno;
+	__u64 inaccurate;
 };
 
 /* The alignment ensures 32-bit compatible interfaces are not broken */
@@ -39,6 +40,7 @@ enum {
 	ALLOCINFO_FILTER_FUNCTION,
 	ALLOCINFO_FILTER_FILENAME,
 	ALLOCINFO_FILTER_LINENO,
+	ALLOCINFO_FILTER_INACCURATE,
 	ALLOCINFO_FILTER_MIN_SIZE,
 	ALLOCINFO_FILTER_MAX_SIZE,
 	__ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
@@ -48,6 +50,7 @@ enum {
 #define ALLOCINFO_FILTER_MASK_FUNCTION		(1 << ALLOCINFO_FILTER_FUNCTION)
 #define ALLOCINFO_FILTER_MASK_FILENAME		(1 << ALLOCINFO_FILTER_FILENAME)
 #define ALLOCINFO_FILTER_MASK_LINENO		(1 << ALLOCINFO_FILTER_LINENO)
+#define ALLOCINFO_FILTER_MASK_INACCURATE	(1 << ALLOCINFO_FILTER_INACCURATE)
 #define ALLOCINFO_FILTER_MASK_MIN_SIZE		(1 << ALLOCINFO_FILTER_MIN_SIZE)
 #define ALLOCINFO_FILTER_MASK_MAX_SIZE		(1 << ALLOCINFO_FILTER_MAX_SIZE)
 
lib/alloc_tag.c +8 -0
index ddc6946f56ab..cbcd12c4ef9c 100644
@@ -249,6 +249,8 @@ static bool matches_filter(struct codetag *ct, struct allocinfo_filter *filter,
 			   struct alloc_tag_counters *counters,
 			   bool *fetched_counters)
 {
+	bool inaccurate;
+
 	if (!filter || !filter->mask)
 		return true;
 
@@ -275,6 +277,12 @@ static bool matches_filter(struct codetag *ct, struct allocinfo_filter *filter,
 	    ct->lineno != filter->fields.lineno)
 		return false;
 
+	if (filter->mask & ALLOCINFO_FILTER_MASK_INACCURATE) {
+		inaccurate = !!(ct->flags & CODETAG_FLAG_INACCURATE);
+		if (inaccurate != !!(filter->fields.inaccurate))
+			return false;
+	}
+
 	if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE | ALLOCINFO_FILTER_MASK_MAX_SIZE)) {
 		if (!*fetched_counters) {
 			*counters = allocinfo_prefetch_counters(ct);
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
#20 lore raw

PATCH v3 5/6 kselftest: alloc_tag: add kselftest for ioctl interface

In reply to Abhishek Bapat

Introduce a kselftest to verify the new IOCTL-based interface for /proc/allocinfo. The test covers:

1. Validation of the filename filter.
2. Validation of the function filter.

The first test validates the functionality of the filename filter. Using "mm/memory.c" as the candidate filename filter, it retrieves filtered entries from both procfs and ioctl and matches the first VEC_MAX_ENTRIES entries.

The second test validates the functionality of the function filter. It uses "dup_mm" as the candidate function as we do not expect this function name to change frequently and hence won't be needing to modify this test often.

Note that both the tests match line no, function name and file name fields. Bytes allocated and calls are not matched as those values may change in the time when the data is being read from procfs and ioctl and hence can lead to false negatives.

---
 MAINTAINERS                                   |   1 +
 tools/testing/selftests/alloc_tag/Makefile    |   9 +
 .../alloc_tag/allocinfo_ioctl_test.c          | 313 ++++++++++++++++++
 3 files changed, 323 insertions(+)
 create mode 100644 tools/testing/selftests/alloc_tag/Makefile
 create mode 100644 tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c
MAINTAINERS +1 -0
index 77f3fc487691..80560f5f1292 100644
@@ -16713,6 +16713,7 @@ F:	include/linux/alloc_tag.h
 F:	include/linux/pgalloc_tag.h
 F:	include/uapi/linux/alloc_tag.h
 F:	lib/alloc_tag.c
+F:	tools/testing/selftests/alloc_tag/
 
 MEMORY CONTROLLER DRIVERS
 M:	Krzysztof Kozlowski <[email protected]>
tools/testing/selftests/alloc_tag/Makefile new file +9 -0
new file mode 100644
index 000000000000..f2b8fc022c3b
@@ -0,0 +1,9 @@
+# SPDX-License-Identifier: GPL-2.0
+
+TEST_GEN_PROGS := allocinfo_ioctl_test
+
+CFLAGS += -Wall
+CFLAGS += -I../../../../usr/include
+
+include ../lib.mk
+
tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +313 -0

313 lines not on this page · raw message

Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
#24 lore raw

PATCH v3 6/6 kselftest: alloc_tag: extend the allocinfo ioctl kselftest

In reply to Abhishek Bapat

Add the following 2 scenarios to the allocinfo ioctl kselftest:
1. Validate size based filtering
2. Validate lineno based filtering

The first test uses "do_init_module" as the candidate function for the test. This is because the associated site will only allocate memory when a kernel module is loaded. The return value of get_content_id() changes every time modules are loaded or unloaded. Hence, as long as get_content_id() values at the start and the end of the test are the same, the memory allocated by the do_init_module call site should also remain the same. Consequently, the test can assume consistency between the value returned by the ioctl and the procfs resulting in less flakiness.

---
 .../alloc_tag/allocinfo_ioctl_test.c          | 194 +++++++++++++++++-
 1 file changed, 193 insertions(+), 1 deletion(-)
tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c +193 -1
index 5c3c16e86c23..ce3576e3cd9b 100644
@@ -291,11 +291,191 @@ static int test_function_filter(void)
 	return run_filter_test(&filter);
 }
 
+static int test_size_filter(void)
+{
+	int fd;
+	struct allocinfo_tag_data_vec *tags = malloc(sizeof(*tags));
+	struct allocinfo_tag_data_vec *procfs_entries = malloc(sizeof(*procfs_entries));
+	struct allocinfo_filter filter;
+	int ret = KSFT_PASS;
+	__u64 target_size, i;
+	bool found = false;
+	const char *target_function = "do_init_module";
+
+	if (!tags || !procfs_entries) {
+		ksft_print_msg("Memory allocation failed.\n");
+		ret = KSFT_FAIL;
+		goto freemem;
+	}
+
+	fd = open(ALLOCINFO_PROC, O_RDONLY);
+	if (fd < 0) {
+		ksft_exit_skip("Failed to open " ALLOCINFO_PROC ": %s\n", strerror(errno));
+		ret = KSFT_FAIL;
+		goto freemem;
+	}
+
+	memset(&filter, 0, sizeof(filter));
+	filter.mask |= ALLOCINFO_FILTER_MASK_FUNCTION;
+	strncpy(filter.fields.function, target_function, ALLOCINFO_STR_SIZE);
+
+	if (get_filtered_procfs_entries(procfs_entries, &filter, fd)) {
+		ksft_print_msg("Error retrieving entries from " ALLOCINFO_PROC "\n");
+		ret = KSFT_FAIL;
+		goto exit;
+	}
+
+	if (procfs_entries->count == 0) {
+		ksft_print_msg("Function %s not found in procfs\n", target_function);
+		ret = KSFT_SKIP;
+		goto exit;
+	}
+
+	/*
+	 * We depend on the result of procfs entries to create the ioctl_filter. Hence we
+	 * cannot recycle the run_filter_test function here.
+	 */
+	target_size = procfs_entries->tag[0].counter.bytes;
+
+	memset(&filter, 0, sizeof(filter));
+	filter.mask |= ALLOCINFO_FILTER_MASK_MIN_SIZE | ALLOCINFO_FILTER_MASK_MAX_SIZE;
+	filter.min_size = target_size;
+	filter.max_size = target_size;
+
+	__u64 pos = 0;
+	enum ioctl_ret ioctl_status;
+
+	/*
+	 * This loop is required because the first 32 entries fetched by the IOCTL based on
+	 * the size parameter might not contain the exact entry that was used from procfs.
+	 * If that happens, we must update pos and fetch again until we find the exact entry.
+	 */
+	while (1) {
+		ioctl_status = get_filtered_ioctl_entries(tags, &filter, fd, pos);
+		if (ioctl_status == IOCTL_INVALID_DATA) {
+			ksft_print_msg("Trouble retrieving valid IOCTL entries, skipping.\n");
+			ret = KSFT_SKIP;
+			goto exit;
+		}
+		if (ioctl_status == IOCTL_FAILURE) {
+			ksft_print_msg("Error retrieving IOCTL entries.\n");
+			ret = KSFT_FAIL;
+			goto exit;
+		}
+
+		for (i = 0; i < tags->count; i++) {
+			if (strcmp(tags->tag[i].tag.function, target_function) == 0) {
+				found = true;
+				break;
+			}
+		}
+
+		if (found)
+			break;
+
+		if (tags->count < VEC_MAX_ENTRIES)
+			break;
+
+		pos += tags->count;
+	}
+
+	if (!found) {
+		ksft_print_msg("Entry with function %s not found in IOCTL results\n",
+			       target_function);
+		ret = KSFT_FAIL;
+	}
+
+exit:
+	close(fd);
+freemem:
+	free(tags);
+	free(procfs_entries);
+	return ret;
+}
+
+static int test_lineno_filter(void)
+{
+	int fd;
+	struct allocinfo_tag_data_vec *tags = malloc(sizeof(*tags));
+	struct allocinfo_tag_data_vec *procfs_entries = malloc(sizeof(*procfs_entries));
+	struct allocinfo_filter filter;
+	enum ioctl_ret ioctl_status;
+	int ret = KSFT_PASS;
+	__u64 target_lineno, i;
+
+	if (!tags || !procfs_entries) {
+		ksft_print_msg("Memory allocation failed.\n");
+		ret = KSFT_FAIL;
+		goto freemem;
+	}
+
+	fd = open(ALLOCINFO_PROC, O_RDONLY);
+	if (fd < 0) {
+		ksft_exit_skip("Failed to open " ALLOCINFO_PROC ": %s\n", strerror(errno));
+		ret = KSFT_FAIL;
+		goto freemem;
+	}
+
+	memset(&filter, 0, sizeof(filter));
+
+	if (get_filtered_procfs_entries(procfs_entries, &filter, fd)) {
+		ksft_print_msg("Error retrieving entries from " ALLOCINFO_PROC "\n");
+		ret = KSFT_FAIL;
+		goto exit;
+	}
+	if (procfs_entries->count == 0) {
+		ksft_print_msg("Could not retrieve procfs entries\n");
+		ret = KSFT_SKIP;
+		goto exit;
+	}
+	/*
+	 * We depend on the result of procfs entries to create the ioctl_filter. Hence we
+	 * cannot recycle the run_filter_test function here.
+	 */
+	target_lineno = procfs_entries->tag[0].tag.lineno;
+
+	filter.mask |= ALLOCINFO_FILTER_MASK_LINENO;
+	filter.fields.lineno = target_lineno;
+
+	ioctl_status = get_filtered_ioctl_entries(tags, &filter, fd, 0);
+	if (ioctl_status == IOCTL_INVALID_DATA) {
+		ksft_print_msg("Trouble retrieving valid IOCTL entries, skipping.\n");
+		ret = KSFT_SKIP;
+		goto exit;
+	}
+	if (ioctl_status == IOCTL_FAILURE) {
+		ksft_print_msg("Error retrieving IOCTL entries.\n");
+		ret = KSFT_FAIL;
+		goto exit;
+	}
+
+	if (tags->count == 0) {
+		ksft_print_msg("IOCTL returned 0 matches for target lineno %llu.\n", target_lineno);
+		ret = KSFT_FAIL;
+		goto exit;
+	}
+	for (i = 0; i < tags->count; i++) {
+		if (tags->tag[i].tag.lineno != target_lineno) {
+			ksft_print_msg("IOCTL entry %llu has incorrect lineno %llu.\n",
+				       i, tags->tag[i].tag.lineno);
+			ret = KSFT_FAIL;
+			goto exit;
+		}
+	}
+
+exit:
+	close(fd);
+freemem:
+	free(tags);
+	free(procfs_entries);
+	return ret;
+}
+
 int main(int argc, char *argv[])
 {
 	int ret;
 
-	ksft_set_plan(2);
+	ksft_set_plan(4);
 
 	ret = test_filename_filter();
 	if (ret == KSFT_SKIP)
@@ -309,5 +489,17 @@ int main(int argc, char *argv[])
 	else
 		ksft_test_result(ret == KSFT_PASS, "test_function_filter\n");
 
+	ret = test_size_filter();
+	if (ret == KSFT_SKIP)
+		ksft_test_result_skip("Skipping test_size_filter\n");
+	else
+		ksft_test_result(ret == KSFT_PASS, "test_size_filter\n");
+
+	ret = test_lineno_filter();
+	if (ret == KSFT_SKIP)
+		ksft_test_result_skip("Skipping test_lineno_filter\n");
+	else
+		ksft_test_result(ret == KSFT_PASS, "test_lineno_filter\n");
+
 	ksft_finished();
 }
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
maintainer
#25 lore raw
In reply to Abhishek Bapat
Quoted 12 lines · On Fri, 5 Jun 2026 23:36:45 +0000 Abhishek Bapat <[email protected]>…

Currently, memory allocation profiling data is primarily exposed through /proc/allocinfo. While useful for manual inspection, this text-based interface poses challenges for production monitoring and large-scale analysis:

1. Userspace must parse large amounts of text to extract specific fields.
2. To find specific tags, userspace must read the entire dataset, requiring many context switches and high data copying.
3. The kernel currently aggregates per-CPU counters for every allocation size, even those the user intends to filter out immediately.

Quoted 4 lines

This series introduces a new IOCTL-based binary interface for allocinfo that supports kernel-side filtering. By allowing the user to specify a filter mask, we significantly reduce the work performed in-kernel and the amount of data transferred to userspace.

Thanks. AI review found several things - you'll want to address at least the first few.

	https://sashiko.dev/#/patchset/[email protected]
reviewer
#2 lore raw

Re: [PATCH v3 1/6] alloc_tag: add ioctl to /proc/allocinfo

In reply to Abhishek Bapat

Hi Suren and Abhishek

Thanks for the new version.

Quoted 91 lines · Abhishek Bapat

From: Suren Baghdasaryan <[email protected]>

Add the following ioctl commands for /proc/allocinfo file:

ALLOCINFO_IOC_CONTENT_ID - gets content identifier which can be used to check whether the file content has changed specifically due to module load/unload. Every time a module is loaded / unloaded, the returned value will be different. By comparing the identifier value at the beginning and at the end of the content retrieval operation, users can validate retrieved information for consistency.

ALLOCINFO_IOC_GET_AT - gets the record at the specified position. This is the position of a record in /proc/allocinfo.

ALLOCINFO_IOC_GET_NEXT - gets the record next to the last retrieved one. If no records were previously retrieved, returns the first record.

---
  Documentation/mm/allocation-profiling.rst     |   5 +
  .../userspace-api/ioctl/ioctl-number.rst      |   2 +
  MAINTAINERS                                   |   1 +
  include/linux/codetag.h                       |   2 +
  include/uapi/linux/alloc_tag.h                |  54 ++++
  lib/alloc_tag.c                               | 232 +++++++++++++++++-
  lib/codetag.c                                 |  18 ++
  7 files changed, 312 insertions(+), 2 deletions(-)

create mode 100644 include/uapi/linux/alloc_tag.h

Documentation/mm/allocation-profiling.rst +5 -0
index 5389d241176a..c3a28467955f 100644
@@ -46,6 +46,11 @@ sysctl:
  Runtime info:
    /proc/allocinfo
 
+  Profiling data can be retrieved either by reading `/proc/allocinfo` directly as
+  text or programmatically via `ioctl()` calls defined in `<uapi/linux/alloc_tag.h>`.
+  The ioctl interface supports structured binary data extraction as well as filtering
+  by module name, function, file, line number, accuracy, or allocation size limits.
+
  Example output::
 
    root@moria-kvm:~# sort -g /proc/allocinfo|tail|numfmt --to=iec
Documentation/userspace-api/ioctl/ioctl-number.rst +2 -0
index 331223761fff..84f6808a8578 100644
@@ -349,6 +349,8 @@ Code  Seq#    Include File                                             Comments
                                                                         <mailto:[email protected]>
  0xA5  20-2F  linux/surface_aggregator/dtx.h                            Microsoft Surface DTX driver
                                                                         <mailto:[email protected]>
+0xA6  00-0F  uapi/linux/alloc_tag.h                                    Memory allocation profiling
+                                                                       <mailto:[email protected]>
  0xAA  00-3F  linux/uapi/linux/userfaultfd.h
  0xAB  00-1F  linux/nbd.h
  0xAC  00-1F  linux/raw.h
MAINTAINERS +1 -0
index a31f6f207afd..77f3fc487691 100644
@@ -16711,6 +16711,7 @@ S:	Maintained
  F:	Documentation/mm/allocation-profiling.rst
  F:	include/linux/alloc_tag.h
  F:	include/linux/pgalloc_tag.h
+F:	include/uapi/linux/alloc_tag.h
  F:	lib/alloc_tag.c
 
  MEMORY CONTROLLER DRIVERS
include/linux/codetag.h +2 -0
index ddae7484ca45..a25a085c2df1 100644
@@ -77,6 +77,8 @@ struct codetag_iterator {
  void codetag_lock_module_list(struct codetag_type *cttype);
  bool codetag_trylock_module_list(struct codetag_type *cttype);
  void codetag_unlock_module_list(struct codetag_type *cttype);
+unsigned long codetag_get_content_id(struct codetag_type *cttype);
+unsigned int codetag_get_count(struct codetag_type *cttype);
  struct codetag_iterator codetag_get_ct_iter(struct codetag_type *cttype);
  struct codetag *codetag_next_ct(struct codetag_iterator *iter);
 
include/uapi/linux/alloc_tag.h new file +0 -0
new file mode 100644
index 000000000000..901199bad514

include/uapi/linux/alloc_tag.h line 3

Quoted 3 lines
include/uapi/linux/alloc_tag.h new file +3 -0
@@ -0,0 +1,54 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+/*
+ *  include/linux/alloc_tag.h

nit: it should be include/uapi/linux/alloc_tag.h

(I guess you may have missed the comment I brought up before. It is not a critical problem though.)

Quoted 357 lines
include/uapi/linux/alloc_tag.h new file +51 -0
+ */
+
+#ifndef _UAPI_ALLOC_TAG_H
+#define _UAPI_ALLOC_TAG_H
+
+#include <linux/types.h>
+
+#define ALLOCINFO_STR_SIZE	64
+
+struct allocinfo_content_id {
+	__u64 id;
+};
+
+struct allocinfo_tag {
+	/* Longer names are trimmed */
+	char modname[ALLOCINFO_STR_SIZE];
+	char function[ALLOCINFO_STR_SIZE];
+	char filename[ALLOCINFO_STR_SIZE];
+	__u64 lineno;
+};
+
+/* The alignment ensures 32-bit compatible interfaces are not broken */
+struct allocinfo_counter {
+	__u64 bytes;
+	__u64 calls;
+	__u8 accurate;
+} __attribute__((aligned(8)));
+
+struct allocinfo_tag_data {
+	struct allocinfo_tag tag;
+	struct allocinfo_counter counter;
+};
+
+struct allocinfo_get_at {
+	__u64 pos;	/* input */
+	struct allocinfo_tag_data data;
+};
+
+#define _ALLOCINFO_IOC_CONTENT_ID	0
+#define _ALLOCINFO_IOC_GET_AT		1
+#define _ALLOCINFO_IOC_GET_NEXT		2
+
+#define ALLOCINFO_IOC_BASE		0xA6
+#define ALLOCINFO_IOC_CONTENT_ID	_IOR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_CONTENT_ID,	\
+					     struct allocinfo_content_id)
+#define ALLOCINFO_IOC_GET_AT		_IOWR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_GET_AT,	\
+					      struct allocinfo_get_at)
+#define ALLOCINFO_IOC_GET_NEXT		_IOR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_GET_NEXT,	\
+					     struct allocinfo_tag_data)
+
+#endif /* _UAPI_ALLOC_TAG_H */
lib/alloc_tag.c +230 -2
index d9be1cf5187d..a0577215eb3d 100644
@@ -5,6 +5,7 @@
  #include <linux/gfp.h>
  #include <linux/kallsyms.h>
  #include <linux/module.h>
+#include <linux/mutex.h>
  #include <linux/page_ext.h>
  #include <linux/pgalloc_tag.h>
  #include <linux/proc_fs.h>
@@ -14,6 +15,7 @@
  #include <linux/string_choices.h>
  #include <linux/vmalloc.h>
  #include <linux/kmemleak.h>
+#include <uapi/linux/alloc_tag.h>
 
  #define ALLOCINFO_FILE_NAME		"allocinfo"
  #define MODULE_ALLOC_TAG_VMAP_SIZE	(100000UL * sizeof(struct alloc_tag))
@@ -47,6 +49,10 @@ struct allocinfo_private {
  	struct codetag_iterator iter;
  	struct codetag_iterator reported_iter;
  	bool print_header;
+	/* ioctl uses a separate iterator not to interfere with reads */
+	struct codetag_iterator ioctl_iter;
+	bool positioned; /* seq_open_private() sets to 0 */
+	struct mutex ioctl_lock;
  };
 
  static void *allocinfo_start(struct seq_file *m, loff_t *pos)
@@ -130,6 +136,229 @@ static const struct seq_operations allocinfo_seq_op = {
  	.show	= allocinfo_show,
  };
 
+/*
+ * Initializes seq_file operations and allocates private state when opening
+ * the /proc/allocinfo procfs entry.
+ */
+static int allocinfo_open(struct inode *inode, struct file *file)
+{
+	int ret;
+
+	ret = seq_open_private(file, &allocinfo_seq_op,
+			       sizeof(struct allocinfo_private));
+	if (!ret) {
+		struct seq_file *m = file->private_data;
+		struct allocinfo_private *priv = m->private;
+
+		mutex_init(&priv->ioctl_lock);
+	}
+	return ret;
+}
+
+/*
+ * Cleans up the seq_file state and frees up the private state allocated in
+ * allocinfo_open() when closing the /proc/allocinfo file descriptor.
+ */
+static int allocinfo_release(struct inode *inode, struct file *file)
+{
+	return seq_release_private(inode, file);
+}
+
+/*
+ * Returns a pointer to the suffix of a string so that its length fits within
+ * ALLOCINFO_STR_SIZE, preserving the trailing characters.
+ */
+static const char *allocinfo_str(const char *str)
+{
+	size_t len = strlen(str);
+
+	/* Keep an extra space for the trailing NULL. */
+	if (len >= ALLOCINFO_STR_SIZE)
+		str += (len - ALLOCINFO_STR_SIZE) + 1;
+	return str;
+}
+
+/* Copy a string and trim from the beginning if it's too long */
+static void allocinfo_copy_str(char *dest, const char *src)
+{
+	strscpy_pad(dest, allocinfo_str(src), ALLOCINFO_STR_SIZE);
+}
+
+/*
+ * Populates the UAPI allocinfo_tag_data structure with active runtime
+ * profiling counters extracted from the given kernel codetag.
+ */
+static void allocinfo_to_params(struct codetag *ct,
+				struct allocinfo_tag_data *data)
+{
+	struct alloc_tag *tag = ct_to_alloc_tag(ct);
+	struct alloc_tag_counters counter = alloc_tag_read(tag);
+
+	if (ct->modname)
+		allocinfo_copy_str(data->tag.modname, ct->modname);
+	else
+		data->tag.modname[0] = '\0';
+	allocinfo_copy_str(data->tag.function, ct->function);
+	allocinfo_copy_str(data->tag.filename, ct->filename);
+	data->tag.lineno = ct->lineno;
+	data->counter.bytes = counter.bytes;
+	data->counter.calls = counter.calls;
+	data->counter.accurate = !alloc_tag_is_inaccurate(tag);
+}
+
+/*
+ * Retrieves the unique content ID representing the current allocation tag module
+ * layout, allowing userspace to detect if modules were loaded / unloaded.
+ */
+static int allocinfo_ioctl_get_content_id(struct seq_file *m, void __user *arg)
+{
+	struct allocinfo_content_id params;
+
+	codetag_lock_module_list(alloc_tag_cttype);
+	params.id = codetag_get_content_id(alloc_tag_cttype);
+	codetag_unlock_module_list(alloc_tag_cttype);
+	if (copy_to_user(arg, &params, sizeof(params)))
+		return -EFAULT;
+
+	return 0;
+}
+
+/*
+ * Seeks the ioctl iterator to the specified 0-indexed tag position, reads its
+ * profiling data and returns it to userspace.
+ */
+static int allocinfo_ioctl_get_at(struct seq_file *m, void __user *arg)
+{
+	struct allocinfo_private *priv;
+	struct codetag *ct;
+	__u64 pos;
+	struct allocinfo_get_at params = {0};
+
+	if (copy_from_user(&params, arg, sizeof(params)))
+		return -EFAULT;
+
+	priv = m->private;
+	pos = params.pos;
+
+	mutex_lock(&priv->ioctl_lock);
+	codetag_lock_module_list(alloc_tag_cttype);
+
+	if (pos >= codetag_get_count(alloc_tag_cttype)) {
+		codetag_unlock_module_list(alloc_tag_cttype);
+		mutex_unlock(&priv->ioctl_lock);
+		return -ENOENT;
+	}
+
+	/* Find the codetag */
+	priv->ioctl_iter = codetag_get_ct_iter(alloc_tag_cttype);
+	ct = codetag_next_ct(&priv->ioctl_iter);
+	while (ct && pos--)
+		ct = codetag_next_ct(&priv->ioctl_iter);
+	if (ct) {
+		allocinfo_to_params(ct, &params.data);
+		priv->positioned = true;
+	}
+
+	codetag_unlock_module_list(alloc_tag_cttype);
+	mutex_unlock(&priv->ioctl_lock);
+
+	if (!ct)
+		return -ENOENT;
+
+	if (copy_to_user(arg, &params, sizeof(params)))
+		return -EFAULT;
+
+	return 0;
+}
+
+/*
+ * Advances the ioctl iterator to the next allocation tag in the sequence and
+ * returns its profiling data to userspace.
+ */
+static int allocinfo_ioctl_get_next(struct seq_file *m, void __user *arg)
+{
+	struct allocinfo_private *priv;
+	struct codetag *ct;
+	struct allocinfo_tag_data params;
+	int ret = 0;
+
+	memset(&params, 0, sizeof(params));
+	priv = m->private;
+
+	mutex_lock(&priv->ioctl_lock);
+	codetag_lock_module_list(alloc_tag_cttype);
+
+	if (!priv->positioned) {
+		priv->ioctl_iter = codetag_get_ct_iter(alloc_tag_cttype);
+		priv->positioned = true;
+	}
+
+	ct = codetag_next_ct(&priv->ioctl_iter);
+	if (ct)
+		allocinfo_to_params(ct, &params);
+
+	if (!ct) {
+		priv->positioned = false;
+		ret = -ENOENT;
+	}
+	codetag_unlock_module_list(alloc_tag_cttype);
+	mutex_unlock(&priv->ioctl_lock);
+
+	if (ret == 0) {
+		if (copy_to_user(arg, &params, sizeof(params)))
+			return -EFAULT;
+	}
+	return ret;
+}
+
+/*
+ * Entry point ioctl function for /proc/allocinfo routing requests to fetch the
+ * layout content ID, seek to a specific tag, or read sequential tags.
+ */
+static long allocinfo_ioctl(struct file *file, unsigned int cmd,
+			    unsigned long __arg)
+{
+	void __user *arg = (void __user *)__arg;
+	int ret;
+
+	switch (cmd) {
+	case ALLOCINFO_IOC_CONTENT_ID:
+		ret = allocinfo_ioctl_get_content_id(file->private_data, arg);
+		break;
+	case ALLOCINFO_IOC_GET_AT:
+		ret = allocinfo_ioctl_get_at(file->private_data, arg);
+		break;
+	case ALLOCINFO_IOC_GET_NEXT:
+		ret = allocinfo_ioctl_get_next(file->private_data, arg);
+		break;
+	default:
+		ret = -ENOIOCTLCMD;
+		break;
+	}
+
+	return ret;
+}
+
+#ifdef CONFIG_COMPAT
+static long allocinfo_compat_ioctl(struct file *file, unsigned int cmd,
+				   unsigned long arg)
+{
+	return allocinfo_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
+}
+#endif
+
+static const struct proc_ops allocinfo_proc_ops = {
+	.proc_open		= allocinfo_open,
+	.proc_read_iter		= seq_read_iter,
+	.proc_lseek		= seq_lseek,
+	.proc_release		= allocinfo_release,
+	.proc_ioctl		= allocinfo_ioctl,
+#ifdef CONFIG_COMPAT
+	.proc_compat_ioctl	= allocinfo_compat_ioctl,
+#endif
+
+};
+
  size_t alloc_tag_top_users(struct codetag_bytes *tags, size_t count, bool can_sleep)
  {
  	struct codetag_iterator iter;
@@ -993,8 +1222,7 @@ static int __init alloc_tag_init(void)
  		return 0;
  	}
 
-	if (!proc_create_seq_private(ALLOCINFO_FILE_NAME, 0400, NULL, &allocinfo_seq_op,
-				     sizeof(struct allocinfo_private), NULL)) {
+	if (!proc_create(ALLOCINFO_FILE_NAME, 0400, NULL, &allocinfo_proc_ops)) {
  		pr_err("Failed to create %s file\n", ALLOCINFO_FILE_NAME);
  		shutdown_mem_profiling(false);
  		return -ENOMEM;
lib/codetag.c +16 -0
index 4001a7ea6675..a9cda4c962a3 100644
@@ -19,6 +19,8 @@ struct codetag_type {
  	struct codetag_type_desc desc;
  	/* generates unique sequence number for module load */
  	unsigned long next_mod_seq;
+	/* bumped on every module load and unload */
+	unsigned long content_id;
  };
 
  struct codetag_range {
@@ -50,6 +52,20 @@ void codetag_unlock_module_list(struct codetag_type *cttype)
  	up_read(&cttype->mod_lock);
  }
 
+unsigned long codetag_get_content_id(struct codetag_type *cttype)
+{
+	lockdep_assert_held(&cttype->mod_lock);
+
+	return cttype->content_id;
+}
+
+unsigned int codetag_get_count(struct codetag_type *cttype)
+{
+	lockdep_assert_held(&cttype->mod_lock);
+
+	return cttype->count;
+}
+
  struct codetag_iterator codetag_get_ct_iter(struct codetag_type *cttype)
  {
  	struct codetag_iterator iter = {

lib/codetag.c static int codetag_module_init(struct codetag_type *cttype, struct module *mod) · line 223

Quoted 4 lines
lib/codetag.c +1 -0
@@ -204,6 +220,7 @@ static int codetag_module_init(struct codetag_type *cttype, struct module *mod)
 
  	down_write(&cttype->mod_lock);
  	cmod->mod_seq = ++cttype->next_mod_seq;
+	++cttype->content_id;

I have a comment on the content_id bump placement.

++cttype->content_id is placed before idr_alloc and the module_load

callback. If idr_alloc fails or module_load returns an error

(While the chance of this occurring is very low.), the idr entry gets

rolled back but content_id has already been bumped. The actual

content didn't change in this case, so userspace would see a

different content_id and assume the data is inconsistent when it

isn't.

Thanks

Best Regards

Hao

Quoted 11 lines
lib/codetag.c +1 -0
  	mod_id = idr_alloc(&cttype->mod_idr, cmod, 0, 0, GFP_KERNEL);
  	if (mod_id >= 0) {
  		if (cttype->desc.module_load) {
@@ -368,6 +385,7 @@ void codetag_unload_module(struct module *mod)
  			cttype->count -= range_size(cttype, &cmod->range);
  			idr_remove(&cttype->mod_idr, mod_id);
  			kfree(cmod);
+			++cttype->content_id;
  		}
  		up_write(&cttype->mod_lock);
  		if (found && cttype->desc.free_section_mem)
reviewer Acked-by on v3 2/6
#9 lore raw

Re: [PATCH v3 2/6] alloc_tag: add ioctl filters to /proc/allocinfo

In reply to Abhishek Bapat

Hi Abhishek

Thanks for the new version.

Quoted 4 lines · Abhishek Bapat

Extend the capability of the IOCTL mechanism to filter allocations based on tag's module name, function name, file name and line number.

Quoted 69 lines
---
  include/uapi/linux/alloc_tag.h | 26 ++++++++++++-
  lib/alloc_tag.c                | 68 ++++++++++++++++++++++++++++++++--
  2 files changed, 89 insertions(+), 5 deletions(-)
include/uapi/linux/alloc_tag.h +25 -1
index 901199bad514..cffb0c46e0b1 100644
@@ -34,8 +34,32 @@ struct allocinfo_tag_data {
  	struct allocinfo_counter counter;
  };
 
+enum {
+	ALLOCINFO_FILTER_MODNAME,
+	ALLOCINFO_FILTER_FUNCTION,
+	ALLOCINFO_FILTER_FILENAME,
+	ALLOCINFO_FILTER_LINENO,
+	__ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_LINENO
+};
+
+#define ALLOCINFO_FILTER_MASK_MODNAME		(1 << ALLOCINFO_FILTER_MODNAME)
+#define ALLOCINFO_FILTER_MASK_FUNCTION		(1 << ALLOCINFO_FILTER_FUNCTION)
+#define ALLOCINFO_FILTER_MASK_FILENAME		(1 << ALLOCINFO_FILTER_FILENAME)
+#define ALLOCINFO_FILTER_MASK_LINENO		(1 << ALLOCINFO_FILTER_LINENO)
+
+#define ALLOCINFO_FILTER_MASKS \
+	((1 << (__ALLOCINFO_FILTER_LAST + 1)) - 1)
+
+struct allocinfo_filter {
+	__u64 mask; /* bitmask of the filter fields used */
+	struct allocinfo_tag fields;
+};
+
  struct allocinfo_get_at {
-	__u64 pos;	/* input */
+	/* inputs */
+	__u64 pos;
+	struct allocinfo_filter filter;
+	/* output */
  	struct allocinfo_tag_data data;
  };
 
lib/alloc_tag.c +7 -0
index a0577215eb3d..93bc976ac505 100644
@@ -49,6 +49,7 @@ struct allocinfo_private {
  	struct codetag_iterator iter;
  	struct codetag_iterator reported_iter;
  	bool print_header;
+	struct allocinfo_filter filter;
  	/* ioctl uses a separate iterator not to interfere with reads */
  	struct codetag_iterator ioctl_iter;
  	bool positioned; /* seq_open_private() sets to 0 */
@@ -184,6 +185,12 @@ static void allocinfo_copy_str(char *dest, const char *src)
  	strscpy_pad(dest, allocinfo_str(src), ALLOCINFO_STR_SIZE);
  }
 
+/* Compare two strings and only consider the trimmed suffix if s1 is too long */
+static int allocinfo_cmp_str(const char *str, const char *template)
+{
+	return strncmp(allocinfo_str(str), template, ALLOCINFO_STR_SIZE);
+}
+
  /*
   * Populates the UAPI allocinfo_tag_data structure with active runtime
   * profiling counters extracted from the given kernel codetag.

lib/alloc_tag.c static int allocinfo_ioctl_get_content_id(struct seq_file *m, void __user *arg) · line 235

Quoted 6 lines
lib/alloc_tag.c +3 -0
@@ -223,6 +230,40 @@ static int allocinfo_ioctl_get_content_id(struct seq_file *m, void __user *arg)
  	return 0;
  }
 
+/*
+ * Verifies whether a given codetag satisfies the active filtering criteria by
+ * matching it's characteristics against the specified filter.

nit: s/it's/its/

Quoted 94 lines
lib/alloc_tag.c +54 -4
+ */
+static bool matches_filter(struct codetag *ct, struct allocinfo_filter *filter)
+{
+	if (!filter || !filter->mask)
+		return true;
+
+	if (filter->mask & ALLOCINFO_FILTER_MASK_MODNAME) {
+		/* user wants to filter by modname but ct->modname is NULL */
+		if (!ct->modname) {
+			/* validate if user was attempting to filter for built-in allocations */
+			if (filter->fields.modname[0] != '\0')
+				return false;
+		} else if (allocinfo_cmp_str(ct->modname, filter->fields.modname))
+			return false;
+	}
+
+	if ((filter->mask & ALLOCINFO_FILTER_MASK_FUNCTION) &&
+	    ct->function && (allocinfo_cmp_str(ct->function, filter->fields.function)))
+		return false;
+
+	if ((filter->mask & ALLOCINFO_FILTER_MASK_FILENAME) &&
+	    ct->filename && (allocinfo_cmp_str(ct->filename, filter->fields.filename)))
+		return false;
+
+	if ((filter->mask & ALLOCINFO_FILTER_MASK_LINENO) &&
+	    ct->lineno != filter->fields.lineno)
+		return false;
+
+	return true;
+}
+
  /*
   * Seeks the ioctl iterator to the specified 0-indexed tag position, reads its
   * profiling data and returns it to userspace.
@@ -231,29 +272,46 @@ static int allocinfo_ioctl_get_at(struct seq_file *m, void __user *arg)
  {
  	struct allocinfo_private *priv;
  	struct codetag *ct;
-	__u64 pos;
  	struct allocinfo_get_at params = {0};
+	__u64 skip_count;
 
  	if (copy_from_user(&params, arg, sizeof(params)))
  		return -EFAULT;
 
+	if (params.filter.mask & ~ALLOCINFO_FILTER_MASKS)
+		return -EINVAL;
+
  	priv = m->private;
-	pos = params.pos;
 
  	mutex_lock(&priv->ioctl_lock);
  	codetag_lock_module_list(alloc_tag_cttype);
 
-	if (pos >= codetag_get_count(alloc_tag_cttype)) {
+	if (params.pos >= codetag_get_count(alloc_tag_cttype)) {
  		codetag_unlock_module_list(alloc_tag_cttype);
  		mutex_unlock(&priv->ioctl_lock);
  		return -ENOENT;
  	}
 
+	skip_count = params.pos;
+
+	if (params.filter.mask)
+		priv->filter = params.filter;
+	else
+		priv->filter.mask = 0;
+
  	/* Find the codetag */
  	priv->ioctl_iter = codetag_get_ct_iter(alloc_tag_cttype);
  	ct = codetag_next_ct(&priv->ioctl_iter);
-	while (ct && pos--)
+
+	while (ct) {
+		if (matches_filter(ct, &priv->filter)) {
+			if (skip_count == 0)
+				break;
+			skip_count--;
+		}
  		ct = codetag_next_ct(&priv->ioctl_iter);
+	}
+
  	if (ct) {
  		allocinfo_to_params(ct, &params.data);
  		priv->positioned = true;
@@ -294,6 +352,8 @@ static int allocinfo_ioctl_get_next(struct seq_file *m, void __user *arg)
  	}
 
  	ct = codetag_next_ct(&priv->ioctl_iter);
+	while (ct && !matches_filter(ct, &priv->filter))
+		ct = codetag_next_ct(&priv->ioctl_iter);
  	if (ct)
  		allocinfo_to_params(ct, &params);
 
reviewer
#11 lore raw

Re: [PATCH v3 3/6] alloc_tag: add size-based filtering to ioctl

In reply to Abhishek Bapat

Hi Abhishek

Thanks for the new version.

Quoted 105 lines · Abhishek Bapat

Extend the allocinfo filtering mechanism to allow users to filter tags based on the total number of bytes allocated [min_size, max_size]. The size range is inclusive.

Filtering by size involves retrieving allocinfo per-CPU counters, which is an expensive operation. Hence, the performance of size-based filtering will be worse than other filters.

---
  include/uapi/linux/alloc_tag.h |  8 +++-
  lib/alloc_tag.c                | 68 +++++++++++++++++++++++++++-------
  2 files changed, 62 insertions(+), 14 deletions(-)
include/uapi/linux/alloc_tag.h +7 -1
index cffb0c46e0b1..0e648192df4d 100644
@@ -39,13 +39,17 @@ enum {
  	ALLOCINFO_FILTER_FUNCTION,
  	ALLOCINFO_FILTER_FILENAME,
  	ALLOCINFO_FILTER_LINENO,
-	__ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_LINENO
+	ALLOCINFO_FILTER_MIN_SIZE,
+	ALLOCINFO_FILTER_MAX_SIZE,
+	__ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
  };
 
  #define ALLOCINFO_FILTER_MASK_MODNAME		(1 << ALLOCINFO_FILTER_MODNAME)
  #define ALLOCINFO_FILTER_MASK_FUNCTION		(1 << ALLOCINFO_FILTER_FUNCTION)
  #define ALLOCINFO_FILTER_MASK_FILENAME		(1 << ALLOCINFO_FILTER_FILENAME)
  #define ALLOCINFO_FILTER_MASK_LINENO		(1 << ALLOCINFO_FILTER_LINENO)
+#define ALLOCINFO_FILTER_MASK_MIN_SIZE		(1 << ALLOCINFO_FILTER_MIN_SIZE)
+#define ALLOCINFO_FILTER_MASK_MAX_SIZE		(1 << ALLOCINFO_FILTER_MAX_SIZE)
 
  #define ALLOCINFO_FILTER_MASKS \
  	((1 << (__ALLOCINFO_FILTER_LAST + 1)) - 1)
@@ -53,6 +57,8 @@ enum {
  struct allocinfo_filter {
  	__u64 mask; /* bitmask of the filter fields used */
  	struct allocinfo_tag fields;
+	__u64 min_size;
+	__u64 max_size;
  };
 
  struct allocinfo_get_at {
lib/alloc_tag.c +20 -7
index 93bc976ac505..ddc6946f56ab 100644
@@ -191,15 +191,26 @@ static int allocinfo_cmp_str(const char *str, const char *template)
  	return strncmp(allocinfo_str(str), template, ALLOCINFO_STR_SIZE);
  }
 
+/* Fetch the per-CPU counters */
+static inline struct alloc_tag_counters allocinfo_prefetch_counters(struct codetag *ct)
+{
+	return alloc_tag_read(ct_to_alloc_tag(ct));
+}
+
  /*
   * Populates the UAPI allocinfo_tag_data structure with active runtime
   * profiling counters extracted from the given kernel codetag.
   */
  static void allocinfo_to_params(struct codetag *ct,
-				struct allocinfo_tag_data *data)
+				struct allocinfo_tag_data *data,
+				struct alloc_tag_counters *counters)
  {
-	struct alloc_tag *tag = ct_to_alloc_tag(ct);
-	struct alloc_tag_counters counter = alloc_tag_read(tag);
+	struct alloc_tag_counters local_counters;
+
+	if (!counters) {
+		local_counters = allocinfo_prefetch_counters(ct);
+		counters = &local_counters;
+	}
 
  	if (ct->modname)
  		allocinfo_copy_str(data->tag.modname, ct->modname);
@@ -208,9 +219,9 @@ static void allocinfo_to_params(struct codetag *ct,
  	allocinfo_copy_str(data->tag.function, ct->function);
  	allocinfo_copy_str(data->tag.filename, ct->filename);
  	data->tag.lineno = ct->lineno;
-	data->counter.bytes = counter.bytes;
-	data->counter.calls = counter.calls;
-	data->counter.accurate = !alloc_tag_is_inaccurate(tag);
+	data->counter.bytes = counters->bytes;
+	data->counter.calls = counters->calls;
+	data->counter.accurate = !alloc_tag_is_inaccurate(ct_to_alloc_tag(ct));
  }
 
  /*
@@ -234,7 +245,9 @@ static int allocinfo_ioctl_get_content_id(struct seq_file *m, void __user *arg)
   * Verifies whether a given codetag satisfies the active filtering criteria by
   * matching it's characteristics against the specified filter.
   */
-static bool matches_filter(struct codetag *ct, struct allocinfo_filter *filter)
+static bool matches_filter(struct codetag *ct, struct allocinfo_filter *filter,
+			   struct alloc_tag_counters *counters,
+			   bool *fetched_counters)
  {
  	if (!filter || !filter->mask)
  		return true;

lib/alloc_tag.c static bool matches_filter(struct codetag *ct, struct allocinfo_filter *filter) · line 263

Quoted 4 lines
lib/alloc_tag.c +1 -0
@@ -247,20 +260,34 @@ static bool matches_filter(struct codetag *ct, struct allocinfo_filter *filter)
  				return false;
  		} else if (allocinfo_cmp_str(ct->modname, filter->fields.modname))
  			return false;
+		}

It seems an extra } was accidentally added here

lib/alloc_tag.c static bool matches_filter(struct codetag *ct, struct allocinfo_filter *filter) · line 269

Quoted 7 lines
lib/alloc_tag.c +1 -1
  	}
 
  	if ((filter->mask & ALLOCINFO_FILTER_MASK_FUNCTION) &&
-	    ct->function && (allocinfo_cmp_str(ct->function, filter->fields.function)))
+	    ct->function && allocinfo_cmp_str(ct->function, filter->fields.function))
  		return false;
 

This should be fixed in the second patch; it's unrelated to current functionality.

lib/alloc_tag.c static bool matches_filter(struct codetag *ct, struct allocinfo_filter *filter) · line 272

Quoted 4 lines
lib/alloc_tag.c +1 -1
  	if ((filter->mask & ALLOCINFO_FILTER_MASK_FILENAME) &&
-	    ct->filename && (allocinfo_cmp_str(ct->filename, filter->fields.filename)))
+	    ct->filename && allocinfo_cmp_str(ct->filename, filter->fields.filename))
  		return false;

Ditto

Thanks

Best Regards

Hao

Quoted 87 lines
lib/alloc_tag.c +32 -4
  	if ((filter->mask & ALLOCINFO_FILTER_MASK_LINENO) &&
  	    ct->lineno != filter->fields.lineno)
  		return false;
 
+	if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE | ALLOCINFO_FILTER_MASK_MAX_SIZE)) {
+		if (!*fetched_counters) {
+			*counters = allocinfo_prefetch_counters(ct);
+			*fetched_counters = true;
+		}
+		if ((filter->mask & ALLOCINFO_FILTER_MASK_MIN_SIZE) &&
+		    counters->bytes < filter->min_size)
+			return false;
+		if ((filter->mask & ALLOCINFO_FILTER_MASK_MAX_SIZE) &&
+		    counters->bytes > filter->max_size)
+			return false;
+	}
+
  	return true;
  }
 
@@ -274,6 +301,8 @@ static int allocinfo_ioctl_get_at(struct seq_file *m, void __user *arg)
  	struct codetag *ct;
  	struct allocinfo_get_at params = {0};
  	__u64 skip_count;
+	struct alloc_tag_counters counters;
+	bool fetched_counters;
 
  	if (copy_from_user(&params, arg, sizeof(params)))
  		return -EFAULT;
@@ -281,6 +310,11 @@ static int allocinfo_ioctl_get_at(struct seq_file *m, void __user *arg)
  	if (params.filter.mask & ~ALLOCINFO_FILTER_MASKS)
  		return -EINVAL;
 
+	if ((params.filter.mask & ALLOCINFO_FILTER_MASK_MIN_SIZE) &&
+	    (params.filter.mask & ALLOCINFO_FILTER_MASK_MAX_SIZE) &&
+	    params.filter.min_size > params.filter.max_size)
+		return -EINVAL;
+
  	priv = m->private;
 
  	mutex_lock(&priv->ioctl_lock);
@@ -304,7 +338,8 @@ static int allocinfo_ioctl_get_at(struct seq_file *m, void __user *arg)
  	ct = codetag_next_ct(&priv->ioctl_iter);
 
  	while (ct) {
-		if (matches_filter(ct, &priv->filter)) {
+		fetched_counters = false;
+		if (matches_filter(ct, &priv->filter, &counters, &fetched_counters)) {
  			if (skip_count == 0)
  				break;
  			skip_count--;
@@ -313,7 +348,7 @@ static int allocinfo_ioctl_get_at(struct seq_file *m, void __user *arg)
  	}
 
  	if (ct) {
-		allocinfo_to_params(ct, &params.data);
+		allocinfo_to_params(ct, &params.data, fetched_counters ? &counters : NULL);
  		priv->positioned = true;
  	}
 
@@ -339,6 +374,8 @@ static int allocinfo_ioctl_get_next(struct seq_file *m, void __user *arg)
  	struct codetag *ct;
  	struct allocinfo_tag_data params;
  	int ret = 0;
+	struct alloc_tag_counters counters;
+	bool fetched_counters;
 
  	memset(&params, 0, sizeof(params));
  	priv = m->private;
@@ -352,10 +389,15 @@ static int allocinfo_ioctl_get_next(struct seq_file *m, void __user *arg)
  	}
 
  	ct = codetag_next_ct(&priv->ioctl_iter);
-	while (ct && !matches_filter(ct, &priv->filter))
+	while (ct) {
+		fetched_counters = false;
+		if (matches_filter(ct, &priv->filter, &counters, &fetched_counters))
+			break;
  		ct = codetag_next_ct(&priv->ioctl_iter);
+	}
+
  	if (ct)
-		allocinfo_to_params(ct, &params);
+		allocinfo_to_params(ct, &params, fetched_counters ? &counters : NULL);
 
  	if (!ct) {
  		priv->positioned = false;
reviewer
#13 lore raw

Re: [PATCH v3 4/6] alloc_tag: add accuracy based filtering to ioctl

In reply to Abhishek Bapat

Hi Abhishek

Quoted 14 lines · Abhishek Bapat

Extend the allocinfo filtering mechanism to allow users to filter tags based on their accuracy.

---
  include/uapi/linux/alloc_tag.h | 3 +++
  lib/alloc_tag.c                | 8 ++++++++
  2 files changed, 11 insertions(+)
include/uapi/linux/alloc_tag.h +0 -0
index 0e648192df4d..42445bdb11c5 100644

include/uapi/linux/alloc_tag.h struct allocinfo_tag { · line 23

Quoted 4 lines
include/uapi/linux/alloc_tag.h +1 -0
@@ -20,6 +20,7 @@ struct allocinfo_tag {
  	char function[ALLOCINFO_STR_SIZE];
  	char filename[ALLOCINFO_STR_SIZE];
  	__u64 lineno;
+	__u64 inaccurate;

I was wondering if it would make sense to define inaccurate as a flags field

(e.g. __u64 flags with ALLOCINFO_TAG_F_INACCURATE (1 <<0)),

so that only bit 0 is used today and the upper bits are reserved for future use,

aligning with current kernel codebase.

This design also allows for better extensibility if we need to

add new flags for any reason in the future.

We also need to add flag validity checks if we go this route.

Thanks

Best Regards

Hao

Quoted 45 lines
include/uapi/linux/alloc_tag.h +2 -0
  };
 
  /* The alignment ensures 32-bit compatible interfaces are not broken */
@@ -39,6 +40,7 @@ enum {
  	ALLOCINFO_FILTER_FUNCTION,
  	ALLOCINFO_FILTER_FILENAME,
  	ALLOCINFO_FILTER_LINENO,
+	ALLOCINFO_FILTER_INACCURATE,
  	ALLOCINFO_FILTER_MIN_SIZE,
  	ALLOCINFO_FILTER_MAX_SIZE,
  	__ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
@@ -48,6 +50,7 @@ enum {
  #define ALLOCINFO_FILTER_MASK_FUNCTION		(1 << ALLOCINFO_FILTER_FUNCTION)
  #define ALLOCINFO_FILTER_MASK_FILENAME		(1 << ALLOCINFO_FILTER_FILENAME)
  #define ALLOCINFO_FILTER_MASK_LINENO		(1 << ALLOCINFO_FILTER_LINENO)
+#define ALLOCINFO_FILTER_MASK_INACCURATE	(1 << ALLOCINFO_FILTER_INACCURATE)
  #define ALLOCINFO_FILTER_MASK_MIN_SIZE		(1 << ALLOCINFO_FILTER_MIN_SIZE)
  #define ALLOCINFO_FILTER_MASK_MAX_SIZE		(1 << ALLOCINFO_FILTER_MAX_SIZE)
 
lib/alloc_tag.c +8 -0
index ddc6946f56ab..cbcd12c4ef9c 100644
@@ -249,6 +249,8 @@ static bool matches_filter(struct codetag *ct, struct allocinfo_filter *filter,
  			   struct alloc_tag_counters *counters,
  			   bool *fetched_counters)
  {
+	bool inaccurate;
+
  	if (!filter || !filter->mask)
  		return true;
 
@@ -275,6 +277,12 @@ static bool matches_filter(struct codetag *ct, struct allocinfo_filter *filter,
  	    ct->lineno != filter->fields.lineno)
  		return false;
 
+	if (filter->mask & ALLOCINFO_FILTER_MASK_INACCURATE) {
+		inaccurate = !!(ct->flags & CODETAG_FLAG_INACCURATE);
+		if (inaccurate != !!(filter->fields.inaccurate))
+			return false;
+	}
+
  	if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE | ALLOCINFO_FILTER_MASK_MAX_SIZE)) {
  		if (!*fetched_counters) {
  			*counters = allocinfo_prefetch_counters(ct);
reviewer
#14 lore raw

Re: [PATCH v3 4/6] alloc_tag: add accuracy based filtering to ioctl

Quoted 30 lines · Hao Ge

Hi Abhishek

Quoted 14 lines · Abhishek Bapat

Extend the allocinfo filtering mechanism to allow users to filter tags based on their accuracy.

---
  include/uapi/linux/alloc_tag.h | 3 +++
  lib/alloc_tag.c                | 8 ++++++++

  2 files changed, 11 insertions(+)
include/uapi/linux/alloc_tag.h +0 -0
index 0e648192df4d..42445bdb11c5 100644

include/uapi/linux/alloc_tag.h struct allocinfo_tag { · line 23

Quoted 4 lines
include/uapi/linux/alloc_tag.h +1 -0
@@ -20,6 +20,7 @@ struct allocinfo_tag {
       char function[ALLOCINFO_STR_SIZE];
       char filename[ALLOCINFO_STR_SIZE];
       __u64 lineno;
+    __u64 inaccurate;

I was wondering if it would make sense to define inaccurate as a flags field

(e.g. __u64 flags with ALLOCINFO_TAG_F_INACCURATE (1 <<0)),

so that only bit 0 is used today and the upper bits are reserved for future use,

Quoted 8 lines

aligning with current kernel codebase.

This design also allows for better extensibility if we need to

add new flags for any reason in the future.

We also need to add flag validity checks if we go this route.

And I've reviewed the issue reported by Sashiko, and I think it's valid.

When we expand the allocinfo_tag_data structure

struct allocinfo_tag_data{

    char modname[64];

    char function[64];

    char filename[64];

    __u64 lineno;

    __u64 inaccurate;

    __u64 bytes;

    __u64 calls;

    __u8 accurate;
  /* padding */

}

I think user space may see two fields related to inaccuracy.

How do you like these modifications?

include/uapi/linux/alloc_tag.h +0 -0
@@ -20,7 +20,6 @@ struct allocinfo_tag {

     char function[ALLOCINFO_STR_SIZE];
     char filename[ALLOCINFO_STR_SIZE];
     __u64 lineno;
-    __u64 inaccurate;
 };

 /* The alignment ensures 32-bit compatible interfaces are not broken */ @@ -40,7 +39,7 @@ enum {
     ALLOCINFO_FILTER_FUNCTION,
     ALLOCINFO_FILTER_FILENAME,
     ALLOCINFO_FILTER_LINENO,
-    ALLOCINFO_FILTER_INACCURATE,
+    ALLOCINFO_FILTER_FLAGS,
     ALLOCINFO_FILTER_MIN_SIZE,
     ALLOCINFO_FILTER_MAX_SIZE,
     __ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
@@ -50,16 +49,20 @@ enum {
 #define ALLOCINFO_FILTER_MASK_FUNCTION        (1 << ALLOCINFO_FILTER_FUNCTION) #define ALLOCINFO_FILTER_MASK_FILENAME        (1 << ALLOCINFO_FILTER_FILENAME) #define ALLOCINFO_FILTER_MASK_LINENO        (1 << ALLOCINFO_FILTER_LINENO) -#define ALLOCINFO_FILTER_MASK_INACCURATE    (1 << ALLOCINFO_FILTER_INACCURATE) +#define ALLOCINFO_FILTER_MASK_FLAGS        (1 << ALLOCINFO_FILTER_FLAGS) #define ALLOCINFO_FILTER_MASK_MIN_SIZE        (1 << ALLOCINFO_FILTER_MIN_SIZE) #define ALLOCINFO_FILTER_MASK_MAX_SIZE        (1 << ALLOCINFO_FILTER_MAX_SIZE)

 #define ALLOCINFO_FILTER_MASKS \
     ((1 << (__ALLOCINFO_FILTER_LAST + 1)) - 1)

+#define ALLOCINFO_FILTER_F_INACCURATE    (1ULL << 0) +#define ALLOCINFO_FILTER_FLAGS_ALL ALLOCINFO_FILTER_F_INACCURATE +
 struct allocinfo_filter {
     __u64 mask; /* bitmask of the filter fields used */ struct allocinfo_tag fields;
+    __u64 flags; /* bitmask of ALLOCINFO_FILTER_F_* */ __u64 min_size;
     __u64 max_size;
 };

lib/alloc_tag.c +0 -0
@@ -249,8 +249,6 @@ static bool matches_filter(struct codetag *ct, struct allocinfo_filter *filter,

                struct alloc_tag_counters *counters, bool *fetched_counters)
 {
-    bool inaccurate;
-
     if (!filter || !filter->mask)
         return true;

@@ -277,10 +275,11 @@ static bool matches_filter(struct codetag *ct, struct allocinfo_filter *filter, ct->lineno != filter->fields.lineno)
         return false;

-    if (filter->mask & ALLOCINFO_FILTER_MASK_INACCURATE) { -        inaccurate = !!(ct->flags & CODETAG_FLAG_INACCURATE); -        if (inaccurate != !!(filter->fields.inaccurate)) -            return false;
+    if (filter->mask & ALLOCINFO_FILTER_MASK_FLAGS) { +        if (filter->flags & ALLOCINFO_FILTER_F_INACCURATE) { +            if (!(ct->flags & CODETAG_FLAG_INACCURATE)) +                return false;
+        }
     }

     if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE | ALLOCINFO_FILTER_MASK_MAX_SIZE)) { @@ -318,6 +317,10 @@ static int allocinfo_ioctl_get_at(struct seq_file *m, void __user *arg) if (params.filter.mask & ~ALLOCINFO_FILTER_MASKS)
         return -EINVAL;

+    if ((params.filter.mask & ALLOCINFO_FILTER_MASK_FLAGS) && +        (params.filter.flags & ~ALLOCINFO_FILTER_FLAGS_ALL)) +        return -EINVAL;
+
     if ((params.filter.mask & ALLOCINFO_FILTER_MASK_MIN_SIZE) && (params.filter.mask & ALLOCINFO_FILTER_MASK_MAX_SIZE) && params.filter.min_size > params.filter.max_size)

Thanks

Best Regards

Hao

Quoted 51 lines

Thanks

Best Regards

Hao

Quoted 43 lines
include/uapi/linux/alloc_tag.h +1 -0
   };
     /* The alignment ensures 32-bit compatible interfaces are not broken */
@@ -39,6 +40,7 @@ enum {
       ALLOCINFO_FILTER_FUNCTION,
       ALLOCINFO_FILTER_FILENAME,
       ALLOCINFO_FILTER_LINENO,
+    ALLOCINFO_FILTER_INACCURATE,
       ALLOCINFO_FILTER_MIN_SIZE,
       ALLOCINFO_FILTER_MAX_SIZE,

      __ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE

include/uapi/linux/alloc_tag.h +1 -0
@@ -48,6 +50,7 @@ enum {
   #define ALLOCINFO_FILTER_MASK_FUNCTION        (1 << ALLOCINFO_FILTER_FUNCTION)
   #define ALLOCINFO_FILTER_MASK_FILENAME        (1 << ALLOCINFO_FILTER_FILENAME)
   #define ALLOCINFO_FILTER_MASK_LINENO        (1 << ALLOCINFO_FILTER_LINENO)
+#define ALLOCINFO_FILTER_MASK_INACCURATE    (1 << 
 ALLOCINFO_FILTER_INACCURATE)
   #define ALLOCINFO_FILTER_MASK_MIN_SIZE        (1 << ALLOCINFO_FILTER_MIN_SIZE)
   #define ALLOCINFO_FILTER_MASK_MAX_SIZE        (1 << ALLOCINFO_FILTER_MAX_SIZE)

  diff --git a/lib/alloc_tag.c b/lib/alloc_tag.c
index ddc6946f56ab..cbcd12c4ef9c 100644

lib/alloc_tag.c +2 -0
@@ -249,6 +249,8 @@ static bool matches_filter(struct codetag *ct, 
 struct allocinfo_filter *filter,
                  struct alloc_tag_counters *counters,
                  bool *fetched_counters)
   {
+    bool inaccurate;
+
       if (!filter || !filter->mask)
           return true;

  @@ -275,6 +277,12 @@ static bool matches_filter(struct codetag *ct, struct allocinfo_filter *filter, ct->lineno != filter->fields.lineno)
          return false;
  +    if (filter->mask & ALLOCINFO_FILTER_MASK_INACCURATE) {
+        inaccurate = !!(ct->flags & CODETAG_FLAG_INACCURATE);
+        if (inaccurate != !!(filter->fields.inaccurate))
+            return false;
+    }
+
      if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE | ALLOCINFO_FILTER_MASK_MAX_SIZE)) { if (!*fetched_counters) {
              *counters = allocinfo_prefetch_counters(ct);

#15 lore raw

Re: [PATCH v3 4/6] alloc_tag: add accuracy based filtering to ioctl

Quoted 65 lines · Hao Ge
Quoted 33 lines · Hao Ge

Hi Abhishek

Quoted 15 lines · Abhishek Bapat

Extend the allocinfo filtering mechanism to allow users to filter tags based on their accuracy.

---
  include/uapi/linux/alloc_tag.h | 3 +++
  lib/alloc_tag.c                | 8 ++++++++
  2 files changed, 11 insertions(+)
include/uapi/linux/alloc_tag.h +0 -0
index 0e648192df4d..42445bdb11c5 100644

include/uapi/linux/alloc_tag.h struct allocinfo_tag { · line 23

Quoted 4 lines
include/uapi/linux/alloc_tag.h +1 -0
@@ -20,6 +20,7 @@ struct allocinfo_tag {
      char function[ALLOCINFO_STR_SIZE];
      char filename[ALLOCINFO_STR_SIZE];
      __u64 lineno;
+    __u64 inaccurate;

I was wondering if it would make sense to define inaccurate as a flags field

(e.g. __u64 flags with ALLOCINFO_TAG_F_INACCURATE (1 <<0)),

so that only bit 0 is used today and the upper bits are reserved for future use,

Quoted 8 lines

aligning with current kernel codebase.

This design also allows for better extensibility if we need to

add new flags for any reason in the future.

We also need to add flag validity checks if we go this route.

And I've reviewed the issue reported by Sashiko, and I think it's valid.

When we expand the allocinfo_tag_data structure

struct allocinfo_tag_data{

     char modname[64];

     char function[64];

     char filename[64];

     __u64 lineno;

     __u64 inaccurate;

     __u64 bytes;

     __u64 calls;

     __u8 accurate;
Quoted 5 lines

/* padding */

}

I think user space may see two fields related to inaccuracy.

Yes but one field (inside allocinfo_tag) is the input parameter which user provides to specify the filtering criteria and the other is the returned tag information. It's similar to any other tag attribute which you can be included in the filters.

Quoted 66 lines

How do you like these modifications?

include/uapi/linux/alloc_tag.h +6 -3
@@ -20,7 +20,6 @@ struct allocinfo_tag {
      char function[ALLOCINFO_STR_SIZE];
      char filename[ALLOCINFO_STR_SIZE];
      __u64 lineno;
-    __u64 inaccurate;
  };
 
  /* The alignment ensures 32-bit compatible interfaces are not broken */
@@ -40,7 +39,7 @@ enum {
      ALLOCINFO_FILTER_FUNCTION,
      ALLOCINFO_FILTER_FILENAME,
      ALLOCINFO_FILTER_LINENO,
-    ALLOCINFO_FILTER_INACCURATE,
+    ALLOCINFO_FILTER_FLAGS,
      ALLOCINFO_FILTER_MIN_SIZE,
      ALLOCINFO_FILTER_MAX_SIZE,
      __ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
@@ -50,16 +49,20 @@ enum {
  #define ALLOCINFO_FILTER_MASK_FUNCTION        (1 <<
 ALLOCINFO_FILTER_FUNCTION)
  #define ALLOCINFO_FILTER_MASK_FILENAME        (1 <<
 ALLOCINFO_FILTER_FILENAME)
  #define ALLOCINFO_FILTER_MASK_LINENO        (1 << ALLOCINFO_FILTER_LINENO)
-#define ALLOCINFO_FILTER_MASK_INACCURATE    (1 <<
 ALLOCINFO_FILTER_INACCURATE)
+#define ALLOCINFO_FILTER_MASK_FLAGS        (1 << ALLOCINFO_FILTER_FLAGS)
  #define ALLOCINFO_FILTER_MASK_MIN_SIZE        (1 <<
 ALLOCINFO_FILTER_MIN_SIZE)
  #define ALLOCINFO_FILTER_MASK_MAX_SIZE        (1 <<
 ALLOCINFO_FILTER_MAX_SIZE)
 
  #define ALLOCINFO_FILTER_MASKS \
      ((1 << (__ALLOCINFO_FILTER_LAST + 1)) - 1)
 
+#define ALLOCINFO_FILTER_F_INACCURATE    (1ULL << 0)
+#define ALLOCINFO_FILTER_FLAGS_ALL ALLOCINFO_FILTER_F_INACCURATE
+
  struct allocinfo_filter {
      __u64 mask; /* bitmask of the filter fields used */
      struct allocinfo_tag fields;
+    __u64 flags; /* bitmask of ALLOCINFO_FILTER_F_* */
      __u64 min_size;
      __u64 max_size;
  };
lib/alloc_tag.c +0 -2
@@ -249,8 +249,6 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,
                 struct alloc_tag_counters *counters,
                 bool *fetched_counters)
  {
-    bool inaccurate;
-
      if (!filter || !filter->mask)
          return true;
@@ -277,10 +275,11 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,

lib/alloc_tag.c static bool matches_filter(struct codetag *ct, · line 281

Quoted 10 lines
lib/alloc_tag.c +3 -4
          ct->lineno != filter->fields.lineno)
          return false;
 
-    if (filter->mask & ALLOCINFO_FILTER_MASK_INACCURATE) {
-        inaccurate = !!(ct->flags & CODETAG_FLAG_INACCURATE);
-        if (inaccurate != !!(filter->fields.inaccurate))
-            return false;
+    if (filter->mask & ALLOCINFO_FILTER_MASK_FLAGS) {
+        if (filter->flags & ALLOCINFO_FILTER_F_INACCURATE) {
+            if (!(ct->flags & CODETAG_FLAG_INACCURATE))

How would you filter records which have only accurate data?

Overall I would prefer ALLOCINFO_FILTER_MASK_INACCURATE rather than ALLOCINFO_FILTER_MASK_FLAGS. The fact that this attribute is a single-bit flag is a technical detail. It's still a tag attribuite like file and module names and IMO deserves its own filter.

Quoted 86 lines
lib/alloc_tag.c +2 -0
+                return false;
+        }
      }
 
      if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE |

ALLOCINFO_FILTER_MASK_MAX_SIZE)) {

lib/alloc_tag.c +4 -0
@@ -318,6 +317,10 @@ static int allocinfo_ioctl_get_at(struct seq_file
 *m, void __user *arg)
      if (params.filter.mask & ~ALLOCINFO_FILTER_MASKS)
          return -EINVAL;
 
+    if ((params.filter.mask & ALLOCINFO_FILTER_MASK_FLAGS) &&
+        (params.filter.flags & ~ALLOCINFO_FILTER_FLAGS_ALL))
+        return -EINVAL;
+
      if ((params.filter.mask & ALLOCINFO_FILTER_MASK_MIN_SIZE) &&
          (params.filter.mask & ALLOCINFO_FILTER_MASK_MAX_SIZE) &&

params.filter.min_size > params.filter.max_size)

Thanks

Best Regards

Hao

Quoted 59 lines

Thanks

Best Regards

Hao

Quoted 51 lines
include/uapi/linux/alloc_tag.h +0 -0
  };
    /* The alignment ensures 32-bit compatible interfaces are not

broken */

include/uapi/linux/alloc_tag.h +2 -0
@@ -39,6 +40,7 @@ enum {
      ALLOCINFO_FILTER_FUNCTION,
      ALLOCINFO_FILTER_FILENAME,
      ALLOCINFO_FILTER_LINENO,
+    ALLOCINFO_FILTER_INACCURATE,
      ALLOCINFO_FILTER_MIN_SIZE,
      ALLOCINFO_FILTER_MAX_SIZE,
      __ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
@@ -48,6 +50,7 @@ enum {
  #define ALLOCINFO_FILTER_MASK_FUNCTION        (1 <<
 ALLOCINFO_FILTER_FUNCTION)
  #define ALLOCINFO_FILTER_MASK_FILENAME        (1 <<
 ALLOCINFO_FILTER_FILENAME)
  #define ALLOCINFO_FILTER_MASK_LINENO        (1 <<
 ALLOCINFO_FILTER_LINENO)
+#define ALLOCINFO_FILTER_MASK_INACCURATE    (1 <<

ALLOCINFO_FILTER_INACCURATE)
#define ALLOCINFO_FILTER_MASK_MIN_SIZE (1 <<
ALLOCINFO_FILTER_MIN_SIZE)
#define ALLOCINFO_FILTER_MASK_MAX_SIZE (1 <<
ALLOCINFO_FILTER_MAX_SIZE)
diff --git a/lib/alloc_tag.c b/lib/alloc_tag.c
index ddc6946f56ab..cbcd12c4ef9c 100644

lib/alloc_tag.c +2 -0
@@ -249,6 +249,8 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,
                 struct alloc_tag_counters *counters,
                 bool *fetched_counters)
  {
+    bool inaccurate;
+
      if (!filter || !filter->mask)
          return true;

@@ -275,6 +277,12 @@ static bool matches_filter(struct codetag *ct,
struct allocinfo_filter *filter,

          ct->lineno != filter->fields.lineno)
          return false;

+ if (filter->mask & ALLOCINFO_FILTER_MASK_INACCURATE) {

lib/alloc_tag.c +5 -0
+        inaccurate = !!(ct->flags & CODETAG_FLAG_INACCURATE);
+        if (inaccurate != !!(filter->fields.inaccurate))
+            return false;
+    }
+
      if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE |
ALLOCINFO_FILTER_MASK_MAX_SIZE)) {
          if (!*fetched_counters) {
              *counters = allocinfo_prefetch_counters(ct);
#26 lore raw
In reply to Andrew Morton
Quoted 20 lines · Andrew Morton
Quoted 12 lines · On Fri, 5 Jun 2026 23:36:45 +0000 Abhishek Bapat <[email protected]>…

Currently, memory allocation profiling data is primarily exposed through /proc/allocinfo. While useful for manual inspection, this text-based interface poses challenges for production monitoring and large-scale analysis:

1. Userspace must parse large amounts of text to extract specific fields.
2. To find specific tags, userspace must read the entire dataset, requiring many context switches and high data copying.
3. The kernel currently aggregates per-CPU counters for every allocation size, even those the user intends to filter out immediately.

Quoted 4 lines

This series introduces a new IOCTL-based binary interface for allocinfo that supports kernel-side filtering. By allowing the user to specify a filter mask, we significantly reduce the work performed in-kernel and the amount of data transferred to userspace.

Quoted 4 lines

Thanks. AI review found several things - you'll want to address at least the first few.

        https://sashiko.dev/#/patchset/[email protected]

All, please note I missed attaching the reason for choosing the IOCTL mechanism to this cover letter, but I will attach it to the v4 patchset cover letter along with other changes. Thanks!

#3 lore raw

Re: [PATCH v3 1/6] alloc_tag: add ioctl to /proc/allocinfo

In reply to Hao Ge
Quoted 105 lines · Hao Ge

Hi Suren and Abhishek

Thanks for the new version.

Quoted 91 lines · Abhishek Bapat

From: Suren Baghdasaryan <[email protected]>

Add the following ioctl commands for /proc/allocinfo file:

ALLOCINFO_IOC_CONTENT_ID - gets content identifier which can be used to check whether the file content has changed specifically due to module load/unload. Every time a module is loaded / unloaded, the returned value will be different. By comparing the identifier value at the beginning and at the end of the content retrieval operation, users can validate retrieved information for consistency.

ALLOCINFO_IOC_GET_AT - gets the record at the specified position. This is the position of a record in /proc/allocinfo.

ALLOCINFO_IOC_GET_NEXT - gets the record next to the last retrieved one. If no records were previously retrieved, returns the first record.

---
  Documentation/mm/allocation-profiling.rst     |   5 +
  .../userspace-api/ioctl/ioctl-number.rst      |   2 +
  MAINTAINERS                                   |   1 +
  include/linux/codetag.h                       |   2 +
  include/uapi/linux/alloc_tag.h                |  54 ++++
  lib/alloc_tag.c                               | 232 +++++++++++++++++-
  lib/codetag.c                                 |  18 ++
  7 files changed, 312 insertions(+), 2 deletions(-)

create mode 100644 include/uapi/linux/alloc_tag.h

Documentation/mm/allocation-profiling.rst +5 -0
index 5389d241176a..c3a28467955f 100644
@@ -46,6 +46,11 @@ sysctl:
  Runtime info:
    /proc/allocinfo
 
+  Profiling data can be retrieved either by reading `/proc/allocinfo` directly as
+  text or programmatically via `ioctl()` calls defined in `<uapi/linux/alloc_tag.h>`.
+  The ioctl interface supports structured binary data extraction as well as filtering
+  by module name, function, file, line number, accuracy, or allocation size limits.
+
  Example output::
 
    root@moria-kvm:~# sort -g /proc/allocinfo|tail|numfmt --to=iec
Documentation/userspace-api/ioctl/ioctl-number.rst +2 -0
index 331223761fff..84f6808a8578 100644
@@ -349,6 +349,8 @@ Code  Seq#    Include File                                             Comments
                                                                         <mailto:[email protected]>
  0xA5  20-2F  linux/surface_aggregator/dtx.h                            Microsoft Surface DTX driver
                                                                         <mailto:[email protected]>
+0xA6  00-0F  uapi/linux/alloc_tag.h                                    Memory allocation profiling
+                                                                       <mailto:[email protected]>
  0xAA  00-3F  linux/uapi/linux/userfaultfd.h
  0xAB  00-1F  linux/nbd.h
  0xAC  00-1F  linux/raw.h
MAINTAINERS +1 -0
index a31f6f207afd..77f3fc487691 100644
@@ -16711,6 +16711,7 @@ S:    Maintained
  F:  Documentation/mm/allocation-profiling.rst
  F:  include/linux/alloc_tag.h
  F:  include/linux/pgalloc_tag.h
+F:   include/uapi/linux/alloc_tag.h
  F:  lib/alloc_tag.c
 
  MEMORY CONTROLLER DRIVERS
include/linux/codetag.h +2 -0
index ddae7484ca45..a25a085c2df1 100644
@@ -77,6 +77,8 @@ struct codetag_iterator {
  void codetag_lock_module_list(struct codetag_type *cttype);
  bool codetag_trylock_module_list(struct codetag_type *cttype);
  void codetag_unlock_module_list(struct codetag_type *cttype);
+unsigned long codetag_get_content_id(struct codetag_type *cttype);
+unsigned int codetag_get_count(struct codetag_type *cttype);
  struct codetag_iterator codetag_get_ct_iter(struct codetag_type *cttype);
  struct codetag *codetag_next_ct(struct codetag_iterator *iter);
 
include/uapi/linux/alloc_tag.h new file +0 -0
new file mode 100644
index 000000000000..901199bad514

include/uapi/linux/alloc_tag.h line 3

Quoted 3 lines
include/uapi/linux/alloc_tag.h new file +3 -0
@@ -0,0 +1,54 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+/*
+ *  include/linux/alloc_tag.h

nit: it should be include/uapi/linux/alloc_tag.h

Quoted 3 lines

(I guess you may have missed the comment I brought up before. It is not a critical problem though.)

Apologies, I missed that comment earlier. Included in the v4 patchset. Thanks for bringing this up.

Quoted 376 lines
Quoted 357 lines
include/uapi/linux/alloc_tag.h new file +51 -0
+ */
+
+#ifndef _UAPI_ALLOC_TAG_H
+#define _UAPI_ALLOC_TAG_H
+
+#include <linux/types.h>
+
+#define ALLOCINFO_STR_SIZE   64
+
+struct allocinfo_content_id {
+     __u64 id;
+};
+
+struct allocinfo_tag {
+     /* Longer names are trimmed */
+     char modname[ALLOCINFO_STR_SIZE];
+     char function[ALLOCINFO_STR_SIZE];
+     char filename[ALLOCINFO_STR_SIZE];
+     __u64 lineno;
+};
+
+/* The alignment ensures 32-bit compatible interfaces are not broken */
+struct allocinfo_counter {
+     __u64 bytes;
+     __u64 calls;
+     __u8 accurate;
+} __attribute__((aligned(8)));
+
+struct allocinfo_tag_data {
+     struct allocinfo_tag tag;
+     struct allocinfo_counter counter;
+};
+
+struct allocinfo_get_at {
+     __u64 pos;      /* input */
+     struct allocinfo_tag_data data;
+};
+
+#define _ALLOCINFO_IOC_CONTENT_ID    0
+#define _ALLOCINFO_IOC_GET_AT                1
+#define _ALLOCINFO_IOC_GET_NEXT              2
+
+#define ALLOCINFO_IOC_BASE           0xA6
+#define ALLOCINFO_IOC_CONTENT_ID     _IOR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_CONTENT_ID,     \
+                                          struct allocinfo_content_id)
+#define ALLOCINFO_IOC_GET_AT         _IOWR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_GET_AT,        \
+                                           struct allocinfo_get_at)
+#define ALLOCINFO_IOC_GET_NEXT               _IOR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_GET_NEXT,       \
+                                          struct allocinfo_tag_data)
+
+#endif /* _UAPI_ALLOC_TAG_H */
lib/alloc_tag.c +230 -2
index d9be1cf5187d..a0577215eb3d 100644
@@ -5,6 +5,7 @@
  #include <linux/gfp.h>
  #include <linux/kallsyms.h>
  #include <linux/module.h>
+#include <linux/mutex.h>
  #include <linux/page_ext.h>
  #include <linux/pgalloc_tag.h>
  #include <linux/proc_fs.h>
@@ -14,6 +15,7 @@
  #include <linux/string_choices.h>
  #include <linux/vmalloc.h>
  #include <linux/kmemleak.h>
+#include <uapi/linux/alloc_tag.h>
 
  #define ALLOCINFO_FILE_NAME         "allocinfo"
  #define MODULE_ALLOC_TAG_VMAP_SIZE  (100000UL * sizeof(struct alloc_tag))
@@ -47,6 +49,10 @@ struct allocinfo_private {
      struct codetag_iterator iter;
      struct codetag_iterator reported_iter;
      bool print_header;
+     /* ioctl uses a separate iterator not to interfere with reads */
+     struct codetag_iterator ioctl_iter;
+     bool positioned; /* seq_open_private() sets to 0 */
+     struct mutex ioctl_lock;
  };
 
  static void *allocinfo_start(struct seq_file *m, loff_t *pos)
@@ -130,6 +136,229 @@ static const struct seq_operations allocinfo_seq_op = {
      .show   = allocinfo_show,
  };
 
+/*
+ * Initializes seq_file operations and allocates private state when opening
+ * the /proc/allocinfo procfs entry.
+ */
+static int allocinfo_open(struct inode *inode, struct file *file)
+{
+     int ret;
+
+     ret = seq_open_private(file, &allocinfo_seq_op,
+                            sizeof(struct allocinfo_private));
+     if (!ret) {
+             struct seq_file *m = file->private_data;
+             struct allocinfo_private *priv = m->private;
+
+             mutex_init(&priv->ioctl_lock);
+     }
+     return ret;
+}
+
+/*
+ * Cleans up the seq_file state and frees up the private state allocated in
+ * allocinfo_open() when closing the /proc/allocinfo file descriptor.
+ */
+static int allocinfo_release(struct inode *inode, struct file *file)
+{
+     return seq_release_private(inode, file);
+}
+
+/*
+ * Returns a pointer to the suffix of a string so that its length fits within
+ * ALLOCINFO_STR_SIZE, preserving the trailing characters.
+ */
+static const char *allocinfo_str(const char *str)
+{
+     size_t len = strlen(str);
+
+     /* Keep an extra space for the trailing NULL. */
+     if (len >= ALLOCINFO_STR_SIZE)
+             str += (len - ALLOCINFO_STR_SIZE) + 1;
+     return str;
+}
+
+/* Copy a string and trim from the beginning if it's too long */
+static void allocinfo_copy_str(char *dest, const char *src)
+{
+     strscpy_pad(dest, allocinfo_str(src), ALLOCINFO_STR_SIZE);
+}
+
+/*
+ * Populates the UAPI allocinfo_tag_data structure with active runtime
+ * profiling counters extracted from the given kernel codetag.
+ */
+static void allocinfo_to_params(struct codetag *ct,
+                             struct allocinfo_tag_data *data)
+{
+     struct alloc_tag *tag = ct_to_alloc_tag(ct);
+     struct alloc_tag_counters counter = alloc_tag_read(tag);
+
+     if (ct->modname)
+             allocinfo_copy_str(data->tag.modname, ct->modname);
+     else
+             data->tag.modname[0] = '\0';
+     allocinfo_copy_str(data->tag.function, ct->function);
+     allocinfo_copy_str(data->tag.filename, ct->filename);
+     data->tag.lineno = ct->lineno;
+     data->counter.bytes = counter.bytes;
+     data->counter.calls = counter.calls;
+     data->counter.accurate = !alloc_tag_is_inaccurate(tag);
+}
+
+/*
+ * Retrieves the unique content ID representing the current allocation tag module
+ * layout, allowing userspace to detect if modules were loaded / unloaded.
+ */
+static int allocinfo_ioctl_get_content_id(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_content_id params;
+
+     codetag_lock_module_list(alloc_tag_cttype);
+     params.id = codetag_get_content_id(alloc_tag_cttype);
+     codetag_unlock_module_list(alloc_tag_cttype);
+     if (copy_to_user(arg, &params, sizeof(params)))
+             return -EFAULT;
+
+     return 0;
+}
+
+/*
+ * Seeks the ioctl iterator to the specified 0-indexed tag position, reads its
+ * profiling data and returns it to userspace.
+ */
+static int allocinfo_ioctl_get_at(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_private *priv;
+     struct codetag *ct;
+     __u64 pos;
+     struct allocinfo_get_at params = {0};
+
+     if (copy_from_user(&params, arg, sizeof(params)))
+             return -EFAULT;
+
+     priv = m->private;
+     pos = params.pos;
+
+     mutex_lock(&priv->ioctl_lock);
+     codetag_lock_module_list(alloc_tag_cttype);
+
+     if (pos >= codetag_get_count(alloc_tag_cttype)) {
+             codetag_unlock_module_list(alloc_tag_cttype);
+             mutex_unlock(&priv->ioctl_lock);
+             return -ENOENT;
+     }
+
+     /* Find the codetag */
+     priv->ioctl_iter = codetag_get_ct_iter(alloc_tag_cttype);
+     ct = codetag_next_ct(&priv->ioctl_iter);
+     while (ct && pos--)
+             ct = codetag_next_ct(&priv->ioctl_iter);
+     if (ct) {
+             allocinfo_to_params(ct, &params.data);
+             priv->positioned = true;
+     }
+
+     codetag_unlock_module_list(alloc_tag_cttype);
+     mutex_unlock(&priv->ioctl_lock);
+
+     if (!ct)
+             return -ENOENT;
+
+     if (copy_to_user(arg, &params, sizeof(params)))
+             return -EFAULT;
+
+     return 0;
+}
+
+/*
+ * Advances the ioctl iterator to the next allocation tag in the sequence and
+ * returns its profiling data to userspace.
+ */
+static int allocinfo_ioctl_get_next(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_private *priv;
+     struct codetag *ct;
+     struct allocinfo_tag_data params;
+     int ret = 0;
+
+     memset(&params, 0, sizeof(params));
+     priv = m->private;
+
+     mutex_lock(&priv->ioctl_lock);
+     codetag_lock_module_list(alloc_tag_cttype);
+
+     if (!priv->positioned) {
+             priv->ioctl_iter = codetag_get_ct_iter(alloc_tag_cttype);
+             priv->positioned = true;
+     }
+
+     ct = codetag_next_ct(&priv->ioctl_iter);
+     if (ct)
+             allocinfo_to_params(ct, &params);
+
+     if (!ct) {
+             priv->positioned = false;
+             ret = -ENOENT;
+     }
+     codetag_unlock_module_list(alloc_tag_cttype);
+     mutex_unlock(&priv->ioctl_lock);
+
+     if (ret == 0) {
+             if (copy_to_user(arg, &params, sizeof(params)))
+                     return -EFAULT;
+     }
+     return ret;
+}
+
+/*
+ * Entry point ioctl function for /proc/allocinfo routing requests to fetch the
+ * layout content ID, seek to a specific tag, or read sequential tags.
+ */
+static long allocinfo_ioctl(struct file *file, unsigned int cmd,
+                         unsigned long __arg)
+{
+     void __user *arg = (void __user *)__arg;
+     int ret;
+
+     switch (cmd) {
+     case ALLOCINFO_IOC_CONTENT_ID:
+             ret = allocinfo_ioctl_get_content_id(file->private_data, arg);
+             break;
+     case ALLOCINFO_IOC_GET_AT:
+             ret = allocinfo_ioctl_get_at(file->private_data, arg);
+             break;
+     case ALLOCINFO_IOC_GET_NEXT:
+             ret = allocinfo_ioctl_get_next(file->private_data, arg);
+             break;
+     default:
+             ret = -ENOIOCTLCMD;
+             break;
+     }
+
+     return ret;
+}
+
+#ifdef CONFIG_COMPAT
+static long allocinfo_compat_ioctl(struct file *file, unsigned int cmd,
+                                unsigned long arg)
+{
+     return allocinfo_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
+}
+#endif
+
+static const struct proc_ops allocinfo_proc_ops = {
+     .proc_open              = allocinfo_open,
+     .proc_read_iter         = seq_read_iter,
+     .proc_lseek             = seq_lseek,
+     .proc_release           = allocinfo_release,
+     .proc_ioctl             = allocinfo_ioctl,
+#ifdef CONFIG_COMPAT
+     .proc_compat_ioctl      = allocinfo_compat_ioctl,
+#endif
+
+};
+
  size_t alloc_tag_top_users(struct codetag_bytes *tags, size_t count, bool can_sleep)
  {
      struct codetag_iterator iter;
@@ -993,8 +1222,7 @@ static int __init alloc_tag_init(void)
              return 0;
      }
 
-     if (!proc_create_seq_private(ALLOCINFO_FILE_NAME, 0400, NULL, &allocinfo_seq_op,
-                                  sizeof(struct allocinfo_private), NULL)) {
+     if (!proc_create(ALLOCINFO_FILE_NAME, 0400, NULL, &allocinfo_proc_ops)) {
              pr_err("Failed to create %s file\n", ALLOCINFO_FILE_NAME);
              shutdown_mem_profiling(false);
              return -ENOMEM;
lib/codetag.c +16 -0
index 4001a7ea6675..a9cda4c962a3 100644
@@ -19,6 +19,8 @@ struct codetag_type {
      struct codetag_type_desc desc;
      /* generates unique sequence number for module load */
      unsigned long next_mod_seq;
+     /* bumped on every module load and unload */
+     unsigned long content_id;
  };
 
  struct codetag_range {
@@ -50,6 +52,20 @@ void codetag_unlock_module_list(struct codetag_type *cttype)
      up_read(&cttype->mod_lock);
  }
 
+unsigned long codetag_get_content_id(struct codetag_type *cttype)
+{
+     lockdep_assert_held(&cttype->mod_lock);
+
+     return cttype->content_id;
+}
+
+unsigned int codetag_get_count(struct codetag_type *cttype)
+{
+     lockdep_assert_held(&cttype->mod_lock);
+
+     return cttype->count;
+}
+
  struct codetag_iterator codetag_get_ct_iter(struct codetag_type *cttype)
  {
      struct codetag_iterator iter = {

lib/codetag.c static int codetag_module_init(struct codetag_type *cttype, struct module *mod) · line 223

Quoted 4 lines
lib/codetag.c +1 -0
@@ -204,6 +220,7 @@ static int codetag_module_init(struct codetag_type *cttype, struct module *mod)
 
      down_write(&cttype->mod_lock);
      cmod->mod_seq = ++cttype->next_mod_seq;
+     ++cttype->content_id;

I have a comment on the content_id bump placement.

++cttype->content_id is placed before idr_alloc and the module_load

callback. If idr_alloc fails or module_load returns an error

(While the chance of this occurring is very low.), the idr entry gets

rolled back but content_id has already been bumped. The actual

content didn't change in this case, so userspace would see a

different content_id and assume the data is inconsistent when it

Quoted 8 lines

isn't.

Thanks

Best Regards

Hao

While I agree with your comment, I decided to place the counter increment there because the chance of failure is low. Furthermore, even if it falsely invalidates user data, the user will simply query the content again. This placement also aligns with where the previously used field (cttype->next_mod_seq) was incremented. Let me know if you still think I should move it. Thanks!

Quoted 12 lines
Quoted 12 lines
lib/codetag.c +1 -0
      mod_id = idr_alloc(&cttype->mod_idr, cmod, 0, 0, GFP_KERNEL);
      if (mod_id >= 0) {
              if (cttype->desc.module_load) {
@@ -368,6 +385,7 @@ void codetag_unload_module(struct module *mod)
                      cttype->count -= range_size(cttype, &cmod->range);
                      idr_remove(&cttype->mod_idr, mod_id);
                      kfree(cmod);
+                     ++cttype->content_id;
              }
              up_write(&cttype->mod_lock);
              if (found && cttype->desc.free_section_mem)
#27 lore raw
In reply to Abhishek Bapat
Quoted 22 lines · Abhishek Bapat
Quoted 20 lines · Andrew Morton
Quoted 16 lines · On Fri, 5 Jun 2026 23:36:45 +0000 Abhishek Bapat <[email protected]>…

Currently, memory allocation profiling data is primarily exposed through /proc/allocinfo. While useful for manual inspection, this text-based interface poses challenges for production monitoring and large-scale analysis:

1. Userspace must parse large amounts of text to extract specific fields.
2. To find specific tags, userspace must read the entire dataset, requiring many context switches and high data copying.
3. The kernel currently aggregates per-CPU counters for every allocation size, even those the user intends to filter out immediately.

This series introduces a new IOCTL-based binary interface for allocinfo that supports kernel-side filtering. By allowing the user to specify a filter mask, we significantly reduce the work performed in-kernel and the amount of data transferred to userspace.

Quoted 8 lines
Quoted 4 lines

Thanks. AI review found several things - you'll want to address at least the first few.

        https://sashiko.dev/#/patchset/[email protected]

All, please note I missed attaching the reason for choosing the IOCTL mechanism to this cover letter, but I will attach it to the v4 patchset cover letter along with other changes. Thanks!

Can you please add it here now so that we can review that?

#16 lore raw

Re: [PATCH v3 4/6] alloc_tag: add accuracy based filtering to ioctl

In reply to Suren Baghdasaryan

Btw, Sashiko left a comment in this patch stating that the value of "inaccurate" is echoed back to the user. But since it's an input-only parameter, that is expected. Changing it in the kernel would be unexpected. Hence, I will ignore that comment.

Quoted 250 lines · Suren Baghdasaryan
Quoted 65 lines · Hao Ge
Quoted 33 lines · Hao Ge

Hi Abhishek

Quoted 15 lines · Abhishek Bapat

Extend the allocinfo filtering mechanism to allow users to filter tags based on their accuracy.

---
  include/uapi/linux/alloc_tag.h | 3 +++
  lib/alloc_tag.c                | 8 ++++++++
  2 files changed, 11 insertions(+)
include/uapi/linux/alloc_tag.h +0 -0
index 0e648192df4d..42445bdb11c5 100644

include/uapi/linux/alloc_tag.h struct allocinfo_tag { · line 23

Quoted 4 lines
include/uapi/linux/alloc_tag.h +1 -0
@@ -20,6 +20,7 @@ struct allocinfo_tag {
      char function[ALLOCINFO_STR_SIZE];
      char filename[ALLOCINFO_STR_SIZE];
      __u64 lineno;
+    __u64 inaccurate;

I was wondering if it would make sense to define inaccurate as a flags field

(e.g. __u64 flags with ALLOCINFO_TAG_F_INACCURATE (1 <<0)),

so that only bit 0 is used today and the upper bits are reserved for future use,

Quoted 8 lines

aligning with current kernel codebase.

This design also allows for better extensibility if we need to

add new flags for any reason in the future.

We also need to add flag validity checks if we go this route.

And I've reviewed the issue reported by Sashiko, and I think it's valid.

When we expand the allocinfo_tag_data structure

struct allocinfo_tag_data{

     char modname[64];

     char function[64];

     char filename[64];

     __u64 lineno;

     __u64 inaccurate;

     __u64 bytes;

     __u64 calls;

     __u8 accurate;
Quoted 5 lines

/* padding */

}

I think user space may see two fields related to inaccuracy.

Yes but one field (inside allocinfo_tag) is the input parameter which user provides to specify the filtering criteria and the other is the returned tag information. It's similar to any other tag attribute which you can be included in the filters.

Quoted 66 lines

How do you like these modifications?

include/uapi/linux/alloc_tag.h +6 -3
@@ -20,7 +20,6 @@ struct allocinfo_tag {
      char function[ALLOCINFO_STR_SIZE];
      char filename[ALLOCINFO_STR_SIZE];
      __u64 lineno;
-    __u64 inaccurate;
  };
 
  /* The alignment ensures 32-bit compatible interfaces are not broken */
@@ -40,7 +39,7 @@ enum {
      ALLOCINFO_FILTER_FUNCTION,
      ALLOCINFO_FILTER_FILENAME,
      ALLOCINFO_FILTER_LINENO,
-    ALLOCINFO_FILTER_INACCURATE,
+    ALLOCINFO_FILTER_FLAGS,
      ALLOCINFO_FILTER_MIN_SIZE,
      ALLOCINFO_FILTER_MAX_SIZE,
      __ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
@@ -50,16 +49,20 @@ enum {
  #define ALLOCINFO_FILTER_MASK_FUNCTION        (1 <<
 ALLOCINFO_FILTER_FUNCTION)
  #define ALLOCINFO_FILTER_MASK_FILENAME        (1 <<
 ALLOCINFO_FILTER_FILENAME)
  #define ALLOCINFO_FILTER_MASK_LINENO        (1 << ALLOCINFO_FILTER_LINENO)
-#define ALLOCINFO_FILTER_MASK_INACCURATE    (1 <<
 ALLOCINFO_FILTER_INACCURATE)
+#define ALLOCINFO_FILTER_MASK_FLAGS        (1 << ALLOCINFO_FILTER_FLAGS)
  #define ALLOCINFO_FILTER_MASK_MIN_SIZE        (1 <<
 ALLOCINFO_FILTER_MIN_SIZE)
  #define ALLOCINFO_FILTER_MASK_MAX_SIZE        (1 <<
 ALLOCINFO_FILTER_MAX_SIZE)
 
  #define ALLOCINFO_FILTER_MASKS \
      ((1 << (__ALLOCINFO_FILTER_LAST + 1)) - 1)
 
+#define ALLOCINFO_FILTER_F_INACCURATE    (1ULL << 0)
+#define ALLOCINFO_FILTER_FLAGS_ALL ALLOCINFO_FILTER_F_INACCURATE
+
  struct allocinfo_filter {
      __u64 mask; /* bitmask of the filter fields used */
      struct allocinfo_tag fields;
+    __u64 flags; /* bitmask of ALLOCINFO_FILTER_F_* */
      __u64 min_size;
      __u64 max_size;
  };
lib/alloc_tag.c +0 -2
@@ -249,8 +249,6 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,
                 struct alloc_tag_counters *counters,
                 bool *fetched_counters)
  {
-    bool inaccurate;
-
      if (!filter || !filter->mask)
          return true;
@@ -277,10 +275,11 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,

lib/alloc_tag.c static bool matches_filter(struct codetag *ct, · line 281

Quoted 10 lines
lib/alloc_tag.c +3 -4
          ct->lineno != filter->fields.lineno)
          return false;
 
-    if (filter->mask & ALLOCINFO_FILTER_MASK_INACCURATE) {
-        inaccurate = !!(ct->flags & CODETAG_FLAG_INACCURATE);
-        if (inaccurate != !!(filter->fields.inaccurate))
-            return false;
+    if (filter->mask & ALLOCINFO_FILTER_MASK_FLAGS) {
+        if (filter->flags & ALLOCINFO_FILTER_F_INACCURATE) {
+            if (!(ct->flags & CODETAG_FLAG_INACCURATE))

How would you filter records which have only accurate data?

Overall I would prefer ALLOCINFO_FILTER_MASK_INACCURATE rather than ALLOCINFO_FILTER_MASK_FLAGS. The fact that this attribute is a single-bit flag is a technical detail. It's still a tag attribuite like file and module names and IMO deserves its own filter.

Quoted 86 lines
lib/alloc_tag.c +2 -0
+                return false;
+        }
      }
 
      if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE |

ALLOCINFO_FILTER_MASK_MAX_SIZE)) {

lib/alloc_tag.c +4 -0
@@ -318,6 +317,10 @@ static int allocinfo_ioctl_get_at(struct seq_file
 *m, void __user *arg)
      if (params.filter.mask & ~ALLOCINFO_FILTER_MASKS)
          return -EINVAL;
 
+    if ((params.filter.mask & ALLOCINFO_FILTER_MASK_FLAGS) &&
+        (params.filter.flags & ~ALLOCINFO_FILTER_FLAGS_ALL))
+        return -EINVAL;
+
      if ((params.filter.mask & ALLOCINFO_FILTER_MASK_MIN_SIZE) &&
          (params.filter.mask & ALLOCINFO_FILTER_MASK_MAX_SIZE) &&

params.filter.min_size > params.filter.max_size)

Thanks

Best Regards

Hao

Quoted 59 lines

Thanks

Best Regards

Hao

Quoted 51 lines
include/uapi/linux/alloc_tag.h +0 -0
  };
    /* The alignment ensures 32-bit compatible interfaces are not

broken */

include/uapi/linux/alloc_tag.h +2 -0
@@ -39,6 +40,7 @@ enum {
      ALLOCINFO_FILTER_FUNCTION,
      ALLOCINFO_FILTER_FILENAME,
      ALLOCINFO_FILTER_LINENO,
+    ALLOCINFO_FILTER_INACCURATE,
      ALLOCINFO_FILTER_MIN_SIZE,
      ALLOCINFO_FILTER_MAX_SIZE,
      __ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
@@ -48,6 +50,7 @@ enum {
  #define ALLOCINFO_FILTER_MASK_FUNCTION        (1 <<
 ALLOCINFO_FILTER_FUNCTION)
  #define ALLOCINFO_FILTER_MASK_FILENAME        (1 <<
 ALLOCINFO_FILTER_FILENAME)
  #define ALLOCINFO_FILTER_MASK_LINENO        (1 <<
 ALLOCINFO_FILTER_LINENO)
+#define ALLOCINFO_FILTER_MASK_INACCURATE    (1 <<

ALLOCINFO_FILTER_INACCURATE)
#define ALLOCINFO_FILTER_MASK_MIN_SIZE (1 <<
ALLOCINFO_FILTER_MIN_SIZE)
#define ALLOCINFO_FILTER_MASK_MAX_SIZE (1 <<
ALLOCINFO_FILTER_MAX_SIZE)
diff --git a/lib/alloc_tag.c b/lib/alloc_tag.c
index ddc6946f56ab..cbcd12c4ef9c 100644

lib/alloc_tag.c +2 -0
@@ -249,6 +249,8 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,
                 struct alloc_tag_counters *counters,
                 bool *fetched_counters)
  {
+    bool inaccurate;
+
      if (!filter || !filter->mask)
          return true;

@@ -275,6 +277,12 @@ static bool matches_filter(struct codetag *ct,
struct allocinfo_filter *filter,

          ct->lineno != filter->fields.lineno)
          return false;

+ if (filter->mask & ALLOCINFO_FILTER_MASK_INACCURATE) {

lib/alloc_tag.c +5 -0
+        inaccurate = !!(ct->flags & CODETAG_FLAG_INACCURATE);
+        if (inaccurate != !!(filter->fields.inaccurate))
+            return false;
+    }
+
      if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE |
ALLOCINFO_FILTER_MASK_MAX_SIZE)) {
          if (!*fetched_counters) {
              *counters = allocinfo_prefetch_counters(ct);
reviewer
#17 lore raw

Re: [PATCH v3 4/6] alloc_tag: add accuracy based filtering to ioctl

In reply to Suren Baghdasaryan

Hi Suren

Quoted 142 lines · Suren Baghdasaryan
Quoted 65 lines · Hao Ge
Quoted 32 lines · Hao Ge

Hi Abhishek

Quoted 15 lines · Abhishek Bapat

Extend the allocinfo filtering mechanism to allow users to filter tags based on their accuracy.

---
   include/uapi/linux/alloc_tag.h | 3 +++
   lib/alloc_tag.c                | 8 ++++++++
   2 files changed, 11 insertions(+)
include/uapi/linux/alloc_tag.h +0 -0
index 0e648192df4d..42445bdb11c5 100644

include/uapi/linux/alloc_tag.h struct allocinfo_tag { · line 23

Quoted 4 lines
include/uapi/linux/alloc_tag.h +1 -0
@@ -20,6 +20,7 @@ struct allocinfo_tag {
       char function[ALLOCINFO_STR_SIZE];
       char filename[ALLOCINFO_STR_SIZE];
       __u64 lineno;
+    __u64 inaccurate;

I was wondering if it would make sense to define inaccurate as a flags field

(e.g. __u64 flags with ALLOCINFO_TAG_F_INACCURATE (1 <<0)),

so that only bit 0 is used today and the upper bits are reserved for future use,

Quoted 8 lines

aligning with current kernel codebase.

This design also allows for better extensibility if we need to

add new flags for any reason in the future.

We also need to add flag validity checks if we go this route.

And I've reviewed the issue reported by Sashiko, and I think it's valid.

When we expand the allocinfo_tag_data structure

struct allocinfo_tag_data{

      char modname[64];

      char function[64];

      char filename[64];

      __u64 lineno;

      __u64 inaccurate;

      __u64 bytes;

      __u64 calls;

      __u8 accurate;
    /* padding */
Quoted 3 lines

}

I think user space may see two fields related to inaccuracy.

Yes but one field (inside allocinfo_tag) is the input parameter which user provides to specify the filtering criteria and the other is the returned tag information. It's similar to any other tag attribute which you can be included in the filters.

Quoted 68 lines

How do you like these modifications?

include/uapi/linux/alloc_tag.h +6 -3
@@ -20,7 +20,6 @@ struct allocinfo_tag {
       char function[ALLOCINFO_STR_SIZE];
       char filename[ALLOCINFO_STR_SIZE];
       __u64 lineno;
-    __u64 inaccurate;
   };
 
   /* The alignment ensures 32-bit compatible interfaces are not broken */
@@ -40,7 +39,7 @@ enum {
       ALLOCINFO_FILTER_FUNCTION,
       ALLOCINFO_FILTER_FILENAME,
       ALLOCINFO_FILTER_LINENO,
-    ALLOCINFO_FILTER_INACCURATE,
+    ALLOCINFO_FILTER_FLAGS,
       ALLOCINFO_FILTER_MIN_SIZE,
       ALLOCINFO_FILTER_MAX_SIZE,
       __ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
@@ -50,16 +49,20 @@ enum {
   #define ALLOCINFO_FILTER_MASK_FUNCTION        (1 <<
 ALLOCINFO_FILTER_FUNCTION)
   #define ALLOCINFO_FILTER_MASK_FILENAME        (1 <<
 ALLOCINFO_FILTER_FILENAME)
   #define ALLOCINFO_FILTER_MASK_LINENO        (1 << ALLOCINFO_FILTER_LINENO)
-#define ALLOCINFO_FILTER_MASK_INACCURATE    (1 <<
 ALLOCINFO_FILTER_INACCURATE)
+#define ALLOCINFO_FILTER_MASK_FLAGS        (1 << ALLOCINFO_FILTER_FLAGS)
   #define ALLOCINFO_FILTER_MASK_MIN_SIZE        (1 <<
 ALLOCINFO_FILTER_MIN_SIZE)
   #define ALLOCINFO_FILTER_MASK_MAX_SIZE        (1 <<
 ALLOCINFO_FILTER_MAX_SIZE)
 
   #define ALLOCINFO_FILTER_MASKS \
       ((1 << (__ALLOCINFO_FILTER_LAST + 1)) - 1)
 
+#define ALLOCINFO_FILTER_F_INACCURATE    (1ULL << 0)
+#define ALLOCINFO_FILTER_FLAGS_ALL ALLOCINFO_FILTER_F_INACCURATE
+
   struct allocinfo_filter {
       __u64 mask; /* bitmask of the filter fields used */
       struct allocinfo_tag fields;
+    __u64 flags; /* bitmask of ALLOCINFO_FILTER_F_* */
       __u64 min_size;
       __u64 max_size;
   };
lib/alloc_tag.c +0 -2
@@ -249,8 +249,6 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,
                  struct alloc_tag_counters *counters,
                  bool *fetched_counters)
   {
-    bool inaccurate;
-
       if (!filter || !filter->mask)
           return true;
@@ -277,10 +275,11 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,
           ct->lineno != filter->fields.lineno)
           return false;
 
Quoted 8 lines

lib/alloc_tag.c static bool matches_filter(struct codetag *ct, · line 281

Quoted 7 lines
lib/alloc_tag.c +3 -4
-    if (filter->mask & ALLOCINFO_FILTER_MASK_INACCURATE) {
-        inaccurate = !!(ct->flags & CODETAG_FLAG_INACCURATE);
-        if (inaccurate != !!(filter->fields.inaccurate))
-            return false;
+    if (filter->mask & ALLOCINFO_FILTER_MASK_FLAGS) {
+        if (filter->flags & ALLOCINFO_FILTER_F_INACCURATE) {
+            if (!(ct->flags & CODETAG_FLAG_INACCURATE))

How would you filter records which have only accurate data?

Sorry, I overlooked this case.

Since allocinfo_tag_data exposes both inaccurate (from allocinfo_tag) and

accurate (from allocinfo_counter), userspace developers might mistakenly read

inaccurate instead of accurate when checking accuracy.

How about we add a comment to clarify?

struct allocinfo_tag {

    /* ... */

    __u64 lineno;

    /* filter criteria only; see allocinfo_counter.accurate for actual accuracy */

    __u64 inaccurate;

};

LGTM for the rest.

Thanks

Best Regards

Hao

Quoted 92 lines

Overall I would prefer ALLOCINFO_FILTER_MASK_INACCURATE rather than ALLOCINFO_FILTER_MASK_FLAGS. The fact that this attribute is a single-bit flag is a technical detail. It's still a tag attribuite like file and module names and IMO deserves its own filter.

Quoted 85 lines
lib/alloc_tag.c +2 -0
+                return false;
+        }
       }
 
       if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE |

ALLOCINFO_FILTER_MASK_MAX_SIZE)) {

lib/alloc_tag.c +4 -0
@@ -318,6 +317,10 @@ static int allocinfo_ioctl_get_at(struct seq_file
 *m, void __user *arg)
       if (params.filter.mask & ~ALLOCINFO_FILTER_MASKS)
           return -EINVAL;
 
+    if ((params.filter.mask & ALLOCINFO_FILTER_MASK_FLAGS) &&
+        (params.filter.flags & ~ALLOCINFO_FILTER_FLAGS_ALL))
+        return -EINVAL;
+
       if ((params.filter.mask & ALLOCINFO_FILTER_MASK_MIN_SIZE) &&
           (params.filter.mask & ALLOCINFO_FILTER_MASK_MAX_SIZE) &&

params.filter.min_size > params.filter.max_size)

Thanks

Best Regards

Hao

Quoted 58 lines

Thanks

Best Regards

Hao

Quoted 51 lines
include/uapi/linux/alloc_tag.h +0 -0
   };
     /* The alignment ensures 32-bit compatible interfaces are not

broken */

include/uapi/linux/alloc_tag.h +2 -0
@@ -39,6 +40,7 @@ enum {
       ALLOCINFO_FILTER_FUNCTION,
       ALLOCINFO_FILTER_FILENAME,
       ALLOCINFO_FILTER_LINENO,
+    ALLOCINFO_FILTER_INACCURATE,
       ALLOCINFO_FILTER_MIN_SIZE,
       ALLOCINFO_FILTER_MAX_SIZE,
       __ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
@@ -48,6 +50,7 @@ enum {
   #define ALLOCINFO_FILTER_MASK_FUNCTION        (1 <<
 ALLOCINFO_FILTER_FUNCTION)
   #define ALLOCINFO_FILTER_MASK_FILENAME        (1 <<
 ALLOCINFO_FILTER_FILENAME)
   #define ALLOCINFO_FILTER_MASK_LINENO        (1 <<
 ALLOCINFO_FILTER_LINENO)
+#define ALLOCINFO_FILTER_MASK_INACCURATE    (1 <<

ALLOCINFO_FILTER_INACCURATE)
#define ALLOCINFO_FILTER_MASK_MIN_SIZE (1 <<
ALLOCINFO_FILTER_MIN_SIZE)
#define ALLOCINFO_FILTER_MASK_MAX_SIZE (1 <<
ALLOCINFO_FILTER_MAX_SIZE)
diff --git a/lib/alloc_tag.c b/lib/alloc_tag.c
index ddc6946f56ab..cbcd12c4ef9c 100644

lib/alloc_tag.c +2 -0
@@ -249,6 +249,8 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,
                  struct alloc_tag_counters *counters,
                  bool *fetched_counters)
   {
+    bool inaccurate;
+
       if (!filter || !filter->mask)
           return true;
   @@ -275,6 +277,12 @@ static bool matches_filter(struct codetag *ct,
struct allocinfo_filter *filter,
           ct->lineno != filter->fields.lineno)
           return false;

+ if (filter->mask & ALLOCINFO_FILTER_MASK_INACCURATE) {

lib/alloc_tag.c +5 -0
+        inaccurate = !!(ct->flags & CODETAG_FLAG_INACCURATE);
+        if (inaccurate != !!(filter->fields.inaccurate))
+            return false;
+    }
+
       if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE |
ALLOCINFO_FILTER_MASK_MAX_SIZE)) {
           if (!*fetched_counters) {
               *counters = allocinfo_prefetch_counters(ct);
reviewer
#4 lore raw

Re: [PATCH v3 1/6] alloc_tag: add ioctl to /proc/allocinfo

In reply to Abhishek Bapat

Hi Abhishek

Quoted 492 lines · Abhishek Bapat
Quoted 103 lines · Hao Ge

Hi Suren and Abhishek

Thanks for the new version.

Quoted 91 lines · Abhishek Bapat

From: Suren Baghdasaryan <[email protected]>

Add the following ioctl commands for /proc/allocinfo file:

ALLOCINFO_IOC_CONTENT_ID - gets content identifier which can be used to check whether the file content has changed specifically due to module load/unload. Every time a module is loaded / unloaded, the returned value will be different. By comparing the identifier value at the beginning and at the end of the content retrieval operation, users can validate retrieved information for consistency.

ALLOCINFO_IOC_GET_AT - gets the record at the specified position. This is the position of a record in /proc/allocinfo.

ALLOCINFO_IOC_GET_NEXT - gets the record next to the last retrieved one. If no records were previously retrieved, returns the first record.

---
   Documentation/mm/allocation-profiling.rst     |   5 +
   .../userspace-api/ioctl/ioctl-number.rst      |   2 +
   MAINTAINERS                                   |   1 +
   include/linux/codetag.h                       |   2 +
   include/uapi/linux/alloc_tag.h                |  54 ++++
   lib/alloc_tag.c                               | 232 +++++++++++++++++-
   lib/codetag.c                                 |  18 ++
   7 files changed, 312 insertions(+), 2 deletions(-)

create mode 100644 include/uapi/linux/alloc_tag.h

Documentation/mm/allocation-profiling.rst +5 -0
index 5389d241176a..c3a28467955f 100644
@@ -46,6 +46,11 @@ sysctl:
   Runtime info:
     /proc/allocinfo
 
+  Profiling data can be retrieved either by reading `/proc/allocinfo` directly as
+  text or programmatically via `ioctl()` calls defined in `<uapi/linux/alloc_tag.h>`.
+  The ioctl interface supports structured binary data extraction as well as filtering
+  by module name, function, file, line number, accuracy, or allocation size limits.
+
   Example output::
 
     root@moria-kvm:~# sort -g /proc/allocinfo|tail|numfmt --to=iec
Documentation/userspace-api/ioctl/ioctl-number.rst +2 -0
index 331223761fff..84f6808a8578 100644
@@ -349,6 +349,8 @@ Code  Seq#    Include File                                             Comments
                                                                          <mailto:[email protected]>
   0xA5  20-2F  linux/surface_aggregator/dtx.h                            Microsoft Surface DTX driver
                                                                          <mailto:[email protected]>
+0xA6  00-0F  uapi/linux/alloc_tag.h                                    Memory allocation profiling
+                                                                       <mailto:[email protected]>
   0xAA  00-3F  linux/uapi/linux/userfaultfd.h
   0xAB  00-1F  linux/nbd.h
   0xAC  00-1F  linux/raw.h
MAINTAINERS +1 -0
index a31f6f207afd..77f3fc487691 100644
@@ -16711,6 +16711,7 @@ S:    Maintained
   F:  Documentation/mm/allocation-profiling.rst
   F:  include/linux/alloc_tag.h
   F:  include/linux/pgalloc_tag.h
+F:   include/uapi/linux/alloc_tag.h
   F:  lib/alloc_tag.c
 
   MEMORY CONTROLLER DRIVERS
include/linux/codetag.h +2 -0
index ddae7484ca45..a25a085c2df1 100644
@@ -77,6 +77,8 @@ struct codetag_iterator {
   void codetag_lock_module_list(struct codetag_type *cttype);
   bool codetag_trylock_module_list(struct codetag_type *cttype);
   void codetag_unlock_module_list(struct codetag_type *cttype);
+unsigned long codetag_get_content_id(struct codetag_type *cttype);
+unsigned int codetag_get_count(struct codetag_type *cttype);
   struct codetag_iterator codetag_get_ct_iter(struct codetag_type *cttype);
   struct codetag *codetag_next_ct(struct codetag_iterator *iter);
 
include/uapi/linux/alloc_tag.h new file +0 -0
new file mode 100644
index 000000000000..901199bad514

include/uapi/linux/alloc_tag.h line 3

Quoted 3 lines
include/uapi/linux/alloc_tag.h new file +3 -0
@@ -0,0 +1,54 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+/*
+ *  include/linux/alloc_tag.h

nit: it should be include/uapi/linux/alloc_tag.h

Quoted 3 lines

(I guess you may have missed the comment I brought up before. It is not a critical problem though.)

Apologies, I missed that comment earlier. Included in the v4 patchset. Thanks for bringing this up.

Quoted 382 lines
Quoted 357 lines
include/uapi/linux/alloc_tag.h new file +51 -0
+ */
+
+#ifndef _UAPI_ALLOC_TAG_H
+#define _UAPI_ALLOC_TAG_H
+
+#include <linux/types.h>
+
+#define ALLOCINFO_STR_SIZE   64
+
+struct allocinfo_content_id {
+     __u64 id;
+};
+
+struct allocinfo_tag {
+     /* Longer names are trimmed */
+     char modname[ALLOCINFO_STR_SIZE];
+     char function[ALLOCINFO_STR_SIZE];
+     char filename[ALLOCINFO_STR_SIZE];
+     __u64 lineno;
+};
+
+/* The alignment ensures 32-bit compatible interfaces are not broken */
+struct allocinfo_counter {
+     __u64 bytes;
+     __u64 calls;
+     __u8 accurate;
+} __attribute__((aligned(8)));
+
+struct allocinfo_tag_data {
+     struct allocinfo_tag tag;
+     struct allocinfo_counter counter;
+};
+
+struct allocinfo_get_at {
+     __u64 pos;      /* input */
+     struct allocinfo_tag_data data;
+};
+
+#define _ALLOCINFO_IOC_CONTENT_ID    0
+#define _ALLOCINFO_IOC_GET_AT                1
+#define _ALLOCINFO_IOC_GET_NEXT              2
+
+#define ALLOCINFO_IOC_BASE           0xA6
+#define ALLOCINFO_IOC_CONTENT_ID     _IOR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_CONTENT_ID,     \
+                                          struct allocinfo_content_id)
+#define ALLOCINFO_IOC_GET_AT         _IOWR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_GET_AT,        \
+                                           struct allocinfo_get_at)
+#define ALLOCINFO_IOC_GET_NEXT               _IOR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_GET_NEXT,       \
+                                          struct allocinfo_tag_data)
+
+#endif /* _UAPI_ALLOC_TAG_H */
lib/alloc_tag.c +230 -2
index d9be1cf5187d..a0577215eb3d 100644
@@ -5,6 +5,7 @@
   #include <linux/gfp.h>
   #include <linux/kallsyms.h>
   #include <linux/module.h>
+#include <linux/mutex.h>
   #include <linux/page_ext.h>
   #include <linux/pgalloc_tag.h>
   #include <linux/proc_fs.h>
@@ -14,6 +15,7 @@
   #include <linux/string_choices.h>
   #include <linux/vmalloc.h>
   #include <linux/kmemleak.h>
+#include <uapi/linux/alloc_tag.h>
 
   #define ALLOCINFO_FILE_NAME         "allocinfo"
   #define MODULE_ALLOC_TAG_VMAP_SIZE  (100000UL * sizeof(struct alloc_tag))
@@ -47,6 +49,10 @@ struct allocinfo_private {
       struct codetag_iterator iter;
       struct codetag_iterator reported_iter;
       bool print_header;
+     /* ioctl uses a separate iterator not to interfere with reads */
+     struct codetag_iterator ioctl_iter;
+     bool positioned; /* seq_open_private() sets to 0 */
+     struct mutex ioctl_lock;
   };
 
   static void *allocinfo_start(struct seq_file *m, loff_t *pos)
@@ -130,6 +136,229 @@ static const struct seq_operations allocinfo_seq_op = {
       .show   = allocinfo_show,
   };
 
+/*
+ * Initializes seq_file operations and allocates private state when opening
+ * the /proc/allocinfo procfs entry.
+ */
+static int allocinfo_open(struct inode *inode, struct file *file)
+{
+     int ret;
+
+     ret = seq_open_private(file, &allocinfo_seq_op,
+                            sizeof(struct allocinfo_private));
+     if (!ret) {
+             struct seq_file *m = file->private_data;
+             struct allocinfo_private *priv = m->private;
+
+             mutex_init(&priv->ioctl_lock);
+     }
+     return ret;
+}
+
+/*
+ * Cleans up the seq_file state and frees up the private state allocated in
+ * allocinfo_open() when closing the /proc/allocinfo file descriptor.
+ */
+static int allocinfo_release(struct inode *inode, struct file *file)
+{
+     return seq_release_private(inode, file);
+}
+
+/*
+ * Returns a pointer to the suffix of a string so that its length fits within
+ * ALLOCINFO_STR_SIZE, preserving the trailing characters.
+ */
+static const char *allocinfo_str(const char *str)
+{
+     size_t len = strlen(str);
+
+     /* Keep an extra space for the trailing NULL. */
+     if (len >= ALLOCINFO_STR_SIZE)
+             str += (len - ALLOCINFO_STR_SIZE) + 1;
+     return str;
+}
+
+/* Copy a string and trim from the beginning if it's too long */
+static void allocinfo_copy_str(char *dest, const char *src)
+{
+     strscpy_pad(dest, allocinfo_str(src), ALLOCINFO_STR_SIZE);
+}
+
+/*
+ * Populates the UAPI allocinfo_tag_data structure with active runtime
+ * profiling counters extracted from the given kernel codetag.
+ */
+static void allocinfo_to_params(struct codetag *ct,
+                             struct allocinfo_tag_data *data)
+{
+     struct alloc_tag *tag = ct_to_alloc_tag(ct);
+     struct alloc_tag_counters counter = alloc_tag_read(tag);
+
+     if (ct->modname)
+             allocinfo_copy_str(data->tag.modname, ct->modname);
+     else
+             data->tag.modname[0] = '\0';
+     allocinfo_copy_str(data->tag.function, ct->function);
+     allocinfo_copy_str(data->tag.filename, ct->filename);
+     data->tag.lineno = ct->lineno;
+     data->counter.bytes = counter.bytes;
+     data->counter.calls = counter.calls;
+     data->counter.accurate = !alloc_tag_is_inaccurate(tag);
+}
+
+/*
+ * Retrieves the unique content ID representing the current allocation tag module
+ * layout, allowing userspace to detect if modules were loaded / unloaded.
+ */
+static int allocinfo_ioctl_get_content_id(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_content_id params;
+
+     codetag_lock_module_list(alloc_tag_cttype);
+     params.id = codetag_get_content_id(alloc_tag_cttype);
+     codetag_unlock_module_list(alloc_tag_cttype);
+     if (copy_to_user(arg, &params, sizeof(params)))
+             return -EFAULT;
+
+     return 0;
+}
+
+/*
+ * Seeks the ioctl iterator to the specified 0-indexed tag position, reads its
+ * profiling data and returns it to userspace.
+ */
+static int allocinfo_ioctl_get_at(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_private *priv;
+     struct codetag *ct;
+     __u64 pos;
+     struct allocinfo_get_at params = {0};
+
+     if (copy_from_user(&params, arg, sizeof(params)))
+             return -EFAULT;
+
+     priv = m->private;
+     pos = params.pos;
+
+     mutex_lock(&priv->ioctl_lock);
+     codetag_lock_module_list(alloc_tag_cttype);
+
+     if (pos >= codetag_get_count(alloc_tag_cttype)) {
+             codetag_unlock_module_list(alloc_tag_cttype);
+             mutex_unlock(&priv->ioctl_lock);
+             return -ENOENT;
+     }
+
+     /* Find the codetag */
+     priv->ioctl_iter = codetag_get_ct_iter(alloc_tag_cttype);
+     ct = codetag_next_ct(&priv->ioctl_iter);
+     while (ct && pos--)
+             ct = codetag_next_ct(&priv->ioctl_iter);
+     if (ct) {
+             allocinfo_to_params(ct, &params.data);
+             priv->positioned = true;
+     }
+
+     codetag_unlock_module_list(alloc_tag_cttype);
+     mutex_unlock(&priv->ioctl_lock);
+
+     if (!ct)
+             return -ENOENT;
+
+     if (copy_to_user(arg, &params, sizeof(params)))
+             return -EFAULT;
+
+     return 0;
+}
+
+/*
+ * Advances the ioctl iterator to the next allocation tag in the sequence and
+ * returns its profiling data to userspace.
+ */
+static int allocinfo_ioctl_get_next(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_private *priv;
+     struct codetag *ct;
+     struct allocinfo_tag_data params;
+     int ret = 0;
+
+     memset(&params, 0, sizeof(params));
+     priv = m->private;
+
+     mutex_lock(&priv->ioctl_lock);
+     codetag_lock_module_list(alloc_tag_cttype);
+
+     if (!priv->positioned) {
+             priv->ioctl_iter = codetag_get_ct_iter(alloc_tag_cttype);
+             priv->positioned = true;
+     }
+
+     ct = codetag_next_ct(&priv->ioctl_iter);
+     if (ct)
+             allocinfo_to_params(ct, &params);
+
+     if (!ct) {
+             priv->positioned = false;
+             ret = -ENOENT;
+     }
+     codetag_unlock_module_list(alloc_tag_cttype);
+     mutex_unlock(&priv->ioctl_lock);
+
+     if (ret == 0) {
+             if (copy_to_user(arg, &params, sizeof(params)))
+                     return -EFAULT;
+     }
+     return ret;
+}
+
+/*
+ * Entry point ioctl function for /proc/allocinfo routing requests to fetch the
+ * layout content ID, seek to a specific tag, or read sequential tags.
+ */
+static long allocinfo_ioctl(struct file *file, unsigned int cmd,
+                         unsigned long __arg)
+{
+     void __user *arg = (void __user *)__arg;
+     int ret;
+
+     switch (cmd) {
+     case ALLOCINFO_IOC_CONTENT_ID:
+             ret = allocinfo_ioctl_get_content_id(file->private_data, arg);
+             break;
+     case ALLOCINFO_IOC_GET_AT:
+             ret = allocinfo_ioctl_get_at(file->private_data, arg);
+             break;
+     case ALLOCINFO_IOC_GET_NEXT:
+             ret = allocinfo_ioctl_get_next(file->private_data, arg);
+             break;
+     default:
+             ret = -ENOIOCTLCMD;
+             break;
+     }
+
+     return ret;
+}
+
+#ifdef CONFIG_COMPAT
+static long allocinfo_compat_ioctl(struct file *file, unsigned int cmd,
+                                unsigned long arg)
+{
+     return allocinfo_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
+}
+#endif
+
+static const struct proc_ops allocinfo_proc_ops = {
+     .proc_open              = allocinfo_open,
+     .proc_read_iter         = seq_read_iter,
+     .proc_lseek             = seq_lseek,
+     .proc_release           = allocinfo_release,
+     .proc_ioctl             = allocinfo_ioctl,
+#ifdef CONFIG_COMPAT
+     .proc_compat_ioctl      = allocinfo_compat_ioctl,
+#endif
+
+};
+
   size_t alloc_tag_top_users(struct codetag_bytes *tags, size_t count, bool can_sleep)
   {
       struct codetag_iterator iter;
@@ -993,8 +1222,7 @@ static int __init alloc_tag_init(void)
               return 0;
       }
 
-     if (!proc_create_seq_private(ALLOCINFO_FILE_NAME, 0400, NULL, &allocinfo_seq_op,
-                                  sizeof(struct allocinfo_private), NULL)) {
+     if (!proc_create(ALLOCINFO_FILE_NAME, 0400, NULL, &allocinfo_proc_ops)) {
               pr_err("Failed to create %s file\n", ALLOCINFO_FILE_NAME);
               shutdown_mem_profiling(false);
               return -ENOMEM;
lib/codetag.c +16 -0
index 4001a7ea6675..a9cda4c962a3 100644
@@ -19,6 +19,8 @@ struct codetag_type {
       struct codetag_type_desc desc;
       /* generates unique sequence number for module load */
       unsigned long next_mod_seq;
+     /* bumped on every module load and unload */
+     unsigned long content_id;
   };
 
   struct codetag_range {
@@ -50,6 +52,20 @@ void codetag_unlock_module_list(struct codetag_type *cttype)
       up_read(&cttype->mod_lock);
   }
 
+unsigned long codetag_get_content_id(struct codetag_type *cttype)
+{
+     lockdep_assert_held(&cttype->mod_lock);
+
+     return cttype->content_id;
+}
+
+unsigned int codetag_get_count(struct codetag_type *cttype)
+{
+     lockdep_assert_held(&cttype->mod_lock);
+
+     return cttype->count;
+}
+
   struct codetag_iterator codetag_get_ct_iter(struct codetag_type *cttype)
   {
       struct codetag_iterator iter = {

lib/codetag.c static int codetag_module_init(struct codetag_type *cttype, struct module *mod) · line 223

Quoted 4 lines
lib/codetag.c +1 -0
@@ -204,6 +220,7 @@ static int codetag_module_init(struct codetag_type *cttype, struct module *mod)
 
       down_write(&cttype->mod_lock);
       cmod->mod_seq = ++cttype->next_mod_seq;
+     ++cttype->content_id;

I have a comment on the content_id bump placement.

++cttype->content_id is placed before idr_alloc and the module_load

callback. If idr_alloc fails or module_load returns an error

(While the chance of this occurring is very low.), the idr entry gets

rolled back but content_id has already been bumped. The actual

content didn't change in this case, so userspace would see a

different content_id and assume the data is inconsistent when it

isn't.

Thanks

Best Regards

Quoted 7 lines
Quoted 1 line

Hao

While I agree with your comment, I decided to place the counter increment there because the chance of failure is low. Furthermore, even if it falsely invalidates user data, the user will simply query the content again. This placement also aligns with where the previously used field (cttype->next_mod_seq) was incremented. Let me know if you still think I should move it. Thanks!

Sorry, I should have marked this as a nit when I raised the comment.

Given its low probability of occurring, it doesn't block anything for now.

The reason I raised this comment was just in case someone adds new logic

in the feature  that could fail. But if that happens, we can move both next_mod_seq

and content_id down together.

Thanks

Best Regards

Hao

Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
lib/codetag.c +1 -0
       mod_id = idr_alloc(&cttype->mod_idr, cmod, 0, 0, GFP_KERNEL);
       if (mod_id >= 0) {
               if (cttype->desc.module_load) {
@@ -368,6 +385,7 @@ void codetag_unload_module(struct module *mod)
                       cttype->count -= range_size(cttype, &cmod->range);
                       idr_remove(&cttype->mod_idr, mod_id);
                       kfree(cmod);
+                     ++cttype->content_id;
               }
               up_write(&cttype->mod_lock);
               if (found && cttype->desc.free_section_mem)
reviewer
#21 lore raw

Re: [PATCH v3 5/6] kselftest: alloc_tag: add kselftest for ioctl interface

In reply to Abhishek Bapat

Hi Abhishek

Quoted 63 lines · Abhishek Bapat

Introduce a kselftest to verify the new IOCTL-based interface for /proc/allocinfo. The test covers:

1. Validation of the filename filter.
2. Validation of the function filter.

The first test validates the functionality of the filename filter. Using "mm/memory.c" as the candidate filename filter, it retrieves filtered entries from both procfs and ioctl and matches the first VEC_MAX_ENTRIES entries.

The second test validates the functionality of the function filter. It uses "dup_mm" as the candidate function as we do not expect this function name to change frequently and hence won't be needing to modify this test often.

Note that both the tests match line no, function name and file name fields. Bytes allocated and calls are not matched as those values may change in the time when the data is being read from procfs and ioctl and hence can lead to false negatives.

---
  MAINTAINERS                                   |   1 +
  tools/testing/selftests/alloc_tag/Makefile    |   9 +
  .../alloc_tag/allocinfo_ioctl_test.c          | 313 ++++++++++++++++++
  3 files changed, 323 insertions(+)

create mode 100644 tools/testing/selftests/alloc_tag/Makefile create mode 100644 tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c

MAINTAINERS +1 -0
index 77f3fc487691..80560f5f1292 100644
@@ -16713,6 +16713,7 @@ F:	include/linux/alloc_tag.h
  F:	include/linux/pgalloc_tag.h
  F:	include/uapi/linux/alloc_tag.h
  F:	lib/alloc_tag.c
+F:	tools/testing/selftests/alloc_tag/
 
  MEMORY CONTROLLER DRIVERS
  M:	Krzysztof Kozlowski <[email protected]>
tools/testing/selftests/alloc_tag/Makefile new file +9 -0
new file mode 100644
index 000000000000..f2b8fc022c3b
@@ -0,0 +1,9 @@
+# SPDX-License-Identifier: GPL-2.0
+
+TEST_GEN_PROGS := allocinfo_ioctl_test
+
+CFLAGS += -Wall
+CFLAGS += -I../../../../usr/include
+
+include ../lib.mk
+
tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +0 -0
new file mode 100644
index 000000000000..5c3c16e86c23

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c line 4

Quoted 4 lines
tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +4 -0
@@ -0,0 +1,313 @@
+// SPDX-License-Identifier: GPL-2.0-only
+
+/* kselftest for allocinfo ioctl
+ * allocinfo ioctl retrives allocinfo data through ioctl

nit: s/retrives/retrieves/

I've applied the full patch series locally and ran the kselftest, all 4 tests pass:

[root@localhost alloc_tag]# ./allocinfo_ioctl_test 1..4
ok 1 test_filename_filter
ok 2 test_function_filter
ok 3 test_size_filter
ok 4 test_lineno_filter
# Totals: pass:4 fail:0 xfail:0 xpass:0 skip:0 error:0

But there are no tests for ALLOCINFO_FILTER_MASK_MODNAME and

ALLOCINFO_FILTER_MASK_INACCURATE.

Thanks

Best Regards

Hao

Quoted 309 lines
tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +309 -0
+ * Copyright (C) 2026 Google, Inc.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+#include <linux/types.h>
+#include <linux/alloc_tag.h>
+#include "../kselftest.h"
+
+#define MAX_LINE_LEN		512
+#define ALLOCINFO_PROC		"/proc/allocinfo"
+
+enum ioctl_ret {
+	IOCTL_SUCCESS = 0,
+	IOCTL_FAILURE = 1,
+	IOCTL_INVALID_DATA = 2,
+};
+
+#define VEC_MAX_ENTRIES 32
+
+struct allocinfo_tag_data_vec {
+	struct allocinfo_tag_data tag[VEC_MAX_ENTRIES];
+	__u64 count;
+};
+
+static inline int __allocinfo_get_content_id(int dev_fd, struct allocinfo_content_id *params)
+{
+	return ioctl(dev_fd, ALLOCINFO_IOC_CONTENT_ID, params);
+}
+
+static inline int __allocinfo_get_at(int dev_fd, struct allocinfo_get_at *params)
+{
+	return ioctl(dev_fd, ALLOCINFO_IOC_GET_AT, params);
+}
+
+static inline int __allocinfo_get_next(int dev_fd, struct allocinfo_tag_data *params)
+{
+	return ioctl(dev_fd, ALLOCINFO_IOC_GET_NEXT, params);
+}
+
+static bool match_entry(const struct allocinfo_tag_data *procfs_entry,
+			const struct allocinfo_tag_data *tag_data,
+			bool match_bytes, bool match_calls, bool match_lineno,
+			bool match_function, bool match_filename)
+{
+	if (match_bytes && tag_data->counter.bytes != procfs_entry->counter.bytes) {
+		ksft_print_msg("size retrieved through ioctl does not match procfs\n");
+		return false;
+	}
+
+	if (match_calls && tag_data->counter.calls != procfs_entry->counter.calls) {
+		ksft_print_msg("call count retrieved through ioctl does not match procfs\n");
+		return false;
+	}
+
+	if (match_lineno && tag_data->tag.lineno != procfs_entry->tag.lineno) {
+		ksft_print_msg("lineno retrieved through ioctl does not match procfs\n");
+		return false;
+	}
+
+	if (match_function &&
+	    strncmp(tag_data->tag.function, procfs_entry->tag.function, ALLOCINFO_STR_SIZE)) {
+		ksft_print_msg("function retrieved through ioctl does not match procfs\n");
+		return false;
+	}
+
+	if (match_filename &&
+	    strncmp(tag_data->tag.filename, procfs_entry->tag.filename, ALLOCINFO_STR_SIZE)) {
+		ksft_print_msg("filename retrieved through ioctl does not match procfs\n");
+		return false;
+	}
+	return true;
+}
+
+static bool match_entries(const struct allocinfo_tag_data_vec *procfs_entries,
+			  const struct allocinfo_tag_data_vec *tags,
+			  bool match_bytes, bool match_calls, bool match_lineno,
+			  bool match_function, bool match_filename)
+{
+	__u64 i;
+
+	if (procfs_entries->count != tags->count) {
+		ksft_print_msg("Entry count mismatch. ioctl entries: %llu, proc entries: %llu\n",
+			       tags->count, procfs_entries->count);
+		return false;
+	}
+	for (i = 0; i < procfs_entries->count; i++) {
+		if (!match_entry(&procfs_entries->tag[i], &tags->tag[i],
+				 match_bytes, match_calls, match_lineno,
+				 match_function, match_filename)) {
+			ksft_print_msg("%lluth entry does not match.\n", i);
+			return false;
+		}
+	}
+	return true;
+}
+
+static int get_filtered_procfs_entries(struct allocinfo_tag_data_vec *procfs_entries,
+				       const struct allocinfo_filter *filter, int fd)
+{
+	FILE *fp = fdopen(fd, "r");
+	char line[MAX_LINE_LEN];
+	int matches;
+	struct allocinfo_tag_data procfs_entry;
+
+	if (!fp) {
+		ksft_print_msg("Failed to open " ALLOCINFO_PROC " for reading\n");
+		return 1;
+	}
+	memset(procfs_entries, 0, sizeof(*procfs_entries));
+	while (fgets(line, sizeof(line), fp) && procfs_entries->count < VEC_MAX_ENTRIES) {
+
+		memset(&procfs_entry, 0, sizeof(procfs_entry));
+		matches = sscanf(line, "%llu %llu %[^:]:%llu func:%s",
+				 &procfs_entry.counter.bytes,
+				 &procfs_entry.counter.calls,
+				 procfs_entry.tag.filename,
+				 &procfs_entry.tag.lineno,
+				 procfs_entry.tag.function);
+
+		if (matches != 5)
+			continue;
+
+		if (filter->mask & ALLOCINFO_FILTER_MASK_FILENAME) {
+			if (strncmp(procfs_entry.tag.filename,
+				    filter->fields.filename, ALLOCINFO_STR_SIZE))
+				continue;
+		}
+		if (filter->mask & ALLOCINFO_FILTER_MASK_FUNCTION) {
+			if (strncmp(procfs_entry.tag.function,
+				    filter->fields.function, ALLOCINFO_STR_SIZE))
+				continue;
+		}
+		if (filter->mask & ALLOCINFO_FILTER_MASK_LINENO) {
+			if (procfs_entry.tag.lineno != filter->fields.lineno)
+				continue;
+		}
+		if (filter->mask & ALLOCINFO_FILTER_MASK_MIN_SIZE) {
+			if (procfs_entry.counter.bytes < filter->min_size)
+				continue;
+		}
+		if (filter->mask & ALLOCINFO_FILTER_MASK_MAX_SIZE) {
+			if (procfs_entry.counter.bytes > filter->max_size)
+				continue;
+		}
+
+		memcpy(&procfs_entries->tag[procfs_entries->count++], &procfs_entry,
+		       sizeof(procfs_entry));
+	}
+	return 0;
+}
+
+static enum ioctl_ret get_filtered_ioctl_entries(struct allocinfo_tag_data_vec *tags,
+						 const struct allocinfo_filter *filter, int fd,
+						 __u64 start_pos)
+{
+	struct allocinfo_content_id start_cont_id, end_cont_id;
+	struct allocinfo_get_at get_at_params;
+	const int max_retries = 10;
+	int retry_count = 0;
+	int status;
+
+	/*
+	 * __allocinfo_get_content_id may return different values if a kernel module was loaded
+	 * between the two calls. If that happens, the data gathered cannot be considered consistent
+	 * and hence needs to be fetched again to avoid flakiness.
+	 */
+	do {
+		if (__allocinfo_get_content_id(fd, &start_cont_id)) {
+			ksft_print_msg("allocinfo_get_content_id failed\n");
+			return IOCTL_FAILURE;
+		}
+
+		memset(tags, 0, sizeof(*tags));
+		memset(&get_at_params, 0, sizeof(get_at_params));
+		memcpy(&get_at_params.filter, filter, sizeof(*filter));
+		get_at_params.pos = start_pos;
+		if (__allocinfo_get_at(fd, &get_at_params)) {
+			ksft_print_msg("allocinfo_get_at failed\n");
+			return IOCTL_FAILURE;
+		}
+		memcpy(&tags->tag[tags->count++], &get_at_params.data, sizeof(get_at_params.data));
+
+		while (tags->count < VEC_MAX_ENTRIES &&
+		       __allocinfo_get_next(fd, &tags->tag[tags->count]) == 0)
+			tags->count++;
+
+		if (__allocinfo_get_content_id(fd, &end_cont_id)) {
+			ksft_print_msg("allocinfo_get_content_id failed\n");
+			return IOCTL_FAILURE;
+		}
+
+		if (start_cont_id.id == end_cont_id.id) {
+			status = IOCTL_SUCCESS;
+		} else {
+			ksft_print_msg("allocinfo_get_content_id mismatch, retrying...\n");
+			status = IOCTL_INVALID_DATA;
+		}
+	} while (status == IOCTL_INVALID_DATA && retry_count++ < max_retries);
+
+	return status;
+}
+
+static int run_filter_test(const struct allocinfo_filter *filter)
+{
+	int fd;
+	struct allocinfo_tag_data_vec *tags = malloc(sizeof(*tags));
+	struct allocinfo_tag_data_vec *procfs_entries = malloc(sizeof(*procfs_entries));
+	int ioctl_status;
+	int ret = KSFT_PASS;
+
+	if (!tags || !procfs_entries) {
+		ksft_print_msg("Memory allocation failed.\n");
+		ret = KSFT_FAIL;
+		goto freemem;
+	}
+
+	fd = open(ALLOCINFO_PROC, O_RDONLY);
+	if (fd < 0) {
+		ksft_exit_skip("Failed to open " ALLOCINFO_PROC ": %s\n", strerror(errno));
+		ret = KSFT_FAIL;
+		goto freemem;
+	}
+
+	if (get_filtered_procfs_entries(procfs_entries, filter, fd)) {
+		ksft_print_msg("Error retrieving entries from " ALLOCINFO_PROC "\n");
+		ret = KSFT_FAIL;
+		goto exit;
+	}
+
+	if (procfs_entries->count == 0) {
+		ksft_print_msg("No entries found in " ALLOCINFO_PROC ", skipping test\n");
+		ret = KSFT_SKIP;
+		goto exit;
+	}
+
+	ioctl_status = get_filtered_ioctl_entries(tags, filter, fd, 0);
+	if (ioctl_status == IOCTL_INVALID_DATA) {
+		ksft_print_msg("Trouble retrieving valid IOCTL entries, skipping.\n");
+		ret = KSFT_SKIP;
+		goto exit;
+	}
+	if (ioctl_status == IOCTL_FAILURE) {
+		ksft_print_msg("Error retrieving IOCTL entries.\n");
+		ret = KSFT_FAIL;
+		goto exit;
+	}
+
+	if (!match_entries(procfs_entries, tags, false, false, true, true, true))
+		ret = KSFT_FAIL;
+
+exit:
+	close(fd);
+freemem:
+	free(tags);
+	free(procfs_entries);
+	return ret;
+}
+
+static int test_filename_filter(void)
+{
+	struct allocinfo_filter filter;
+	const char *target_filename = "mm/memory.c";
+
+	memset(&filter, 0, sizeof(filter));
+	filter.mask |= ALLOCINFO_FILTER_MASK_FILENAME;
+	strncpy(filter.fields.filename, target_filename, ALLOCINFO_STR_SIZE);
+
+	return run_filter_test(&filter);
+}
+
+static int test_function_filter(void)
+{
+	struct allocinfo_filter filter;
+	const char *target_function = "dup_mm";
+
+	memset(&filter, 0, sizeof(filter));
+	filter.mask |= ALLOCINFO_FILTER_MASK_FUNCTION;
+	strncpy(filter.fields.function, target_function, ALLOCINFO_STR_SIZE);
+
+	return run_filter_test(&filter);
+}
+
+int main(int argc, char *argv[])
+{
+	int ret;
+
+	ksft_set_plan(2);
+
+	ret = test_filename_filter();
+	if (ret == KSFT_SKIP)
+		ksft_test_result_skip("Skipping test_filename_filter\n");
+	else
+		ksft_test_result(ret == KSFT_PASS, "test_filename_filter\n");
+
+	ret = test_function_filter();
+	if (ret == KSFT_SKIP)
+		ksft_test_result_skip("Skipping test_function_filter\n");
+	else
+		ksft_test_result(ret == KSFT_PASS, "test_function_filter\n");
+
+	ksft_finished();
+}
reviewer
#22 lore raw

Re: [PATCH v3 5/6] kselftest: alloc_tag: add kselftest for ioctl interface

Quoted 85 lines · Hao Ge

Hi Abhishek

Quoted 62 lines · Abhishek Bapat

Introduce a kselftest to verify the new IOCTL-based interface for /proc/allocinfo. The test covers:

1. Validation of the filename filter.
2. Validation of the function filter.

The first test validates the functionality of the filename filter. Using "mm/memory.c" as the candidate filename filter, it retrieves filtered entries from both procfs and ioctl and matches the first VEC_MAX_ENTRIES entries.

The second test validates the functionality of the function filter. It uses "dup_mm" as the candidate function as we do not expect this function name to change frequently and hence won't be needing to modify this test often.

Note that both the tests match line no, function name and file name fields. Bytes allocated and calls are not matched as those values may change in the time when the data is being read from procfs and ioctl and hence can lead to false negatives.

---
  MAINTAINERS                                   |   1 + tools/testing/selftests/alloc_tag/Makefile    |   9 + .../alloc_tag/allocinfo_ioctl_test.c          | 313 ++++++++++++++++++

  3 files changed, 323 insertions(+)

  create mode 100644 tools/testing/selftests/alloc_tag/Makefile create mode 100644 tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c

MAINTAINERS +0 -0
index 77f3fc487691..80560f5f1292 100644
@@ -16713,6 +16713,7 @@ F:    include/linux/alloc_tag.h

  F:    include/linux/pgalloc_tag.h
  F:    include/uapi/linux/alloc_tag.h
  F:    lib/alloc_tag.c
+F:    tools/testing/selftests/alloc_tag/
    MEMORY CONTROLLER DRIVERS
  M:    Krzysztof Kozlowski <[email protected]>

tools/testing/selftests/alloc_tag/Makefile new file +9 -0
new file mode 100644
index 000000000000..f2b8fc022c3b
@@ -0,0 +1,9 @@
+# SPDX-License-Identifier: GPL-2.0
+
+TEST_GEN_PROGS := allocinfo_ioctl_test
+
+CFLAGS += -Wall
+CFLAGS += -I../../../../usr/include
+
+include ../lib.mk
+
tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +0 -0
new file mode 100644
index 000000000000..5c3c16e86c23

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c line 4

Quoted 4 lines
tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +4 -0
@@ -0,0 +1,313 @@
+// SPDX-License-Identifier: GPL-2.0-only
+
+/* kselftest for allocinfo ioctl
+ * allocinfo ioctl retrives allocinfo data through ioctl

nit: s/retrives/retrieves/

I've applied the full patch series locally and ran the kselftest, all 4 tests pass:

[root@localhost alloc_tag]# ./allocinfo_ioctl_test 1..4
ok 1 test_filename_filter
ok 2 test_function_filter
ok 3 test_size_filter
ok 4 test_lineno_filter
# Totals: pass:4 fail:0 xfail:0 xpass:0 skip:0 error:0

Quoted 3 lines

But there are no tests for ALLOCINFO_FILTER_MASK_MODNAME and

ALLOCINFO_FILTER_MASK_INACCURATE.

Sorry, please disregard my suggestion about adding tests for

ALLOCINFO_FILTER_MASK_MODNAME and ALLOCINFO_FILTER_MASK_INACCURATE.

ALLOCINFO_FILTER_MASK_MODNAME depends on kernel config and also requires

the module to be loaded. ALLOCINFO_FILTER_MASK_INACCURATE entries may not

be common, unless we can find a stable way to produce them.

Quoted 349 lines

Thanks

Best Regards

Hao

Quoted 341 lines
tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +32 -0
+ * Copyright (C) 2026 Google, Inc.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+#include <linux/types.h>
+#include <linux/alloc_tag.h>
+#include "../kselftest.h"
+
+#define MAX_LINE_LEN        512
+#define ALLOCINFO_PROC        "/proc/allocinfo"
+
+enum ioctl_ret {
+    IOCTL_SUCCESS = 0,
+    IOCTL_FAILURE = 1,
+    IOCTL_INVALID_DATA = 2,
+};
+
+#define VEC_MAX_ENTRIES 32
+
+struct allocinfo_tag_data_vec {
+    struct allocinfo_tag_data tag[VEC_MAX_ENTRIES];
+    __u64 count;
+};
+
+static inline int __allocinfo_get_content_id(int dev_fd, struct 

allocinfo_content_id *params)

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +5 -0
+{
+    return ioctl(dev_fd, ALLOCINFO_IOC_CONTENT_ID, params);
+}
+
+static inline int __allocinfo_get_at(int dev_fd, struct 

allocinfo_get_at *params)

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +5 -0
+{
+    return ioctl(dev_fd, ALLOCINFO_IOC_GET_AT, params);
+}
+
+static inline int __allocinfo_get_next(int dev_fd, struct 

allocinfo_tag_data *params)

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +10 -0
+{
+    return ioctl(dev_fd, ALLOCINFO_IOC_GET_NEXT, params);
+}
+
+static bool match_entry(const struct allocinfo_tag_data *procfs_entry,
+            const struct allocinfo_tag_data *tag_data,
+            bool match_bytes, bool match_calls, bool match_lineno,
+            bool match_function, bool match_filename)
+{
+    if (match_bytes && tag_data->counter.bytes != 

procfs_entry->counter.bytes) {
+        ksft_print_msg("size retrieved through ioctl does not match procfs\n");
+        return false;
+    }
+
+    if (match_calls && tag_data->counter.calls != procfs_entry->counter.calls) {
+        ksft_print_msg("call count retrieved through ioctl does not match procfs\n");
+        return false;
+    }
+
+    if (match_lineno && tag_data->tag.lineno != procfs_entry->tag.lineno) {
+        ksft_print_msg("lineno retrieved through ioctl does not match procfs\n");
+        return false;
+    }
+
+    if (match_function &&
+        strncmp(tag_data->tag.function, procfs_entry->tag.function, ALLOCINFO_STR_SIZE)) {
+        ksft_print_msg("function retrieved through ioctl does not match procfs\n");
+        return false;
+    }
+
+    if (match_filename &&
+        strncmp(tag_data->tag.filename, procfs_entry->tag.filename, ALLOCINFO_STR_SIZE)) {
+        ksft_print_msg("filename retrieved through ioctl does not match procfs\n");
+        return false;
+    }
+    return true;

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +3 -0
+}
+
+static bool match_entries(const struct allocinfo_tag_data_vec 

*procfs_entries,
+              const struct allocinfo_tag_data_vec *tags, +              bool match_bytes, bool match_calls, bool match_lineno, +              bool match_function, bool match_filename)

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +5 -0
+{
+    __u64 i;
+
+    if (procfs_entries->count != tags->count) {
+        ksft_print_msg("Entry count mismatch. ioctl entries: %llu, 

proc entries: %llu\n",
+                   tags->count, procfs_entries->count); +        return false;
+    }
+    for (i = 0; i < procfs_entries->count; i++) {
+        if (!match_entry(&procfs_entries->tag[i], &tags->tag[i], +                 match_bytes, match_calls, match_lineno, +                 match_function, match_filename)) {
+            ksft_print_msg("%lluth entry does not match.\n", i); +            return false;
+        }
+    }
+    return true;

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +3 -0
+}
+
+static int get_filtered_procfs_entries(struct allocinfo_tag_data_vec 

*procfs_entries,
+                       const struct allocinfo_filter *filter, int fd)

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +8 -0
+{
+    FILE *fp = fdopen(fd, "r");
+    char line[MAX_LINE_LEN];
+    int matches;
+    struct allocinfo_tag_data procfs_entry;
+
+    if (!fp) {
+        ksft_print_msg("Failed to open " ALLOCINFO_PROC " for 

reading\n");
+        return 1;
+    }
+    memset(procfs_entries, 0, sizeof(*procfs_entries)); +    while (fgets(line, sizeof(line), fp) && procfs_entries->count < VEC_MAX_ENTRIES) {

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +42 -0
+
+        memset(&procfs_entry, 0, sizeof(procfs_entry));
+        matches = sscanf(line, "%llu %llu %[^:]:%llu func:%s",
+                 &procfs_entry.counter.bytes,
+                 &procfs_entry.counter.calls,
+                 procfs_entry.tag.filename,
+                 &procfs_entry.tag.lineno,
+                 procfs_entry.tag.function);
+
+        if (matches != 5)
+            continue;
+
+        if (filter->mask & ALLOCINFO_FILTER_MASK_FILENAME) {
+            if (strncmp(procfs_entry.tag.filename,
+                    filter->fields.filename, ALLOCINFO_STR_SIZE))
+                continue;
+        }
+        if (filter->mask & ALLOCINFO_FILTER_MASK_FUNCTION) {
+            if (strncmp(procfs_entry.tag.function,
+                    filter->fields.function, ALLOCINFO_STR_SIZE))
+                continue;
+        }
+        if (filter->mask & ALLOCINFO_FILTER_MASK_LINENO) {
+            if (procfs_entry.tag.lineno != filter->fields.lineno)
+                continue;
+        }
+        if (filter->mask & ALLOCINFO_FILTER_MASK_MIN_SIZE) {
+            if (procfs_entry.counter.bytes < filter->min_size)
+                continue;
+        }
+        if (filter->mask & ALLOCINFO_FILTER_MASK_MAX_SIZE) {
+            if (procfs_entry.counter.bytes > filter->max_size)
+                continue;
+        }
+
+ memcpy(&procfs_entries->tag[procfs_entries->count++], &procfs_entry,
+               sizeof(procfs_entry));
+    }
+    return 0;
+}
+
+static enum ioctl_ret get_filtered_ioctl_entries(struct 

allocinfo_tag_data_vec *tags,
+                         const struct allocinfo_filter *filter, int fd, +                         __u64 start_pos)

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +9 -0
+{
+    struct allocinfo_content_id start_cont_id, end_cont_id;
+    struct allocinfo_get_at get_at_params;
+    const int max_retries = 10;
+    int retry_count = 0;
+    int status;
+
+    /*
+     * __allocinfo_get_content_id may return different values if a 

kernel module was loaded
+     * between the two calls. If that happens, the data gathered cannot be considered consistent
+     * and hence needs to be fetched again to avoid flakiness. +     */
+    do {
+        if (__allocinfo_get_content_id(fd, &start_cont_id)) { +            ksft_print_msg("allocinfo_get_content_id failed\n"); +            return IOCTL_FAILURE;
+        }
+
+        memset(tags, 0, sizeof(*tags));
+        memset(&get_at_params, 0, sizeof(get_at_params)); +        memcpy(&get_at_params.filter, filter, sizeof(*filter)); +        get_at_params.pos = start_pos;
+        if (__allocinfo_get_at(fd, &get_at_params)) { +            ksft_print_msg("allocinfo_get_at failed\n"); +            return IOCTL_FAILURE;
+        }
+        memcpy(&tags->tag[tags->count++], &get_at_params.data, sizeof(get_at_params.data));

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +14 -0
+
+        while (tags->count < VEC_MAX_ENTRIES &&
+               __allocinfo_get_next(fd, &tags->tag[tags->count]) == 0)
+            tags->count++;
+
+        if (__allocinfo_get_content_id(fd, &end_cont_id)) {
+            ksft_print_msg("allocinfo_get_content_id failed\n");
+            return IOCTL_FAILURE;
+        }
+
+        if (start_cont_id.id == end_cont_id.id) {
+            status = IOCTL_SUCCESS;
+        } else {
+            ksft_print_msg("allocinfo_get_content_id mismatch, 

retrying...\n");
+            status = IOCTL_INVALID_DATA;
+        }
+    } while (status == IOCTL_INVALID_DATA && retry_count++ < max_retries);

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +9 -0
+
+    return status;
+}
+
+static int run_filter_test(const struct allocinfo_filter *filter)
+{
+    int fd;
+    struct allocinfo_tag_data_vec *tags = malloc(sizeof(*tags));
+    struct allocinfo_tag_data_vec *procfs_entries = 

malloc(sizeof(*procfs_entries));
+    int ioctl_status;
+    int ret = KSFT_PASS;

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +10 -0
+
+    if (!tags || !procfs_entries) {
+        ksft_print_msg("Memory allocation failed.\n");
+        ret = KSFT_FAIL;
+        goto freemem;
+    }
+
+    fd = open(ALLOCINFO_PROC, O_RDONLY);
+    if (fd < 0) {
+        ksft_exit_skip("Failed to open " ALLOCINFO_PROC ": %s\n", 

strerror(errno));
+        ret = KSFT_FAIL;
+        goto freemem;
+    }
+
+    if (get_filtered_procfs_entries(procfs_entries, filter, fd)) { +        ksft_print_msg("Error retrieving entries from " ALLOCINFO_PROC "\n");
+        ret = KSFT_FAIL;
+        goto exit;
+    }
+
+    if (procfs_entries->count == 0) {
+        ksft_print_msg("No entries found in " ALLOCINFO_PROC ", skipping test\n");
+        ret = KSFT_SKIP;
+        goto exit;
+    }
+
+    ioctl_status = get_filtered_ioctl_entries(tags, filter, fd, 0); +    if (ioctl_status == IOCTL_INVALID_DATA) {
+        ksft_print_msg("Trouble retrieving valid IOCTL entries, skipping.\n");
+        ret = KSFT_SKIP;
+        goto exit;
+    }
+    if (ioctl_status == IOCTL_FAILURE) {
+        ksft_print_msg("Error retrieving IOCTL entries.\n"); +        ret = KSFT_FAIL;
+        goto exit;
+    }
+
+    if (!match_entries(procfs_entries, tags, false, false, true, true, true))
+        ret = KSFT_FAIL;

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +17 -0
+
+exit:
+    close(fd);
+freemem:
+    free(tags);
+    free(procfs_entries);
+    return ret;
+}
+
+static int test_filename_filter(void)
+{
+    struct allocinfo_filter filter;
+    const char *target_filename = "mm/memory.c";
+
+    memset(&filter, 0, sizeof(filter));
+    filter.mask |= ALLOCINFO_FILTER_MASK_FILENAME;
+    strncpy(filter.fields.filename, target_filename, 

ALLOCINFO_STR_SIZE);

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +12 -0
+
+    return run_filter_test(&filter);
+}
+
+static int test_function_filter(void)
+{
+    struct allocinfo_filter filter;
+    const char *target_function = "dup_mm";
+
+    memset(&filter, 0, sizeof(filter));
+    filter.mask |= ALLOCINFO_FILTER_MASK_FUNCTION;
+    strncpy(filter.fields.function, target_function, 

ALLOCINFO_STR_SIZE);

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +24 -0
+
+    return run_filter_test(&filter);
+}
+
+int main(int argc, char *argv[])
+{
+    int ret;
+
+    ksft_set_plan(2);
+
+    ret = test_filename_filter();
+    if (ret == KSFT_SKIP)
+        ksft_test_result_skip("Skipping test_filename_filter\n");
+    else
+        ksft_test_result(ret == KSFT_PASS, "test_filename_filter\n");
+
+    ret = test_function_filter();
+    if (ret == KSFT_SKIP)
+        ksft_test_result_skip("Skipping test_function_filter\n");
+    else
+        ksft_test_result(ret == KSFT_PASS, "test_function_filter\n");
+
+    ksft_finished();
+}
#18 lore raw

Re: [PATCH v3 4/6] alloc_tag: add accuracy based filtering to ioctl

In reply to Hao Ge
Quoted 170 lines · Hao Ge

Hi Suren

Quoted 142 lines · Suren Baghdasaryan
Quoted 65 lines · Hao Ge
Quoted 32 lines · Hao Ge

Hi Abhishek

Quoted 15 lines · Abhishek Bapat

Extend the allocinfo filtering mechanism to allow users to filter tags based on their accuracy.

---
   include/uapi/linux/alloc_tag.h | 3 +++
   lib/alloc_tag.c                | 8 ++++++++
   2 files changed, 11 insertions(+)
include/uapi/linux/alloc_tag.h +0 -0
index 0e648192df4d..42445bdb11c5 100644

include/uapi/linux/alloc_tag.h struct allocinfo_tag { · line 23

Quoted 4 lines
include/uapi/linux/alloc_tag.h +1 -0
@@ -20,6 +20,7 @@ struct allocinfo_tag {
       char function[ALLOCINFO_STR_SIZE];
       char filename[ALLOCINFO_STR_SIZE];
       __u64 lineno;
+    __u64 inaccurate;

I was wondering if it would make sense to define inaccurate as a flags field

(e.g. __u64 flags with ALLOCINFO_TAG_F_INACCURATE (1 <<0)),

so that only bit 0 is used today and the upper bits are reserved for future use,

Quoted 8 lines

aligning with current kernel codebase.

This design also allows for better extensibility if we need to

add new flags for any reason in the future.

We also need to add flag validity checks if we go this route.

And I've reviewed the issue reported by Sashiko, and I think it's valid.

When we expand the allocinfo_tag_data structure

struct allocinfo_tag_data{

      char modname[64];

      char function[64];

      char filename[64];

      __u64 lineno;

      __u64 inaccurate;

      __u64 bytes;

      __u64 calls;

      __u8 accurate;
    /* padding */
Quoted 3 lines

}

I think user space may see two fields related to inaccuracy.

Yes but one field (inside allocinfo_tag) is the input parameter which user provides to specify the filtering criteria and the other is the returned tag information. It's similar to any other tag attribute which you can be included in the filters.

Quoted 68 lines

How do you like these modifications?

include/uapi/linux/alloc_tag.h +6 -3
@@ -20,7 +20,6 @@ struct allocinfo_tag {
       char function[ALLOCINFO_STR_SIZE];
       char filename[ALLOCINFO_STR_SIZE];
       __u64 lineno;
-    __u64 inaccurate;
   };
 
   /* The alignment ensures 32-bit compatible interfaces are not broken */
@@ -40,7 +39,7 @@ enum {
       ALLOCINFO_FILTER_FUNCTION,
       ALLOCINFO_FILTER_FILENAME,
       ALLOCINFO_FILTER_LINENO,
-    ALLOCINFO_FILTER_INACCURATE,
+    ALLOCINFO_FILTER_FLAGS,
       ALLOCINFO_FILTER_MIN_SIZE,
       ALLOCINFO_FILTER_MAX_SIZE,
       __ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
@@ -50,16 +49,20 @@ enum {
   #define ALLOCINFO_FILTER_MASK_FUNCTION        (1 <<
 ALLOCINFO_FILTER_FUNCTION)
   #define ALLOCINFO_FILTER_MASK_FILENAME        (1 <<
 ALLOCINFO_FILTER_FILENAME)
   #define ALLOCINFO_FILTER_MASK_LINENO        (1 << ALLOCINFO_FILTER_LINENO)
-#define ALLOCINFO_FILTER_MASK_INACCURATE    (1 <<
 ALLOCINFO_FILTER_INACCURATE)
+#define ALLOCINFO_FILTER_MASK_FLAGS        (1 << ALLOCINFO_FILTER_FLAGS)
   #define ALLOCINFO_FILTER_MASK_MIN_SIZE        (1 <<
 ALLOCINFO_FILTER_MIN_SIZE)
   #define ALLOCINFO_FILTER_MASK_MAX_SIZE        (1 <<
 ALLOCINFO_FILTER_MAX_SIZE)
 
   #define ALLOCINFO_FILTER_MASKS \
       ((1 << (__ALLOCINFO_FILTER_LAST + 1)) - 1)
 
+#define ALLOCINFO_FILTER_F_INACCURATE    (1ULL << 0)
+#define ALLOCINFO_FILTER_FLAGS_ALL ALLOCINFO_FILTER_F_INACCURATE
+
   struct allocinfo_filter {
       __u64 mask; /* bitmask of the filter fields used */
       struct allocinfo_tag fields;
+    __u64 flags; /* bitmask of ALLOCINFO_FILTER_F_* */
       __u64 min_size;
       __u64 max_size;
   };
lib/alloc_tag.c +0 -2
@@ -249,8 +249,6 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,
                  struct alloc_tag_counters *counters,
                  bool *fetched_counters)
   {
-    bool inaccurate;
-
       if (!filter || !filter->mask)
           return true;
@@ -277,10 +275,11 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,
           ct->lineno != filter->fields.lineno)
           return false;
 
Quoted 8 lines

lib/alloc_tag.c static bool matches_filter(struct codetag *ct, · line 281

Quoted 7 lines
lib/alloc_tag.c +3 -4
-    if (filter->mask & ALLOCINFO_FILTER_MASK_INACCURATE) {
-        inaccurate = !!(ct->flags & CODETAG_FLAG_INACCURATE);
-        if (inaccurate != !!(filter->fields.inaccurate))
-            return false;
+    if (filter->mask & ALLOCINFO_FILTER_MASK_FLAGS) {
+        if (filter->flags & ALLOCINFO_FILTER_F_INACCURATE) {
+            if (!(ct->flags & CODETAG_FLAG_INACCURATE))

How would you filter records which have only accurate data?

Sorry, I overlooked this case.

Since allocinfo_tag_data exposes both inaccurate (from allocinfo_tag) and

accurate (from allocinfo_counter), userspace developers might mistakenly read

inaccurate instead of accurate when checking accuracy.

How about we add a comment to clarify?

struct allocinfo_tag {

Quoted 8 lines
     /* ... */

     __u64 lineno;

     /* filter criteria only; see allocinfo_counter.accurate for actual

accuracy */

     __u64 inaccurate;

I think we had comments showing which block of parameters are inputs and which ones are outputs but I'm not opposed to an additional reminder here.

Quoted 105 lines

};

LGTM for the rest.

Thanks

Best Regards

Hao

Quoted 92 lines

Overall I would prefer ALLOCINFO_FILTER_MASK_INACCURATE rather than ALLOCINFO_FILTER_MASK_FLAGS. The fact that this attribute is a single-bit flag is a technical detail. It's still a tag attribuite like file and module names and IMO deserves its own filter.

Quoted 85 lines
lib/alloc_tag.c +2 -0
+                return false;
+        }
       }
 
       if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE |

ALLOCINFO_FILTER_MASK_MAX_SIZE)) {

lib/alloc_tag.c +4 -0
@@ -318,6 +317,10 @@ static int allocinfo_ioctl_get_at(struct seq_file
 *m, void __user *arg)
       if (params.filter.mask & ~ALLOCINFO_FILTER_MASKS)
           return -EINVAL;
 
+    if ((params.filter.mask & ALLOCINFO_FILTER_MASK_FLAGS) &&
+        (params.filter.flags & ~ALLOCINFO_FILTER_FLAGS_ALL))
+        return -EINVAL;
+
       if ((params.filter.mask & ALLOCINFO_FILTER_MASK_MIN_SIZE) &&
           (params.filter.mask & ALLOCINFO_FILTER_MASK_MAX_SIZE) &&

params.filter.min_size > params.filter.max_size)

Thanks

Best Regards

Hao

Quoted 58 lines

Thanks

Best Regards

Hao

Quoted 51 lines
include/uapi/linux/alloc_tag.h +0 -0
   };
     /* The alignment ensures 32-bit compatible interfaces are not

broken */

include/uapi/linux/alloc_tag.h +2 -0
@@ -39,6 +40,7 @@ enum {
       ALLOCINFO_FILTER_FUNCTION,
       ALLOCINFO_FILTER_FILENAME,
       ALLOCINFO_FILTER_LINENO,
+    ALLOCINFO_FILTER_INACCURATE,
       ALLOCINFO_FILTER_MIN_SIZE,
       ALLOCINFO_FILTER_MAX_SIZE,
       __ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
@@ -48,6 +50,7 @@ enum {
   #define ALLOCINFO_FILTER_MASK_FUNCTION        (1 <<
 ALLOCINFO_FILTER_FUNCTION)
   #define ALLOCINFO_FILTER_MASK_FILENAME        (1 <<
 ALLOCINFO_FILTER_FILENAME)
   #define ALLOCINFO_FILTER_MASK_LINENO        (1 <<
 ALLOCINFO_FILTER_LINENO)
+#define ALLOCINFO_FILTER_MASK_INACCURATE    (1 <<

ALLOCINFO_FILTER_INACCURATE)
#define ALLOCINFO_FILTER_MASK_MIN_SIZE (1 <<
ALLOCINFO_FILTER_MIN_SIZE)
#define ALLOCINFO_FILTER_MASK_MAX_SIZE (1 <<
ALLOCINFO_FILTER_MAX_SIZE)
diff --git a/lib/alloc_tag.c b/lib/alloc_tag.c
index ddc6946f56ab..cbcd12c4ef9c 100644

lib/alloc_tag.c +2 -0
@@ -249,6 +249,8 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,
                  struct alloc_tag_counters *counters,
                  bool *fetched_counters)
   {
+    bool inaccurate;
+
       if (!filter || !filter->mask)
           return true;
   @@ -275,6 +277,12 @@ static bool matches_filter(struct codetag *ct,
struct allocinfo_filter *filter,
           ct->lineno != filter->fields.lineno)
           return false;

+ if (filter->mask & ALLOCINFO_FILTER_MASK_INACCURATE) {

lib/alloc_tag.c +5 -0
+        inaccurate = !!(ct->flags & CODETAG_FLAG_INACCURATE);
+        if (inaccurate != !!(filter->fields.inaccurate))
+            return false;
+    }
+
       if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE |
ALLOCINFO_FILTER_MASK_MAX_SIZE)) {
           if (!*fetched_counters) {
               *counters = allocinfo_prefetch_counters(ct);
#28 lore raw
In reply to Suren Baghdasaryan
Quoted 27 lines · Suren Baghdasaryan
Quoted 25 lines · Abhishek Bapat
Quoted 23 lines · Andrew Morton
Quoted 12 lines · On Fri, 5 Jun 2026 23:36:45 +0000 Abhishek Bapat <[email protected]>…

Currently, memory allocation profiling data is primarily exposed through /proc/allocinfo. While useful for manual inspection, this text-based interface poses challenges for production monitoring and large-scale analysis:

1. Userspace must parse large amounts of text to extract specific fields.
2. To find specific tags, userspace must read the entire dataset, requiring many context switches and high data copying.
3. The kernel currently aggregates per-CPU counters for every allocation size, even those the user intends to filter out immediately.

Quoted 4 lines

This series introduces a new IOCTL-based binary interface for allocinfo that supports kernel-side filtering. By allowing the user to specify a filter mask, we significantly reduce the work performed in-kernel and the amount of data transferred to userspace.

Thanks. AI review found several things - you'll want to address at least the first few.

Quoted 7 lines
Quoted 5 lines
Quoted 1 line
        https://sashiko.dev/#/patchset/[email protected]

All, please note I missed attaching the reason for choosing the IOCTL mechanism to this cover letter, but I will attach it to the v4 patchset cover letter along with other changes. Thanks!

Can you please add it here now so that we can review that?

I intend to add this to the end of the cover-letter passages, right before the version change descriptions:

The ioctl() mechanism was chosen for allocinfo to address the per-CPU counter aggregation performance bottleneck. A traditional read() operation must report the total allocation count and sizes for every code tag in the system. Doing so requires iterating across all CPUs to sum their per-CPU counters for thousands of tags, which introduces substantial runtime overhead.
The ioctl() interface allows userspace to push selective filtering criteria directly into the kernel before the per-CPU counter aggregation. The kernel aggregates per-CPU counters only for a small subset of tags that match the filter. This results in significant performance improvement.
Beyond fast filtered retrieval, the ioctl() foundation allows
introducing a context capture mechanism in the future to capture the context for specific allocations.

#5 lore raw

Re: [PATCH v3 1/6] alloc_tag: add ioctl to /proc/allocinfo

In reply to Hao Ge
Quoted 514 lines · Hao Ge

Hi Abhishek

Quoted 492 lines · Abhishek Bapat
Quoted 103 lines · Hao Ge

Hi Suren and Abhishek

Thanks for the new version.

Quoted 91 lines · Abhishek Bapat

From: Suren Baghdasaryan <[email protected]>

Add the following ioctl commands for /proc/allocinfo file:

ALLOCINFO_IOC_CONTENT_ID - gets content identifier which can be used to check whether the file content has changed specifically due to module load/unload. Every time a module is loaded / unloaded, the returned value will be different. By comparing the identifier value at the beginning and at the end of the content retrieval operation, users can validate retrieved information for consistency.

ALLOCINFO_IOC_GET_AT - gets the record at the specified position. This is the position of a record in /proc/allocinfo.

ALLOCINFO_IOC_GET_NEXT - gets the record next to the last retrieved one. If no records were previously retrieved, returns the first record.

---
   Documentation/mm/allocation-profiling.rst     |   5 +
   .../userspace-api/ioctl/ioctl-number.rst      |   2 +
   MAINTAINERS                                   |   1 +
   include/linux/codetag.h                       |   2 +
   include/uapi/linux/alloc_tag.h                |  54 ++++
   lib/alloc_tag.c                               | 232 +++++++++++++++++-
   lib/codetag.c                                 |  18 ++
   7 files changed, 312 insertions(+), 2 deletions(-)

create mode 100644 include/uapi/linux/alloc_tag.h

Documentation/mm/allocation-profiling.rst +5 -0
index 5389d241176a..c3a28467955f 100644
@@ -46,6 +46,11 @@ sysctl:
   Runtime info:
     /proc/allocinfo
 
+  Profiling data can be retrieved either by reading `/proc/allocinfo` directly as
+  text or programmatically via `ioctl()` calls defined in `<uapi/linux/alloc_tag.h>`.
+  The ioctl interface supports structured binary data extraction as well as filtering
+  by module name, function, file, line number, accuracy, or allocation size limits.
+
   Example output::
 
     root@moria-kvm:~# sort -g /proc/allocinfo|tail|numfmt --to=iec
Documentation/userspace-api/ioctl/ioctl-number.rst +2 -0
index 331223761fff..84f6808a8578 100644
@@ -349,6 +349,8 @@ Code  Seq#    Include File                                             Comments
                                                                          <mailto:[email protected]>
   0xA5  20-2F  linux/surface_aggregator/dtx.h                            Microsoft Surface DTX driver
                                                                          <mailto:[email protected]>
+0xA6  00-0F  uapi/linux/alloc_tag.h                                    Memory allocation profiling
+                                                                       <mailto:[email protected]>
   0xAA  00-3F  linux/uapi/linux/userfaultfd.h
   0xAB  00-1F  linux/nbd.h
   0xAC  00-1F  linux/raw.h
MAINTAINERS +1 -0
index a31f6f207afd..77f3fc487691 100644
@@ -16711,6 +16711,7 @@ S:    Maintained
   F:  Documentation/mm/allocation-profiling.rst
   F:  include/linux/alloc_tag.h
   F:  include/linux/pgalloc_tag.h
+F:   include/uapi/linux/alloc_tag.h
   F:  lib/alloc_tag.c
 
   MEMORY CONTROLLER DRIVERS
include/linux/codetag.h +2 -0
index ddae7484ca45..a25a085c2df1 100644
@@ -77,6 +77,8 @@ struct codetag_iterator {
   void codetag_lock_module_list(struct codetag_type *cttype);
   bool codetag_trylock_module_list(struct codetag_type *cttype);
   void codetag_unlock_module_list(struct codetag_type *cttype);
+unsigned long codetag_get_content_id(struct codetag_type *cttype);
+unsigned int codetag_get_count(struct codetag_type *cttype);
   struct codetag_iterator codetag_get_ct_iter(struct codetag_type *cttype);
   struct codetag *codetag_next_ct(struct codetag_iterator *iter);
 
include/uapi/linux/alloc_tag.h new file +0 -0
new file mode 100644
index 000000000000..901199bad514

include/uapi/linux/alloc_tag.h line 3

Quoted 3 lines
include/uapi/linux/alloc_tag.h new file +3 -0
@@ -0,0 +1,54 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+/*
+ *  include/linux/alloc_tag.h

nit: it should be include/uapi/linux/alloc_tag.h

Quoted 3 lines

(I guess you may have missed the comment I brought up before. It is not a critical problem though.)

Apologies, I missed that comment earlier. Included in the v4 patchset. Thanks for bringing this up.

Quoted 382 lines
Quoted 357 lines
include/uapi/linux/alloc_tag.h new file +51 -0
+ */
+
+#ifndef _UAPI_ALLOC_TAG_H
+#define _UAPI_ALLOC_TAG_H
+
+#include <linux/types.h>
+
+#define ALLOCINFO_STR_SIZE   64
+
+struct allocinfo_content_id {
+     __u64 id;
+};
+
+struct allocinfo_tag {
+     /* Longer names are trimmed */
+     char modname[ALLOCINFO_STR_SIZE];
+     char function[ALLOCINFO_STR_SIZE];
+     char filename[ALLOCINFO_STR_SIZE];
+     __u64 lineno;
+};
+
+/* The alignment ensures 32-bit compatible interfaces are not broken */
+struct allocinfo_counter {
+     __u64 bytes;
+     __u64 calls;
+     __u8 accurate;
+} __attribute__((aligned(8)));
+
+struct allocinfo_tag_data {
+     struct allocinfo_tag tag;
+     struct allocinfo_counter counter;
+};
+
+struct allocinfo_get_at {
+     __u64 pos;      /* input */
+     struct allocinfo_tag_data data;
+};
+
+#define _ALLOCINFO_IOC_CONTENT_ID    0
+#define _ALLOCINFO_IOC_GET_AT                1
+#define _ALLOCINFO_IOC_GET_NEXT              2
+
+#define ALLOCINFO_IOC_BASE           0xA6
+#define ALLOCINFO_IOC_CONTENT_ID     _IOR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_CONTENT_ID,     \
+                                          struct allocinfo_content_id)
+#define ALLOCINFO_IOC_GET_AT         _IOWR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_GET_AT,        \
+                                           struct allocinfo_get_at)
+#define ALLOCINFO_IOC_GET_NEXT               _IOR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_GET_NEXT,       \
+                                          struct allocinfo_tag_data)
+
+#endif /* _UAPI_ALLOC_TAG_H */
lib/alloc_tag.c +230 -2
index d9be1cf5187d..a0577215eb3d 100644
@@ -5,6 +5,7 @@
   #include <linux/gfp.h>
   #include <linux/kallsyms.h>
   #include <linux/module.h>
+#include <linux/mutex.h>
   #include <linux/page_ext.h>
   #include <linux/pgalloc_tag.h>
   #include <linux/proc_fs.h>
@@ -14,6 +15,7 @@
   #include <linux/string_choices.h>
   #include <linux/vmalloc.h>
   #include <linux/kmemleak.h>
+#include <uapi/linux/alloc_tag.h>
 
   #define ALLOCINFO_FILE_NAME         "allocinfo"
   #define MODULE_ALLOC_TAG_VMAP_SIZE  (100000UL * sizeof(struct alloc_tag))
@@ -47,6 +49,10 @@ struct allocinfo_private {
       struct codetag_iterator iter;
       struct codetag_iterator reported_iter;
       bool print_header;
+     /* ioctl uses a separate iterator not to interfere with reads */
+     struct codetag_iterator ioctl_iter;
+     bool positioned; /* seq_open_private() sets to 0 */
+     struct mutex ioctl_lock;
   };
 
   static void *allocinfo_start(struct seq_file *m, loff_t *pos)
@@ -130,6 +136,229 @@ static const struct seq_operations allocinfo_seq_op = {
       .show   = allocinfo_show,
   };
 
+/*
+ * Initializes seq_file operations and allocates private state when opening
+ * the /proc/allocinfo procfs entry.
+ */
+static int allocinfo_open(struct inode *inode, struct file *file)
+{
+     int ret;
+
+     ret = seq_open_private(file, &allocinfo_seq_op,
+                            sizeof(struct allocinfo_private));
+     if (!ret) {
+             struct seq_file *m = file->private_data;
+             struct allocinfo_private *priv = m->private;
+
+             mutex_init(&priv->ioctl_lock);
+     }
+     return ret;
+}
+
+/*
+ * Cleans up the seq_file state and frees up the private state allocated in
+ * allocinfo_open() when closing the /proc/allocinfo file descriptor.
+ */
+static int allocinfo_release(struct inode *inode, struct file *file)
+{
+     return seq_release_private(inode, file);
+}
+
+/*
+ * Returns a pointer to the suffix of a string so that its length fits within
+ * ALLOCINFO_STR_SIZE, preserving the trailing characters.
+ */
+static const char *allocinfo_str(const char *str)
+{
+     size_t len = strlen(str);
+
+     /* Keep an extra space for the trailing NULL. */
+     if (len >= ALLOCINFO_STR_SIZE)
+             str += (len - ALLOCINFO_STR_SIZE) + 1;
+     return str;
+}
+
+/* Copy a string and trim from the beginning if it's too long */
+static void allocinfo_copy_str(char *dest, const char *src)
+{
+     strscpy_pad(dest, allocinfo_str(src), ALLOCINFO_STR_SIZE);
+}
+
+/*
+ * Populates the UAPI allocinfo_tag_data structure with active runtime
+ * profiling counters extracted from the given kernel codetag.
+ */
+static void allocinfo_to_params(struct codetag *ct,
+                             struct allocinfo_tag_data *data)
+{
+     struct alloc_tag *tag = ct_to_alloc_tag(ct);
+     struct alloc_tag_counters counter = alloc_tag_read(tag);
+
+     if (ct->modname)
+             allocinfo_copy_str(data->tag.modname, ct->modname);
+     else
+             data->tag.modname[0] = '\0';
+     allocinfo_copy_str(data->tag.function, ct->function);
+     allocinfo_copy_str(data->tag.filename, ct->filename);
+     data->tag.lineno = ct->lineno;
+     data->counter.bytes = counter.bytes;
+     data->counter.calls = counter.calls;
+     data->counter.accurate = !alloc_tag_is_inaccurate(tag);
+}
+
+/*
+ * Retrieves the unique content ID representing the current allocation tag module
+ * layout, allowing userspace to detect if modules were loaded / unloaded.
+ */
+static int allocinfo_ioctl_get_content_id(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_content_id params;
+
+     codetag_lock_module_list(alloc_tag_cttype);
+     params.id = codetag_get_content_id(alloc_tag_cttype);
+     codetag_unlock_module_list(alloc_tag_cttype);
+     if (copy_to_user(arg, &params, sizeof(params)))
+             return -EFAULT;
+
+     return 0;
+}
+
+/*
+ * Seeks the ioctl iterator to the specified 0-indexed tag position, reads its
+ * profiling data and returns it to userspace.
+ */
+static int allocinfo_ioctl_get_at(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_private *priv;
+     struct codetag *ct;
+     __u64 pos;
+     struct allocinfo_get_at params = {0};
+
+     if (copy_from_user(&params, arg, sizeof(params)))
+             return -EFAULT;
+
+     priv = m->private;
+     pos = params.pos;
+
+     mutex_lock(&priv->ioctl_lock);
+     codetag_lock_module_list(alloc_tag_cttype);
+
+     if (pos >= codetag_get_count(alloc_tag_cttype)) {
+             codetag_unlock_module_list(alloc_tag_cttype);
+             mutex_unlock(&priv->ioctl_lock);
+             return -ENOENT;
+     }
+
+     /* Find the codetag */
+     priv->ioctl_iter = codetag_get_ct_iter(alloc_tag_cttype);
+     ct = codetag_next_ct(&priv->ioctl_iter);
+     while (ct && pos--)
+             ct = codetag_next_ct(&priv->ioctl_iter);
+     if (ct) {
+             allocinfo_to_params(ct, &params.data);
+             priv->positioned = true;
+     }
+
+     codetag_unlock_module_list(alloc_tag_cttype);
+     mutex_unlock(&priv->ioctl_lock);
+
+     if (!ct)
+             return -ENOENT;
+
+     if (copy_to_user(arg, &params, sizeof(params)))
+             return -EFAULT;
+
+     return 0;
+}
+
+/*
+ * Advances the ioctl iterator to the next allocation tag in the sequence and
+ * returns its profiling data to userspace.
+ */
+static int allocinfo_ioctl_get_next(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_private *priv;
+     struct codetag *ct;
+     struct allocinfo_tag_data params;
+     int ret = 0;
+
+     memset(&params, 0, sizeof(params));
+     priv = m->private;
+
+     mutex_lock(&priv->ioctl_lock);
+     codetag_lock_module_list(alloc_tag_cttype);
+
+     if (!priv->positioned) {
+             priv->ioctl_iter = codetag_get_ct_iter(alloc_tag_cttype);
+             priv->positioned = true;
+     }
+
+     ct = codetag_next_ct(&priv->ioctl_iter);
+     if (ct)
+             allocinfo_to_params(ct, &params);
+
+     if (!ct) {
+             priv->positioned = false;
+             ret = -ENOENT;
+     }
+     codetag_unlock_module_list(alloc_tag_cttype);
+     mutex_unlock(&priv->ioctl_lock);
+
+     if (ret == 0) {
+             if (copy_to_user(arg, &params, sizeof(params)))
+                     return -EFAULT;
+     }
+     return ret;
+}
+
+/*
+ * Entry point ioctl function for /proc/allocinfo routing requests to fetch the
+ * layout content ID, seek to a specific tag, or read sequential tags.
+ */
+static long allocinfo_ioctl(struct file *file, unsigned int cmd,
+                         unsigned long __arg)
+{
+     void __user *arg = (void __user *)__arg;
+     int ret;
+
+     switch (cmd) {
+     case ALLOCINFO_IOC_CONTENT_ID:
+             ret = allocinfo_ioctl_get_content_id(file->private_data, arg);
+             break;
+     case ALLOCINFO_IOC_GET_AT:
+             ret = allocinfo_ioctl_get_at(file->private_data, arg);
+             break;
+     case ALLOCINFO_IOC_GET_NEXT:
+             ret = allocinfo_ioctl_get_next(file->private_data, arg);
+             break;
+     default:
+             ret = -ENOIOCTLCMD;
+             break;
+     }
+
+     return ret;
+}
+
+#ifdef CONFIG_COMPAT
+static long allocinfo_compat_ioctl(struct file *file, unsigned int cmd,
+                                unsigned long arg)
+{
+     return allocinfo_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
+}
+#endif
+
+static const struct proc_ops allocinfo_proc_ops = {
+     .proc_open              = allocinfo_open,
+     .proc_read_iter         = seq_read_iter,
+     .proc_lseek             = seq_lseek,
+     .proc_release           = allocinfo_release,
+     .proc_ioctl             = allocinfo_ioctl,
+#ifdef CONFIG_COMPAT
+     .proc_compat_ioctl      = allocinfo_compat_ioctl,
+#endif
+
+};
+
   size_t alloc_tag_top_users(struct codetag_bytes *tags, size_t count, bool can_sleep)
   {
       struct codetag_iterator iter;
@@ -993,8 +1222,7 @@ static int __init alloc_tag_init(void)
               return 0;
       }
 
-     if (!proc_create_seq_private(ALLOCINFO_FILE_NAME, 0400, NULL, &allocinfo_seq_op,
-                                  sizeof(struct allocinfo_private), NULL)) {
+     if (!proc_create(ALLOCINFO_FILE_NAME, 0400, NULL, &allocinfo_proc_ops)) {
               pr_err("Failed to create %s file\n", ALLOCINFO_FILE_NAME);
               shutdown_mem_profiling(false);
               return -ENOMEM;
lib/codetag.c +16 -0
index 4001a7ea6675..a9cda4c962a3 100644
@@ -19,6 +19,8 @@ struct codetag_type {
       struct codetag_type_desc desc;
       /* generates unique sequence number for module load */
       unsigned long next_mod_seq;
+     /* bumped on every module load and unload */
+     unsigned long content_id;
   };
 
   struct codetag_range {
@@ -50,6 +52,20 @@ void codetag_unlock_module_list(struct codetag_type *cttype)
       up_read(&cttype->mod_lock);
   }
 
+unsigned long codetag_get_content_id(struct codetag_type *cttype)
+{
+     lockdep_assert_held(&cttype->mod_lock);
+
+     return cttype->content_id;
+}
+
+unsigned int codetag_get_count(struct codetag_type *cttype)
+{
+     lockdep_assert_held(&cttype->mod_lock);
+
+     return cttype->count;
+}
+
   struct codetag_iterator codetag_get_ct_iter(struct codetag_type *cttype)
   {
       struct codetag_iterator iter = {

lib/codetag.c static int codetag_module_init(struct codetag_type *cttype, struct module *mod) · line 223

Quoted 4 lines
lib/codetag.c +1 -0
@@ -204,6 +220,7 @@ static int codetag_module_init(struct codetag_type *cttype, struct module *mod)
 
       down_write(&cttype->mod_lock);
       cmod->mod_seq = ++cttype->next_mod_seq;
+     ++cttype->content_id;

I have a comment on the content_id bump placement.

++cttype->content_id is placed before idr_alloc and the module_load

callback. If idr_alloc fails or module_load returns an error

(While the chance of this occurring is very low.), the idr entry gets

rolled back but content_id has already been bumped. The actual

content didn't change in this case, so userspace would see a

different content_id and assume the data is inconsistent when it

isn't.

Thanks

Best Regards

Quoted 7 lines
Quoted 1 line

Hao

While I agree with your comment, I decided to place the counter increment there because the chance of failure is low. Furthermore, even if it falsely invalidates user data, the user will simply query the content again. This placement also aligns with where the previously used field (cttype->next_mod_seq) was incremented. Let me know if you still think I should move it. Thanks!

Sorry, I should have marked this as a nit when I raised the comment.

Given its low probability of occurring, it doesn't block anything for now.

The reason I raised this comment was just in case someone adds new logic

in the feature that could fail. But if that happens, we can move both next_mod_seq

Quoted 9 lines

and content_id down together.

Thanks

Best Regards

Hao

Sounds good, so for now I am not touching this patch and keeping it as is other than the file path nit inside the UAPI header file.

Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
lib/codetag.c +1 -0
       mod_id = idr_alloc(&cttype->mod_idr, cmod, 0, 0, GFP_KERNEL);
       if (mod_id >= 0) {
               if (cttype->desc.module_load) {
@@ -368,6 +385,7 @@ void codetag_unload_module(struct module *mod)
                       cttype->count -= range_size(cttype, &cmod->range);
                       idr_remove(&cttype->mod_idr, mod_id);
                       kfree(cmod);
+                     ++cttype->content_id;
               }
               up_write(&cttype->mod_lock);
               if (found && cttype->desc.free_section_mem)
#19 lore raw

Re: [PATCH v3 4/6] alloc_tag: add accuracy based filtering to ioctl

In reply to Suren Baghdasaryan
Quoted 176 lines · Suren Baghdasaryan
Quoted 174 lines · Hao Ge

Hi Suren

Quoted 142 lines · Suren Baghdasaryan
Quoted 65 lines · Hao Ge
Quoted 32 lines · Hao Ge

Hi Abhishek

Quoted 15 lines · Abhishek Bapat

Extend the allocinfo filtering mechanism to allow users to filter tags based on their accuracy.

---
   include/uapi/linux/alloc_tag.h | 3 +++
   lib/alloc_tag.c                | 8 ++++++++
   2 files changed, 11 insertions(+)
include/uapi/linux/alloc_tag.h +0 -0
index 0e648192df4d..42445bdb11c5 100644

include/uapi/linux/alloc_tag.h struct allocinfo_tag { · line 23

Quoted 4 lines
include/uapi/linux/alloc_tag.h +1 -0
@@ -20,6 +20,7 @@ struct allocinfo_tag {
       char function[ALLOCINFO_STR_SIZE];
       char filename[ALLOCINFO_STR_SIZE];
       __u64 lineno;
+    __u64 inaccurate;

I was wondering if it would make sense to define inaccurate as a flags field

(e.g. __u64 flags with ALLOCINFO_TAG_F_INACCURATE (1 <<0)),

so that only bit 0 is used today and the upper bits are reserved for future use,

Quoted 8 lines

aligning with current kernel codebase.

This design also allows for better extensibility if we need to

add new flags for any reason in the future.

We also need to add flag validity checks if we go this route.

And I've reviewed the issue reported by Sashiko, and I think it's valid.

When we expand the allocinfo_tag_data structure

struct allocinfo_tag_data{

      char modname[64];

      char function[64];

      char filename[64];

      __u64 lineno;

      __u64 inaccurate;

      __u64 bytes;

      __u64 calls;

      __u8 accurate;
    /* padding */
Quoted 3 lines

}

I think user space may see two fields related to inaccuracy.

Yes but one field (inside allocinfo_tag) is the input parameter which user provides to specify the filtering criteria and the other is the returned tag information. It's similar to any other tag attribute which you can be included in the filters.

Quoted 68 lines

How do you like these modifications?

include/uapi/linux/alloc_tag.h +6 -3
@@ -20,7 +20,6 @@ struct allocinfo_tag {
       char function[ALLOCINFO_STR_SIZE];
       char filename[ALLOCINFO_STR_SIZE];
       __u64 lineno;
-    __u64 inaccurate;
   };
 
   /* The alignment ensures 32-bit compatible interfaces are not broken */
@@ -40,7 +39,7 @@ enum {
       ALLOCINFO_FILTER_FUNCTION,
       ALLOCINFO_FILTER_FILENAME,
       ALLOCINFO_FILTER_LINENO,
-    ALLOCINFO_FILTER_INACCURATE,
+    ALLOCINFO_FILTER_FLAGS,
       ALLOCINFO_FILTER_MIN_SIZE,
       ALLOCINFO_FILTER_MAX_SIZE,
       __ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
@@ -50,16 +49,20 @@ enum {
   #define ALLOCINFO_FILTER_MASK_FUNCTION        (1 <<
 ALLOCINFO_FILTER_FUNCTION)
   #define ALLOCINFO_FILTER_MASK_FILENAME        (1 <<
 ALLOCINFO_FILTER_FILENAME)
   #define ALLOCINFO_FILTER_MASK_LINENO        (1 << ALLOCINFO_FILTER_LINENO)
-#define ALLOCINFO_FILTER_MASK_INACCURATE    (1 <<
 ALLOCINFO_FILTER_INACCURATE)
+#define ALLOCINFO_FILTER_MASK_FLAGS        (1 << ALLOCINFO_FILTER_FLAGS)
   #define ALLOCINFO_FILTER_MASK_MIN_SIZE        (1 <<
 ALLOCINFO_FILTER_MIN_SIZE)
   #define ALLOCINFO_FILTER_MASK_MAX_SIZE        (1 <<
 ALLOCINFO_FILTER_MAX_SIZE)
 
   #define ALLOCINFO_FILTER_MASKS \
       ((1 << (__ALLOCINFO_FILTER_LAST + 1)) - 1)
 
+#define ALLOCINFO_FILTER_F_INACCURATE    (1ULL << 0)
+#define ALLOCINFO_FILTER_FLAGS_ALL ALLOCINFO_FILTER_F_INACCURATE
+
   struct allocinfo_filter {
       __u64 mask; /* bitmask of the filter fields used */
       struct allocinfo_tag fields;
+    __u64 flags; /* bitmask of ALLOCINFO_FILTER_F_* */
       __u64 min_size;
       __u64 max_size;
   };
lib/alloc_tag.c +0 -2
@@ -249,8 +249,6 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,
                  struct alloc_tag_counters *counters,
                  bool *fetched_counters)
   {
-    bool inaccurate;
-
       if (!filter || !filter->mask)
           return true;
@@ -277,10 +275,11 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,
           ct->lineno != filter->fields.lineno)
           return false;
 
Quoted 8 lines

lib/alloc_tag.c static bool matches_filter(struct codetag *ct, · line 281

Quoted 7 lines
lib/alloc_tag.c +3 -4
-    if (filter->mask & ALLOCINFO_FILTER_MASK_INACCURATE) {
-        inaccurate = !!(ct->flags & CODETAG_FLAG_INACCURATE);
-        if (inaccurate != !!(filter->fields.inaccurate))
-            return false;
+    if (filter->mask & ALLOCINFO_FILTER_MASK_FLAGS) {
+        if (filter->flags & ALLOCINFO_FILTER_F_INACCURATE) {
+            if (!(ct->flags & CODETAG_FLAG_INACCURATE))

How would you filter records which have only accurate data?

Sorry, I overlooked this case.

Since allocinfo_tag_data exposes both inaccurate (from allocinfo_tag) and

accurate (from allocinfo_counter), userspace developers might mistakenly read

inaccurate instead of accurate when checking accuracy.

How about we add a comment to clarify?

struct allocinfo_tag {

     /* ... */

     __u64 lineno;
Quoted 9 lines
Quoted 4 lines
     /* filter criteria only; see allocinfo_counter.accurate for actual

accuracy */

     __u64 inaccurate;

I think we had comments showing which block of parameters are inputs and which ones are outputs but I'm not opposed to an additional reminder here.

Ack, I'll include the recommended comment.

Quoted 105 lines
Quoted 105 lines

};

LGTM for the rest.

Thanks

Best Regards

Hao

Quoted 92 lines

Overall I would prefer ALLOCINFO_FILTER_MASK_INACCURATE rather than ALLOCINFO_FILTER_MASK_FLAGS. The fact that this attribute is a single-bit flag is a technical detail. It's still a tag attribuite like file and module names and IMO deserves its own filter.

Quoted 85 lines
lib/alloc_tag.c +2 -0
+                return false;
+        }
       }
 
       if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE |

ALLOCINFO_FILTER_MASK_MAX_SIZE)) {

lib/alloc_tag.c +4 -0
@@ -318,6 +317,10 @@ static int allocinfo_ioctl_get_at(struct seq_file
 *m, void __user *arg)
       if (params.filter.mask & ~ALLOCINFO_FILTER_MASKS)
           return -EINVAL;
 
+    if ((params.filter.mask & ALLOCINFO_FILTER_MASK_FLAGS) &&
+        (params.filter.flags & ~ALLOCINFO_FILTER_FLAGS_ALL))
+        return -EINVAL;
+
       if ((params.filter.mask & ALLOCINFO_FILTER_MASK_MIN_SIZE) &&
           (params.filter.mask & ALLOCINFO_FILTER_MASK_MAX_SIZE) &&

params.filter.min_size > params.filter.max_size)

Thanks

Best Regards

Hao

Quoted 58 lines

Thanks

Best Regards

Hao

Quoted 51 lines
include/uapi/linux/alloc_tag.h +0 -0
   };
     /* The alignment ensures 32-bit compatible interfaces are not

broken */

include/uapi/linux/alloc_tag.h +2 -0
@@ -39,6 +40,7 @@ enum {
       ALLOCINFO_FILTER_FUNCTION,
       ALLOCINFO_FILTER_FILENAME,
       ALLOCINFO_FILTER_LINENO,
+    ALLOCINFO_FILTER_INACCURATE,
       ALLOCINFO_FILTER_MIN_SIZE,
       ALLOCINFO_FILTER_MAX_SIZE,
       __ALLOCINFO_FILTER_LAST = ALLOCINFO_FILTER_MAX_SIZE
@@ -48,6 +50,7 @@ enum {
   #define ALLOCINFO_FILTER_MASK_FUNCTION        (1 <<
 ALLOCINFO_FILTER_FUNCTION)
   #define ALLOCINFO_FILTER_MASK_FILENAME        (1 <<
 ALLOCINFO_FILTER_FILENAME)
   #define ALLOCINFO_FILTER_MASK_LINENO        (1 <<
 ALLOCINFO_FILTER_LINENO)
+#define ALLOCINFO_FILTER_MASK_INACCURATE    (1 <<

ALLOCINFO_FILTER_INACCURATE)
#define ALLOCINFO_FILTER_MASK_MIN_SIZE (1 <<
ALLOCINFO_FILTER_MIN_SIZE)
#define ALLOCINFO_FILTER_MASK_MAX_SIZE (1 <<
ALLOCINFO_FILTER_MAX_SIZE)
diff --git a/lib/alloc_tag.c b/lib/alloc_tag.c
index ddc6946f56ab..cbcd12c4ef9c 100644

lib/alloc_tag.c +2 -0
@@ -249,6 +249,8 @@ static bool matches_filter(struct codetag *ct,
 struct allocinfo_filter *filter,
                  struct alloc_tag_counters *counters,
                  bool *fetched_counters)
   {
+    bool inaccurate;
+
       if (!filter || !filter->mask)
           return true;
   @@ -275,6 +277,12 @@ static bool matches_filter(struct codetag *ct,
struct allocinfo_filter *filter,
           ct->lineno != filter->fields.lineno)
           return false;

+ if (filter->mask & ALLOCINFO_FILTER_MASK_INACCURATE) {

lib/alloc_tag.c +5 -0
+        inaccurate = !!(ct->flags & CODETAG_FLAG_INACCURATE);
+        if (inaccurate != !!(filter->fields.inaccurate))
+            return false;
+    }
+
       if (filter->mask & (ALLOCINFO_FILTER_MASK_MIN_SIZE |
ALLOCINFO_FILTER_MASK_MAX_SIZE)) {
           if (!*fetched_counters) {
               *counters = allocinfo_prefetch_counters(ct);
#23 lore raw

Re: [PATCH v3 5/6] kselftest: alloc_tag: add kselftest for ioctl interface

In reply to Hao Ge
Quoted 99 lines · Hao Ge
Quoted 89 lines · Hao Ge

Hi Abhishek

Quoted 65 lines · Abhishek Bapat

Introduce a kselftest to verify the new IOCTL-based interface for /proc/allocinfo. The test covers:

1. Validation of the filename filter.
2. Validation of the function filter.

The first test validates the functionality of the filename filter. Using "mm/memory.c" as the candidate filename filter, it retrieves filtered entries from both procfs and ioctl and matches the first VEC_MAX_ENTRIES entries.

The second test validates the functionality of the function filter. It uses "dup_mm" as the candidate function as we do not expect this function name to change frequently and hence won't be needing to modify this test often.

Note that both the tests match line no, function name and file name fields. Bytes allocated and calls are not matched as those values may change in the time when the data is being read from procfs and ioctl and hence can lead to false negatives.

---
  MAINTAINERS                                   |   1 +
  tools/testing/selftests/alloc_tag/Makefile    |   9 +
  .../alloc_tag/allocinfo_ioctl_test.c          | 313 ++++++++++++++++++
  3 files changed, 323 insertions(+)

create mode 100644 tools/testing/selftests/alloc_tag/Makefile create mode 100644
tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c

MAINTAINERS +1 -0
index 77f3fc487691..80560f5f1292 100644
@@ -16713,6 +16713,7 @@ F:    include/linux/alloc_tag.h
  F:    include/linux/pgalloc_tag.h
  F:    include/uapi/linux/alloc_tag.h
  F:    lib/alloc_tag.c
+F:    tools/testing/selftests/alloc_tag/
    MEMORY CONTROLLER DRIVERS
  M:    Krzysztof Kozlowski <[email protected]>
tools/testing/selftests/alloc_tag/Makefile new file +9 -0
new file mode 100644
index 000000000000..f2b8fc022c3b
@@ -0,0 +1,9 @@
+# SPDX-License-Identifier: GPL-2.0
+
+TEST_GEN_PROGS := allocinfo_ioctl_test
+
+CFLAGS += -Wall
+CFLAGS += -I../../../../usr/include
+
+include ../lib.mk
+
tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +0 -0
new file mode 100644
index 000000000000..5c3c16e86c23

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c line 4

Quoted 4 lines
tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +4 -0
@@ -0,0 +1,313 @@
+// SPDX-License-Identifier: GPL-2.0-only
+
+/* kselftest for allocinfo ioctl
+ * allocinfo ioctl retrives allocinfo data through ioctl

nit: s/retrives/retrieves/

I've applied the full patch series locally and ran the kselftest, all 4 tests pass:

[root@localhost alloc_tag]# ./allocinfo_ioctl_test 1..4
ok 1 test_filename_filter
ok 2 test_function_filter
ok 3 test_size_filter
ok 4 test_lineno_filter
# Totals: pass:4 fail:0 xfail:0 xpass:0 skip:0 error:0

Quoted 3 lines

But there are no tests for ALLOCINFO_FILTER_MASK_MODNAME and

ALLOCINFO_FILTER_MASK_INACCURATE.

Sorry, please disregard my suggestion about adding tests for

Quoted 9 lines

ALLOCINFO_FILTER_MASK_MODNAME and ALLOCINFO_FILTER_MASK_INACCURATE.

ALLOCINFO_FILTER_MASK_MODNAME depends on kernel config and also requires

the module to be loaded. ALLOCINFO_FILTER_MASK_INACCURATE entries may not

be common, unless we can find a stable way to produce them.

Ack, those are non-trivial to repro and hence we left them out.

Quoted 349 lines
Quoted 349 lines

Thanks

Best Regards

Hao

Quoted 341 lines
tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +32 -0
+ * Copyright (C) 2026 Google, Inc.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+#include <linux/types.h>
+#include <linux/alloc_tag.h>
+#include "../kselftest.h"
+
+#define MAX_LINE_LEN        512
+#define ALLOCINFO_PROC        "/proc/allocinfo"
+
+enum ioctl_ret {
+    IOCTL_SUCCESS = 0,
+    IOCTL_FAILURE = 1,
+    IOCTL_INVALID_DATA = 2,
+};
+
+#define VEC_MAX_ENTRIES 32
+
+struct allocinfo_tag_data_vec {
+    struct allocinfo_tag_data tag[VEC_MAX_ENTRIES];
+    __u64 count;
+};
+
+static inline int __allocinfo_get_content_id(int dev_fd, struct

allocinfo_content_id *params)

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +5 -0
+{
+    return ioctl(dev_fd, ALLOCINFO_IOC_CONTENT_ID, params);
+}
+
+static inline int __allocinfo_get_at(int dev_fd, struct

allocinfo_get_at *params)

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +5 -0
+{
+    return ioctl(dev_fd, ALLOCINFO_IOC_GET_AT, params);
+}
+
+static inline int __allocinfo_get_next(int dev_fd, struct

allocinfo_tag_data *params)

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +10 -0
+{
+    return ioctl(dev_fd, ALLOCINFO_IOC_GET_NEXT, params);
+}
+
+static bool match_entry(const struct allocinfo_tag_data *procfs_entry,
+            const struct allocinfo_tag_data *tag_data,
+            bool match_bytes, bool match_calls, bool match_lineno,
+            bool match_function, bool match_filename)
+{
+    if (match_bytes && tag_data->counter.bytes !=

procfs_entry->counter.bytes) {
+ ksft_print_msg("size retrieved through ioctl does not match
procfs\n");

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +4 -0
+        return false;
+    }
+
+    if (match_calls && tag_data->counter.calls !=

procfs_entry->counter.calls) {
+ ksft_print_msg("call count retrieved through ioctl does not
match procfs\n");

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +4 -0
+        return false;
+    }
+
+    if (match_lineno && tag_data->tag.lineno !=

procfs_entry->tag.lineno) {
+ ksft_print_msg("lineno retrieved through ioctl does not
match procfs\n");

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +5 -0
+        return false;
+    }
+
+    if (match_function &&
+        strncmp(tag_data->tag.function, procfs_entry->tag.function,

ALLOCINFO_STR_SIZE)) {
+ ksft_print_msg("function retrieved through ioctl does not
match procfs\n");

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +5 -0
+        return false;
+    }
+
+    if (match_filename &&
+        strncmp(tag_data->tag.filename, procfs_entry->tag.filename,

ALLOCINFO_STR_SIZE)) {
+ ksft_print_msg("filename retrieved through ioctl does not
match procfs\n");

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +6 -0
+        return false;
+    }
+    return true;
+}
+
+static bool match_entries(const struct allocinfo_tag_data_vec

*procfs_entries,

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +8 -0
+              const struct allocinfo_tag_data_vec *tags,
+              bool match_bytes, bool match_calls, bool match_lineno,
+              bool match_function, bool match_filename)
+{
+    __u64 i;
+
+    if (procfs_entries->count != tags->count) {
+        ksft_print_msg("Entry count mismatch. ioctl entries: %llu,

proc entries: %llu\n",

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +15 -0
+                   tags->count, procfs_entries->count);
+        return false;
+    }
+    for (i = 0; i < procfs_entries->count; i++) {
+        if (!match_entry(&procfs_entries->tag[i], &tags->tag[i],
+                 match_bytes, match_calls, match_lineno,
+                 match_function, match_filename)) {
+            ksft_print_msg("%lluth entry does not match.\n", i);
+            return false;
+        }
+    }
+    return true;
+}
+
+static int get_filtered_procfs_entries(struct allocinfo_tag_data_vec

*procfs_entries,

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +9 -0
+                       const struct allocinfo_filter *filter, int fd)
+{
+    FILE *fp = fdopen(fd, "r");
+    char line[MAX_LINE_LEN];
+    int matches;
+    struct allocinfo_tag_data procfs_entry;
+
+    if (!fp) {
+        ksft_print_msg("Failed to open " ALLOCINFO_PROC " for

reading\n");

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +4 -0
+        return 1;
+    }
+    memset(procfs_entries, 0, sizeof(*procfs_entries));
+    while (fgets(line, sizeof(line), fp) && procfs_entries->count <

VEC_MAX_ENTRIES) {

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +42 -0
+
+        memset(&procfs_entry, 0, sizeof(procfs_entry));
+        matches = sscanf(line, "%llu %llu %[^:]:%llu func:%s",
+                 &procfs_entry.counter.bytes,
+                 &procfs_entry.counter.calls,
+                 procfs_entry.tag.filename,
+                 &procfs_entry.tag.lineno,
+                 procfs_entry.tag.function);
+
+        if (matches != 5)
+            continue;
+
+        if (filter->mask & ALLOCINFO_FILTER_MASK_FILENAME) {
+            if (strncmp(procfs_entry.tag.filename,
+                    filter->fields.filename, ALLOCINFO_STR_SIZE))
+                continue;
+        }
+        if (filter->mask & ALLOCINFO_FILTER_MASK_FUNCTION) {
+            if (strncmp(procfs_entry.tag.function,
+                    filter->fields.function, ALLOCINFO_STR_SIZE))
+                continue;
+        }
+        if (filter->mask & ALLOCINFO_FILTER_MASK_LINENO) {
+            if (procfs_entry.tag.lineno != filter->fields.lineno)
+                continue;
+        }
+        if (filter->mask & ALLOCINFO_FILTER_MASK_MIN_SIZE) {
+            if (procfs_entry.counter.bytes < filter->min_size)
+                continue;
+        }
+        if (filter->mask & ALLOCINFO_FILTER_MASK_MAX_SIZE) {
+            if (procfs_entry.counter.bytes > filter->max_size)
+                continue;
+        }
+
+ memcpy(&procfs_entries->tag[procfs_entries->count++], &procfs_entry,
+               sizeof(procfs_entry));
+    }
+    return 0;
+}
+
+static enum ioctl_ret get_filtered_ioctl_entries(struct

allocinfo_tag_data_vec *tags,

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +11 -0
+                         const struct allocinfo_filter *filter, int fd,
+                         __u64 start_pos)
+{
+    struct allocinfo_content_id start_cont_id, end_cont_id;
+    struct allocinfo_get_at get_at_params;
+    const int max_retries = 10;
+    int retry_count = 0;
+    int status;
+
+    /*
+     * __allocinfo_get_content_id may return different values if a

kernel module was loaded
+ * between the two calls. If that happens, the data gathered
cannot be considered consistent

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +17 -0
+     * and hence needs to be fetched again to avoid flakiness.
+     */
+    do {
+        if (__allocinfo_get_content_id(fd, &start_cont_id)) {
+            ksft_print_msg("allocinfo_get_content_id failed\n");
+            return IOCTL_FAILURE;
+        }
+
+        memset(tags, 0, sizeof(*tags));
+        memset(&get_at_params, 0, sizeof(get_at_params));
+        memcpy(&get_at_params.filter, filter, sizeof(*filter));
+        get_at_params.pos = start_pos;
+        if (__allocinfo_get_at(fd, &get_at_params)) {
+            ksft_print_msg("allocinfo_get_at failed\n");
+            return IOCTL_FAILURE;
+        }
+        memcpy(&tags->tag[tags->count++], &get_at_params.data,

sizeof(get_at_params.data));

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +14 -0
+
+        while (tags->count < VEC_MAX_ENTRIES &&
+               __allocinfo_get_next(fd, &tags->tag[tags->count]) == 0)
+            tags->count++;
+
+        if (__allocinfo_get_content_id(fd, &end_cont_id)) {
+            ksft_print_msg("allocinfo_get_content_id failed\n");
+            return IOCTL_FAILURE;
+        }
+
+        if (start_cont_id.id == end_cont_id.id) {
+            status = IOCTL_SUCCESS;
+        } else {
+            ksft_print_msg("allocinfo_get_content_id mismatch,

retrying...\n");

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +3 -0
+            status = IOCTL_INVALID_DATA;
+        }
+    } while (status == IOCTL_INVALID_DATA && retry_count++ <

max_retries);

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +9 -0
+
+    return status;
+}
+
+static int run_filter_test(const struct allocinfo_filter *filter)
+{
+    int fd;
+    struct allocinfo_tag_data_vec *tags = malloc(sizeof(*tags));
+    struct allocinfo_tag_data_vec *procfs_entries =

malloc(sizeof(*procfs_entries));

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +12 -0
+    int ioctl_status;
+    int ret = KSFT_PASS;
+
+    if (!tags || !procfs_entries) {
+        ksft_print_msg("Memory allocation failed.\n");
+        ret = KSFT_FAIL;
+        goto freemem;
+    }
+
+    fd = open(ALLOCINFO_PROC, O_RDONLY);
+    if (fd < 0) {
+        ksft_exit_skip("Failed to open " ALLOCINFO_PROC ": %s\n",

strerror(errno));

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +6 -0
+        ret = KSFT_FAIL;
+        goto freemem;
+    }
+
+    if (get_filtered_procfs_entries(procfs_entries, filter, fd)) {
+        ksft_print_msg("Error retrieving entries from "

ALLOCINFO_PROC "\n");

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +6 -0
+        ret = KSFT_FAIL;
+        goto exit;
+    }
+
+    if (procfs_entries->count == 0) {
+        ksft_print_msg("No entries found in " ALLOCINFO_PROC ",

skipping test\n");

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +7 -0
+        ret = KSFT_SKIP;
+        goto exit;
+    }
+
+    ioctl_status = get_filtered_ioctl_entries(tags, filter, fd, 0);
+    if (ioctl_status == IOCTL_INVALID_DATA) {
+        ksft_print_msg("Trouble retrieving valid IOCTL entries,

skipping.\n");

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +10 -0
+        ret = KSFT_SKIP;
+        goto exit;
+    }
+    if (ioctl_status == IOCTL_FAILURE) {
+        ksft_print_msg("Error retrieving IOCTL entries.\n");
+        ret = KSFT_FAIL;
+        goto exit;
+    }
+
+    if (!match_entries(procfs_entries, tags, false, false, true,

true, true))

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +18 -0
+        ret = KSFT_FAIL;
+
+exit:
+    close(fd);
+freemem:
+    free(tags);
+    free(procfs_entries);
+    return ret;
+}
+
+static int test_filename_filter(void)
+{
+    struct allocinfo_filter filter;
+    const char *target_filename = "mm/memory.c";
+
+    memset(&filter, 0, sizeof(filter));
+    filter.mask |= ALLOCINFO_FILTER_MASK_FILENAME;
+    strncpy(filter.fields.filename, target_filename,

ALLOCINFO_STR_SIZE);

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +12 -0
+
+    return run_filter_test(&filter);
+}
+
+static int test_function_filter(void)
+{
+    struct allocinfo_filter filter;
+    const char *target_function = "dup_mm";
+
+    memset(&filter, 0, sizeof(filter));
+    filter.mask |= ALLOCINFO_FILTER_MASK_FUNCTION;
+    strncpy(filter.fields.function, target_function,

ALLOCINFO_STR_SIZE);

tools/testing/selftests/alloc_tag/allocinfo_ioctl_test.c new file +24 -0
+
+    return run_filter_test(&filter);
+}
+
+int main(int argc, char *argv[])
+{
+    int ret;
+
+    ksft_set_plan(2);
+
+    ret = test_filename_filter();
+    if (ret == KSFT_SKIP)
+        ksft_test_result_skip("Skipping test_filename_filter\n");
+    else
+        ksft_test_result(ret == KSFT_PASS, "test_filename_filter\n");
+
+    ret = test_function_filter();
+    if (ret == KSFT_SKIP)
+        ksft_test_result_skip("Skipping test_function_filter\n");
+    else
+        ksft_test_result(ret == KSFT_PASS, "test_function_filter\n");
+
+    ksft_finished();
+}
#6 lore raw

Re: [PATCH v3 1/6] alloc_tag: add ioctl to /proc/allocinfo

In reply to Abhishek Bapat
Quoted 521 lines · Abhishek Bapat
Quoted 519 lines · Hao Ge

Hi Abhishek

Quoted 492 lines · Abhishek Bapat
Quoted 103 lines · Hao Ge

Hi Suren and Abhishek

Thanks for the new version.

Quoted 91 lines · Abhishek Bapat

From: Suren Baghdasaryan <[email protected]>

Add the following ioctl commands for /proc/allocinfo file:

ALLOCINFO_IOC_CONTENT_ID - gets content identifier which can be used to check whether the file content has changed specifically due to module load/unload. Every time a module is loaded / unloaded, the returned value will be different. By comparing the identifier value at the beginning and at the end of the content retrieval operation, users can validate retrieved information for consistency.

ALLOCINFO_IOC_GET_AT - gets the record at the specified position. This is the position of a record in /proc/allocinfo.

ALLOCINFO_IOC_GET_NEXT - gets the record next to the last retrieved one. If no records were previously retrieved, returns the first record.

---
   Documentation/mm/allocation-profiling.rst     |   5 +
   .../userspace-api/ioctl/ioctl-number.rst      |   2 +
   MAINTAINERS                                   |   1 +
   include/linux/codetag.h                       |   2 +
   include/uapi/linux/alloc_tag.h                |  54 ++++
   lib/alloc_tag.c                               | 232 +++++++++++++++++-
   lib/codetag.c                                 |  18 ++
   7 files changed, 312 insertions(+), 2 deletions(-)

create mode 100644 include/uapi/linux/alloc_tag.h

Documentation/mm/allocation-profiling.rst +5 -0
index 5389d241176a..c3a28467955f 100644
@@ -46,6 +46,11 @@ sysctl:
   Runtime info:
     /proc/allocinfo
 
+  Profiling data can be retrieved either by reading `/proc/allocinfo` directly as
+  text or programmatically via `ioctl()` calls defined in `<uapi/linux/alloc_tag.h>`.
+  The ioctl interface supports structured binary data extraction as well as filtering
+  by module name, function, file, line number, accuracy, or allocation size limits.
+
   Example output::
 
     root@moria-kvm:~# sort -g /proc/allocinfo|tail|numfmt --to=iec
Documentation/userspace-api/ioctl/ioctl-number.rst +2 -0
index 331223761fff..84f6808a8578 100644
@@ -349,6 +349,8 @@ Code  Seq#    Include File                                             Comments
                                                                          <mailto:[email protected]>
   0xA5  20-2F  linux/surface_aggregator/dtx.h                            Microsoft Surface DTX driver
                                                                          <mailto:[email protected]>
+0xA6  00-0F  uapi/linux/alloc_tag.h                                    Memory allocation profiling
+                                                                       <mailto:[email protected]>
   0xAA  00-3F  linux/uapi/linux/userfaultfd.h
   0xAB  00-1F  linux/nbd.h
   0xAC  00-1F  linux/raw.h
MAINTAINERS +1 -0
index a31f6f207afd..77f3fc487691 100644
@@ -16711,6 +16711,7 @@ S:    Maintained
   F:  Documentation/mm/allocation-profiling.rst
   F:  include/linux/alloc_tag.h
   F:  include/linux/pgalloc_tag.h
+F:   include/uapi/linux/alloc_tag.h
   F:  lib/alloc_tag.c
 
   MEMORY CONTROLLER DRIVERS
include/linux/codetag.h +2 -0
index ddae7484ca45..a25a085c2df1 100644
@@ -77,6 +77,8 @@ struct codetag_iterator {
   void codetag_lock_module_list(struct codetag_type *cttype);
   bool codetag_trylock_module_list(struct codetag_type *cttype);
   void codetag_unlock_module_list(struct codetag_type *cttype);
+unsigned long codetag_get_content_id(struct codetag_type *cttype);
+unsigned int codetag_get_count(struct codetag_type *cttype);
   struct codetag_iterator codetag_get_ct_iter(struct codetag_type *cttype);
   struct codetag *codetag_next_ct(struct codetag_iterator *iter);
 
include/uapi/linux/alloc_tag.h new file +0 -0
new file mode 100644
index 000000000000..901199bad514

include/uapi/linux/alloc_tag.h line 3

Quoted 3 lines
include/uapi/linux/alloc_tag.h new file +3 -0
@@ -0,0 +1,54 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+/*
+ *  include/linux/alloc_tag.h

nit: it should be include/uapi/linux/alloc_tag.h

Quoted 3 lines

(I guess you may have missed the comment I brought up before. It is not a critical problem though.)

Apologies, I missed that comment earlier. Included in the v4 patchset. Thanks for bringing this up.

Quoted 382 lines
Quoted 357 lines
include/uapi/linux/alloc_tag.h new file +51 -0
+ */
+
+#ifndef _UAPI_ALLOC_TAG_H
+#define _UAPI_ALLOC_TAG_H
+
+#include <linux/types.h>
+
+#define ALLOCINFO_STR_SIZE   64
+
+struct allocinfo_content_id {
+     __u64 id;
+};
+
+struct allocinfo_tag {
+     /* Longer names are trimmed */
+     char modname[ALLOCINFO_STR_SIZE];
+     char function[ALLOCINFO_STR_SIZE];
+     char filename[ALLOCINFO_STR_SIZE];
+     __u64 lineno;
+};
+
+/* The alignment ensures 32-bit compatible interfaces are not broken */
+struct allocinfo_counter {
+     __u64 bytes;
+     __u64 calls;
+     __u8 accurate;
+} __attribute__((aligned(8)));
+
+struct allocinfo_tag_data {
+     struct allocinfo_tag tag;
+     struct allocinfo_counter counter;
+};
+
+struct allocinfo_get_at {
+     __u64 pos;      /* input */
+     struct allocinfo_tag_data data;
+};
+
+#define _ALLOCINFO_IOC_CONTENT_ID    0
+#define _ALLOCINFO_IOC_GET_AT                1
+#define _ALLOCINFO_IOC_GET_NEXT              2
+
+#define ALLOCINFO_IOC_BASE           0xA6
+#define ALLOCINFO_IOC_CONTENT_ID     _IOR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_CONTENT_ID,     \
+                                          struct allocinfo_content_id)
+#define ALLOCINFO_IOC_GET_AT         _IOWR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_GET_AT,        \
+                                           struct allocinfo_get_at)
+#define ALLOCINFO_IOC_GET_NEXT               _IOR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_GET_NEXT,       \
+                                          struct allocinfo_tag_data)
+
+#endif /* _UAPI_ALLOC_TAG_H */
lib/alloc_tag.c +230 -2
index d9be1cf5187d..a0577215eb3d 100644
@@ -5,6 +5,7 @@
   #include <linux/gfp.h>
   #include <linux/kallsyms.h>
   #include <linux/module.h>
+#include <linux/mutex.h>
   #include <linux/page_ext.h>
   #include <linux/pgalloc_tag.h>
   #include <linux/proc_fs.h>
@@ -14,6 +15,7 @@
   #include <linux/string_choices.h>
   #include <linux/vmalloc.h>
   #include <linux/kmemleak.h>
+#include <uapi/linux/alloc_tag.h>
 
   #define ALLOCINFO_FILE_NAME         "allocinfo"
   #define MODULE_ALLOC_TAG_VMAP_SIZE  (100000UL * sizeof(struct alloc_tag))
@@ -47,6 +49,10 @@ struct allocinfo_private {
       struct codetag_iterator iter;
       struct codetag_iterator reported_iter;
       bool print_header;
+     /* ioctl uses a separate iterator not to interfere with reads */
+     struct codetag_iterator ioctl_iter;
+     bool positioned; /* seq_open_private() sets to 0 */
+     struct mutex ioctl_lock;
   };
 
   static void *allocinfo_start(struct seq_file *m, loff_t *pos)
@@ -130,6 +136,229 @@ static const struct seq_operations allocinfo_seq_op = {
       .show   = allocinfo_show,
   };
 
+/*
+ * Initializes seq_file operations and allocates private state when opening
+ * the /proc/allocinfo procfs entry.
+ */
+static int allocinfo_open(struct inode *inode, struct file *file)
+{
+     int ret;
+
+     ret = seq_open_private(file, &allocinfo_seq_op,
+                            sizeof(struct allocinfo_private));
+     if (!ret) {
+             struct seq_file *m = file->private_data;
+             struct allocinfo_private *priv = m->private;
+
+             mutex_init(&priv->ioctl_lock);
+     }
+     return ret;
+}
+
+/*
+ * Cleans up the seq_file state and frees up the private state allocated in
+ * allocinfo_open() when closing the /proc/allocinfo file descriptor.
+ */
+static int allocinfo_release(struct inode *inode, struct file *file)
+{
+     return seq_release_private(inode, file);
+}
+
+/*
+ * Returns a pointer to the suffix of a string so that its length fits within
+ * ALLOCINFO_STR_SIZE, preserving the trailing characters.
+ */
+static const char *allocinfo_str(const char *str)
+{
+     size_t len = strlen(str);
+
+     /* Keep an extra space for the trailing NULL. */
+     if (len >= ALLOCINFO_STR_SIZE)
+             str += (len - ALLOCINFO_STR_SIZE) + 1;
+     return str;
+}
+
+/* Copy a string and trim from the beginning if it's too long */
+static void allocinfo_copy_str(char *dest, const char *src)
+{
+     strscpy_pad(dest, allocinfo_str(src), ALLOCINFO_STR_SIZE);
+}
+
+/*
+ * Populates the UAPI allocinfo_tag_data structure with active runtime
+ * profiling counters extracted from the given kernel codetag.
+ */
+static void allocinfo_to_params(struct codetag *ct,
+                             struct allocinfo_tag_data *data)
+{
+     struct alloc_tag *tag = ct_to_alloc_tag(ct);
+     struct alloc_tag_counters counter = alloc_tag_read(tag);
+
+     if (ct->modname)
+             allocinfo_copy_str(data->tag.modname, ct->modname);
+     else
+             data->tag.modname[0] = '\0';
+     allocinfo_copy_str(data->tag.function, ct->function);
+     allocinfo_copy_str(data->tag.filename, ct->filename);
+     data->tag.lineno = ct->lineno;
+     data->counter.bytes = counter.bytes;
+     data->counter.calls = counter.calls;
+     data->counter.accurate = !alloc_tag_is_inaccurate(tag);
+}
+
+/*
+ * Retrieves the unique content ID representing the current allocation tag module
+ * layout, allowing userspace to detect if modules were loaded / unloaded.
+ */
+static int allocinfo_ioctl_get_content_id(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_content_id params;
+
+     codetag_lock_module_list(alloc_tag_cttype);
+     params.id = codetag_get_content_id(alloc_tag_cttype);
+     codetag_unlock_module_list(alloc_tag_cttype);
+     if (copy_to_user(arg, &params, sizeof(params)))
+             return -EFAULT;
+
+     return 0;
+}
+
+/*
+ * Seeks the ioctl iterator to the specified 0-indexed tag position, reads its
+ * profiling data and returns it to userspace.
+ */
+static int allocinfo_ioctl_get_at(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_private *priv;
+     struct codetag *ct;
+     __u64 pos;
+     struct allocinfo_get_at params = {0};
+
+     if (copy_from_user(&params, arg, sizeof(params)))
+             return -EFAULT;
+
+     priv = m->private;
+     pos = params.pos;
+
+     mutex_lock(&priv->ioctl_lock);
+     codetag_lock_module_list(alloc_tag_cttype);
+
+     if (pos >= codetag_get_count(alloc_tag_cttype)) {
+             codetag_unlock_module_list(alloc_tag_cttype);
+             mutex_unlock(&priv->ioctl_lock);
+             return -ENOENT;
+     }
+
+     /* Find the codetag */
+     priv->ioctl_iter = codetag_get_ct_iter(alloc_tag_cttype);
+     ct = codetag_next_ct(&priv->ioctl_iter);
+     while (ct && pos--)
+             ct = codetag_next_ct(&priv->ioctl_iter);
+     if (ct) {
+             allocinfo_to_params(ct, &params.data);
+             priv->positioned = true;
+     }
+
+     codetag_unlock_module_list(alloc_tag_cttype);
+     mutex_unlock(&priv->ioctl_lock);
+
+     if (!ct)
+             return -ENOENT;
+
+     if (copy_to_user(arg, &params, sizeof(params)))
+             return -EFAULT;
+
+     return 0;
+}
+
+/*
+ * Advances the ioctl iterator to the next allocation tag in the sequence and
+ * returns its profiling data to userspace.
+ */
+static int allocinfo_ioctl_get_next(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_private *priv;
+     struct codetag *ct;
+     struct allocinfo_tag_data params;
+     int ret = 0;
+
+     memset(&params, 0, sizeof(params));
+     priv = m->private;
+
+     mutex_lock(&priv->ioctl_lock);
+     codetag_lock_module_list(alloc_tag_cttype);
+
+     if (!priv->positioned) {
+             priv->ioctl_iter = codetag_get_ct_iter(alloc_tag_cttype);
+             priv->positioned = true;
+     }
+
+     ct = codetag_next_ct(&priv->ioctl_iter);
+     if (ct)
+             allocinfo_to_params(ct, &params);
+
+     if (!ct) {
+             priv->positioned = false;
+             ret = -ENOENT;
+     }
+     codetag_unlock_module_list(alloc_tag_cttype);
+     mutex_unlock(&priv->ioctl_lock);
+
+     if (ret == 0) {
+             if (copy_to_user(arg, &params, sizeof(params)))
+                     return -EFAULT;
+     }
+     return ret;
+}
+
+/*
+ * Entry point ioctl function for /proc/allocinfo routing requests to fetch the
+ * layout content ID, seek to a specific tag, or read sequential tags.
+ */
+static long allocinfo_ioctl(struct file *file, unsigned int cmd,
+                         unsigned long __arg)
+{
+     void __user *arg = (void __user *)__arg;
+     int ret;
+
+     switch (cmd) {
+     case ALLOCINFO_IOC_CONTENT_ID:
+             ret = allocinfo_ioctl_get_content_id(file->private_data, arg);
+             break;
+     case ALLOCINFO_IOC_GET_AT:
+             ret = allocinfo_ioctl_get_at(file->private_data, arg);
+             break;
+     case ALLOCINFO_IOC_GET_NEXT:
+             ret = allocinfo_ioctl_get_next(file->private_data, arg);
+             break;
+     default:
+             ret = -ENOIOCTLCMD;
+             break;
+     }
+
+     return ret;
+}
+
+#ifdef CONFIG_COMPAT
+static long allocinfo_compat_ioctl(struct file *file, unsigned int cmd,
+                                unsigned long arg)
+{
+     return allocinfo_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
+}
+#endif
+
+static const struct proc_ops allocinfo_proc_ops = {
+     .proc_open              = allocinfo_open,
+     .proc_read_iter         = seq_read_iter,
+     .proc_lseek             = seq_lseek,
+     .proc_release           = allocinfo_release,
+     .proc_ioctl             = allocinfo_ioctl,
+#ifdef CONFIG_COMPAT
+     .proc_compat_ioctl      = allocinfo_compat_ioctl,
+#endif
+
+};
+
   size_t alloc_tag_top_users(struct codetag_bytes *tags, size_t count, bool can_sleep)
   {
       struct codetag_iterator iter;
@@ -993,8 +1222,7 @@ static int __init alloc_tag_init(void)
               return 0;
       }
 
-     if (!proc_create_seq_private(ALLOCINFO_FILE_NAME, 0400, NULL, &allocinfo_seq_op,
-                                  sizeof(struct allocinfo_private), NULL)) {
+     if (!proc_create(ALLOCINFO_FILE_NAME, 0400, NULL, &allocinfo_proc_ops)) {
               pr_err("Failed to create %s file\n", ALLOCINFO_FILE_NAME);
               shutdown_mem_profiling(false);
               return -ENOMEM;
lib/codetag.c +16 -0
index 4001a7ea6675..a9cda4c962a3 100644
@@ -19,6 +19,8 @@ struct codetag_type {
       struct codetag_type_desc desc;
       /* generates unique sequence number for module load */
       unsigned long next_mod_seq;
+     /* bumped on every module load and unload */
+     unsigned long content_id;
   };
 
   struct codetag_range {
@@ -50,6 +52,20 @@ void codetag_unlock_module_list(struct codetag_type *cttype)
       up_read(&cttype->mod_lock);
   }
 
+unsigned long codetag_get_content_id(struct codetag_type *cttype)
+{
+     lockdep_assert_held(&cttype->mod_lock);
+
+     return cttype->content_id;
+}
+
+unsigned int codetag_get_count(struct codetag_type *cttype)
+{
+     lockdep_assert_held(&cttype->mod_lock);
+
+     return cttype->count;
+}
+
   struct codetag_iterator codetag_get_ct_iter(struct codetag_type *cttype)
   {
       struct codetag_iterator iter = {

lib/codetag.c static int codetag_module_init(struct codetag_type *cttype, struct module *mod) · line 223

Quoted 4 lines
lib/codetag.c +1 -0
@@ -204,6 +220,7 @@ static int codetag_module_init(struct codetag_type *cttype, struct module *mod)
 
       down_write(&cttype->mod_lock);
       cmod->mod_seq = ++cttype->next_mod_seq;
+     ++cttype->content_id;

I have a comment on the content_id bump placement.

++cttype->content_id is placed before idr_alloc and the module_load

callback. If idr_alloc fails or module_load returns an error

(While the chance of this occurring is very low.), the idr entry gets

rolled back but content_id has already been bumped. The actual

content didn't change in this case, so userspace would see a

different content_id and assume the data is inconsistent when it

isn't.

Thanks

Best Regards

Quoted 7 lines
Quoted 1 line

Hao

While I agree with your comment, I decided to place the counter increment there because the chance of failure is low. Furthermore, even if it falsely invalidates user data, the user will simply query the content again. This placement also aligns with where the previously used field (cttype->next_mod_seq) was incremented. Let me know if you still think I should move it. Thanks!

Sorry, I should have marked this as a nit when I raised the comment.

Given its low probability of occurring, it doesn't block anything for now.

The reason I raised this comment was just in case someone adds new logic

in the feature that could fail. But if that happens, we can move both next_mod_seq

and content_id down together.

Thanks

Quoted 7 lines
Quoted 4 lines

Best Regards

Hao

Sounds good, so for now I am not touching this patch and keeping it as is other than the file path nit inside the UAPI header file.

Actually, checkpatch is complaining about using the same filename inside of the file and hence I am dropping that comment completely.

Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
lib/codetag.c +1 -0
       mod_id = idr_alloc(&cttype->mod_idr, cmod, 0, 0, GFP_KERNEL);
       if (mod_id >= 0) {
               if (cttype->desc.module_load) {
@@ -368,6 +385,7 @@ void codetag_unload_module(struct module *mod)
                       cttype->count -= range_size(cttype, &cmod->range);
                       idr_remove(&cttype->mod_idr, mod_id);
                       kfree(cmod);
+                     ++cttype->content_id;
               }
               up_write(&cttype->mod_lock);
               if (found && cttype->desc.free_section_mem)
#7 lore raw

Re: [PATCH v3 1/6] alloc_tag: add ioctl to /proc/allocinfo

Quoted 525 lines · Abhishek Bapat
Quoted 523 lines · Abhishek Bapat
Quoted 521 lines · Hao Ge

Hi Abhishek

Quoted 492 lines · Abhishek Bapat
Quoted 103 lines · Hao Ge

Hi Suren and Abhishek

Thanks for the new version.

Quoted 91 lines · Abhishek Bapat

From: Suren Baghdasaryan <[email protected]>

Add the following ioctl commands for /proc/allocinfo file:

ALLOCINFO_IOC_CONTENT_ID - gets content identifier which can be used to check whether the file content has changed specifically due to module load/unload. Every time a module is loaded / unloaded, the returned value will be different. By comparing the identifier value at the beginning and at the end of the content retrieval operation, users can validate retrieved information for consistency.

ALLOCINFO_IOC_GET_AT - gets the record at the specified position. This is the position of a record in /proc/allocinfo.

ALLOCINFO_IOC_GET_NEXT - gets the record next to the last retrieved one. If no records were previously retrieved, returns the first record.

---
   Documentation/mm/allocation-profiling.rst     |   5 +
   .../userspace-api/ioctl/ioctl-number.rst      |   2 +
   MAINTAINERS                                   |   1 +
   include/linux/codetag.h                       |   2 +
   include/uapi/linux/alloc_tag.h                |  54 ++++
   lib/alloc_tag.c                               | 232 +++++++++++++++++-
   lib/codetag.c                                 |  18 ++
   7 files changed, 312 insertions(+), 2 deletions(-)

create mode 100644 include/uapi/linux/alloc_tag.h

Documentation/mm/allocation-profiling.rst +5 -0
index 5389d241176a..c3a28467955f 100644
@@ -46,6 +46,11 @@ sysctl:
   Runtime info:
     /proc/allocinfo
 
+  Profiling data can be retrieved either by reading `/proc/allocinfo` directly as
+  text or programmatically via `ioctl()` calls defined in `<uapi/linux/alloc_tag.h>`.
+  The ioctl interface supports structured binary data extraction as well as filtering
+  by module name, function, file, line number, accuracy, or allocation size limits.
+
   Example output::
 
     root@moria-kvm:~# sort -g /proc/allocinfo|tail|numfmt --to=iec
Documentation/userspace-api/ioctl/ioctl-number.rst +2 -0
index 331223761fff..84f6808a8578 100644
@@ -349,6 +349,8 @@ Code  Seq#    Include File                                             Comments
                                                                          <mailto:[email protected]>
   0xA5  20-2F  linux/surface_aggregator/dtx.h                            Microsoft Surface DTX driver
                                                                          <mailto:[email protected]>
+0xA6  00-0F  uapi/linux/alloc_tag.h                                    Memory allocation profiling
+                                                                       <mailto:[email protected]>
   0xAA  00-3F  linux/uapi/linux/userfaultfd.h
   0xAB  00-1F  linux/nbd.h
   0xAC  00-1F  linux/raw.h
MAINTAINERS +1 -0
index a31f6f207afd..77f3fc487691 100644
@@ -16711,6 +16711,7 @@ S:    Maintained
   F:  Documentation/mm/allocation-profiling.rst
   F:  include/linux/alloc_tag.h
   F:  include/linux/pgalloc_tag.h
+F:   include/uapi/linux/alloc_tag.h
   F:  lib/alloc_tag.c
 
   MEMORY CONTROLLER DRIVERS
include/linux/codetag.h +2 -0
index ddae7484ca45..a25a085c2df1 100644
@@ -77,6 +77,8 @@ struct codetag_iterator {
   void codetag_lock_module_list(struct codetag_type *cttype);
   bool codetag_trylock_module_list(struct codetag_type *cttype);
   void codetag_unlock_module_list(struct codetag_type *cttype);
+unsigned long codetag_get_content_id(struct codetag_type *cttype);
+unsigned int codetag_get_count(struct codetag_type *cttype);
   struct codetag_iterator codetag_get_ct_iter(struct codetag_type *cttype);
   struct codetag *codetag_next_ct(struct codetag_iterator *iter);
 
include/uapi/linux/alloc_tag.h new file +0 -0
new file mode 100644
index 000000000000..901199bad514

include/uapi/linux/alloc_tag.h line 3

Quoted 3 lines
include/uapi/linux/alloc_tag.h new file +3 -0
@@ -0,0 +1,54 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+/*
+ *  include/linux/alloc_tag.h

nit: it should be include/uapi/linux/alloc_tag.h

Quoted 3 lines

(I guess you may have missed the comment I brought up before. It is not a critical problem though.)

Apologies, I missed that comment earlier. Included in the v4 patchset. Thanks for bringing this up.

Quoted 382 lines
Quoted 357 lines
include/uapi/linux/alloc_tag.h new file +51 -0
+ */
+
+#ifndef _UAPI_ALLOC_TAG_H
+#define _UAPI_ALLOC_TAG_H
+
+#include <linux/types.h>
+
+#define ALLOCINFO_STR_SIZE   64
+
+struct allocinfo_content_id {
+     __u64 id;
+};
+
+struct allocinfo_tag {
+     /* Longer names are trimmed */
+     char modname[ALLOCINFO_STR_SIZE];
+     char function[ALLOCINFO_STR_SIZE];
+     char filename[ALLOCINFO_STR_SIZE];
+     __u64 lineno;
+};
+
+/* The alignment ensures 32-bit compatible interfaces are not broken */
+struct allocinfo_counter {
+     __u64 bytes;
+     __u64 calls;
+     __u8 accurate;
+} __attribute__((aligned(8)));
+
+struct allocinfo_tag_data {
+     struct allocinfo_tag tag;
+     struct allocinfo_counter counter;
+};
+
+struct allocinfo_get_at {
+     __u64 pos;      /* input */
+     struct allocinfo_tag_data data;
+};
+
+#define _ALLOCINFO_IOC_CONTENT_ID    0
+#define _ALLOCINFO_IOC_GET_AT                1
+#define _ALLOCINFO_IOC_GET_NEXT              2
+
+#define ALLOCINFO_IOC_BASE           0xA6
+#define ALLOCINFO_IOC_CONTENT_ID     _IOR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_CONTENT_ID,     \
+                                          struct allocinfo_content_id)
+#define ALLOCINFO_IOC_GET_AT         _IOWR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_GET_AT,        \
+                                           struct allocinfo_get_at)
+#define ALLOCINFO_IOC_GET_NEXT               _IOR(ALLOCINFO_IOC_BASE, _ALLOCINFO_IOC_GET_NEXT,       \
+                                          struct allocinfo_tag_data)
+
+#endif /* _UAPI_ALLOC_TAG_H */
lib/alloc_tag.c +230 -2
index d9be1cf5187d..a0577215eb3d 100644
@@ -5,6 +5,7 @@
   #include <linux/gfp.h>
   #include <linux/kallsyms.h>
   #include <linux/module.h>
+#include <linux/mutex.h>
   #include <linux/page_ext.h>
   #include <linux/pgalloc_tag.h>
   #include <linux/proc_fs.h>
@@ -14,6 +15,7 @@
   #include <linux/string_choices.h>
   #include <linux/vmalloc.h>
   #include <linux/kmemleak.h>
+#include <uapi/linux/alloc_tag.h>
 
   #define ALLOCINFO_FILE_NAME         "allocinfo"
   #define MODULE_ALLOC_TAG_VMAP_SIZE  (100000UL * sizeof(struct alloc_tag))
@@ -47,6 +49,10 @@ struct allocinfo_private {
       struct codetag_iterator iter;
       struct codetag_iterator reported_iter;
       bool print_header;
+     /* ioctl uses a separate iterator not to interfere with reads */
+     struct codetag_iterator ioctl_iter;
+     bool positioned; /* seq_open_private() sets to 0 */
+     struct mutex ioctl_lock;
   };
 
   static void *allocinfo_start(struct seq_file *m, loff_t *pos)
@@ -130,6 +136,229 @@ static const struct seq_operations allocinfo_seq_op = {
       .show   = allocinfo_show,
   };
 
+/*
+ * Initializes seq_file operations and allocates private state when opening
+ * the /proc/allocinfo procfs entry.
+ */
+static int allocinfo_open(struct inode *inode, struct file *file)
+{
+     int ret;
+
+     ret = seq_open_private(file, &allocinfo_seq_op,
+                            sizeof(struct allocinfo_private));
+     if (!ret) {
+             struct seq_file *m = file->private_data;
+             struct allocinfo_private *priv = m->private;
+
+             mutex_init(&priv->ioctl_lock);
+     }
+     return ret;
+}
+
+/*
+ * Cleans up the seq_file state and frees up the private state allocated in
+ * allocinfo_open() when closing the /proc/allocinfo file descriptor.
+ */
+static int allocinfo_release(struct inode *inode, struct file *file)
+{
+     return seq_release_private(inode, file);
+}
+
+/*
+ * Returns a pointer to the suffix of a string so that its length fits within
+ * ALLOCINFO_STR_SIZE, preserving the trailing characters.
+ */
+static const char *allocinfo_str(const char *str)
+{
+     size_t len = strlen(str);
+
+     /* Keep an extra space for the trailing NULL. */
+     if (len >= ALLOCINFO_STR_SIZE)
+             str += (len - ALLOCINFO_STR_SIZE) + 1;
+     return str;
+}
+
+/* Copy a string and trim from the beginning if it's too long */
+static void allocinfo_copy_str(char *dest, const char *src)
+{
+     strscpy_pad(dest, allocinfo_str(src), ALLOCINFO_STR_SIZE);
+}
+
+/*
+ * Populates the UAPI allocinfo_tag_data structure with active runtime
+ * profiling counters extracted from the given kernel codetag.
+ */
+static void allocinfo_to_params(struct codetag *ct,
+                             struct allocinfo_tag_data *data)
+{
+     struct alloc_tag *tag = ct_to_alloc_tag(ct);
+     struct alloc_tag_counters counter = alloc_tag_read(tag);
+
+     if (ct->modname)
+             allocinfo_copy_str(data->tag.modname, ct->modname);
+     else
+             data->tag.modname[0] = '\0';
+     allocinfo_copy_str(data->tag.function, ct->function);
+     allocinfo_copy_str(data->tag.filename, ct->filename);
+     data->tag.lineno = ct->lineno;
+     data->counter.bytes = counter.bytes;
+     data->counter.calls = counter.calls;
+     data->counter.accurate = !alloc_tag_is_inaccurate(tag);
+}
+
+/*
+ * Retrieves the unique content ID representing the current allocation tag module
+ * layout, allowing userspace to detect if modules were loaded / unloaded.
+ */
+static int allocinfo_ioctl_get_content_id(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_content_id params;
+
+     codetag_lock_module_list(alloc_tag_cttype);
+     params.id = codetag_get_content_id(alloc_tag_cttype);
+     codetag_unlock_module_list(alloc_tag_cttype);
+     if (copy_to_user(arg, &params, sizeof(params)))
+             return -EFAULT;
+
+     return 0;
+}
+
+/*
+ * Seeks the ioctl iterator to the specified 0-indexed tag position, reads its
+ * profiling data and returns it to userspace.
+ */
+static int allocinfo_ioctl_get_at(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_private *priv;
+     struct codetag *ct;
+     __u64 pos;
+     struct allocinfo_get_at params = {0};
+
+     if (copy_from_user(&params, arg, sizeof(params)))
+             return -EFAULT;
+
+     priv = m->private;
+     pos = params.pos;
+
+     mutex_lock(&priv->ioctl_lock);
+     codetag_lock_module_list(alloc_tag_cttype);
+
+     if (pos >= codetag_get_count(alloc_tag_cttype)) {
+             codetag_unlock_module_list(alloc_tag_cttype);
+             mutex_unlock(&priv->ioctl_lock);
+             return -ENOENT;
+     }
+
+     /* Find the codetag */
+     priv->ioctl_iter = codetag_get_ct_iter(alloc_tag_cttype);
+     ct = codetag_next_ct(&priv->ioctl_iter);
+     while (ct && pos--)
+             ct = codetag_next_ct(&priv->ioctl_iter);
+     if (ct) {
+             allocinfo_to_params(ct, &params.data);
+             priv->positioned = true;
+     }
+
+     codetag_unlock_module_list(alloc_tag_cttype);
+     mutex_unlock(&priv->ioctl_lock);
+
+     if (!ct)
+             return -ENOENT;
+
+     if (copy_to_user(arg, &params, sizeof(params)))
+             return -EFAULT;
+
+     return 0;
+}
+
+/*
+ * Advances the ioctl iterator to the next allocation tag in the sequence and
+ * returns its profiling data to userspace.
+ */
+static int allocinfo_ioctl_get_next(struct seq_file *m, void __user *arg)
+{
+     struct allocinfo_private *priv;
+     struct codetag *ct;
+     struct allocinfo_tag_data params;
+     int ret = 0;
+
+     memset(&params, 0, sizeof(params));
+     priv = m->private;
+
+     mutex_lock(&priv->ioctl_lock);
+     codetag_lock_module_list(alloc_tag_cttype);
+
+     if (!priv->positioned) {
+             priv->ioctl_iter = codetag_get_ct_iter(alloc_tag_cttype);
+             priv->positioned = true;
+     }
+
+     ct = codetag_next_ct(&priv->ioctl_iter);
+     if (ct)
+             allocinfo_to_params(ct, &params);
+
+     if (!ct) {
+             priv->positioned = false;
+             ret = -ENOENT;
+     }
+     codetag_unlock_module_list(alloc_tag_cttype);
+     mutex_unlock(&priv->ioctl_lock);
+
+     if (ret == 0) {
+             if (copy_to_user(arg, &params, sizeof(params)))
+                     return -EFAULT;
+     }
+     return ret;
+}
+
+/*
+ * Entry point ioctl function for /proc/allocinfo routing requests to fetch the
+ * layout content ID, seek to a specific tag, or read sequential tags.
+ */
+static long allocinfo_ioctl(struct file *file, unsigned int cmd,
+                         unsigned long __arg)
+{
+     void __user *arg = (void __user *)__arg;
+     int ret;
+
+     switch (cmd) {
+     case ALLOCINFO_IOC_CONTENT_ID:
+             ret = allocinfo_ioctl_get_content_id(file->private_data, arg);
+             break;
+     case ALLOCINFO_IOC_GET_AT:
+             ret = allocinfo_ioctl_get_at(file->private_data, arg);
+             break;
+     case ALLOCINFO_IOC_GET_NEXT:
+             ret = allocinfo_ioctl_get_next(file->private_data, arg);
+             break;
+     default:
+             ret = -ENOIOCTLCMD;
+             break;
+     }
+
+     return ret;
+}
+
+#ifdef CONFIG_COMPAT
+static long allocinfo_compat_ioctl(struct file *file, unsigned int cmd,
+                                unsigned long arg)
+{
+     return allocinfo_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
+}
+#endif
+
+static const struct proc_ops allocinfo_proc_ops = {
+     .proc_open              = allocinfo_open,
+     .proc_read_iter         = seq_read_iter,
+     .proc_lseek             = seq_lseek,
+     .proc_release           = allocinfo_release,
+     .proc_ioctl             = allocinfo_ioctl,
+#ifdef CONFIG_COMPAT
+     .proc_compat_ioctl      = allocinfo_compat_ioctl,
+#endif
+
+};
+
   size_t alloc_tag_top_users(struct codetag_bytes *tags, size_t count, bool can_sleep)
   {
       struct codetag_iterator iter;
@@ -993,8 +1222,7 @@ static int __init alloc_tag_init(void)
               return 0;
       }
 
-     if (!proc_create_seq_private(ALLOCINFO_FILE_NAME, 0400, NULL, &allocinfo_seq_op,
-                                  sizeof(struct allocinfo_private), NULL)) {
+     if (!proc_create(ALLOCINFO_FILE_NAME, 0400, NULL, &allocinfo_proc_ops)) {
               pr_err("Failed to create %s file\n", ALLOCINFO_FILE_NAME);
               shutdown_mem_profiling(false);
               return -ENOMEM;
lib/codetag.c +16 -0
index 4001a7ea6675..a9cda4c962a3 100644
@@ -19,6 +19,8 @@ struct codetag_type {
       struct codetag_type_desc desc;
       /* generates unique sequence number for module load */
       unsigned long next_mod_seq;
+     /* bumped on every module load and unload */
+     unsigned long content_id;
   };
 
   struct codetag_range {
@@ -50,6 +52,20 @@ void codetag_unlock_module_list(struct codetag_type *cttype)
       up_read(&cttype->mod_lock);
   }
 
+unsigned long codetag_get_content_id(struct codetag_type *cttype)
+{
+     lockdep_assert_held(&cttype->mod_lock);
+
+     return cttype->content_id;
+}
+
+unsigned int codetag_get_count(struct codetag_type *cttype)
+{
+     lockdep_assert_held(&cttype->mod_lock);
+
+     return cttype->count;
+}
+
   struct codetag_iterator codetag_get_ct_iter(struct codetag_type *cttype)
   {
       struct codetag_iterator iter = {

lib/codetag.c static int codetag_module_init(struct codetag_type *cttype, struct module *mod) · line 223

Quoted 4 lines
lib/codetag.c +1 -0
@@ -204,6 +220,7 @@ static int codetag_module_init(struct codetag_type *cttype, struct module *mod)
 
       down_write(&cttype->mod_lock);
       cmod->mod_seq = ++cttype->next_mod_seq;
+     ++cttype->content_id;

I have a comment on the content_id bump placement.

++cttype->content_id is placed before idr_alloc and the module_load

callback. If idr_alloc fails or module_load returns an error

(While the chance of this occurring is very low.), the idr entry gets

rolled back but content_id has already been bumped. The actual

content didn't change in this case, so userspace would see a

different content_id and assume the data is inconsistent when it

isn't.

Thanks

Best Regards

Quoted 7 lines
Quoted 1 line

Hao

While I agree with your comment, I decided to place the counter increment there because the chance of failure is low. Furthermore, even if it falsely invalidates user data, the user will simply query the content again. This placement also aligns with where the previously used field (cttype->next_mod_seq) was incremented. Let me know if you still think I should move it. Thanks!

Sorry, I should have marked this as a nit when I raised the comment.

Given its low probability of occurring, it doesn't block anything for now.

The reason I raised this comment was just in case someone adds new logic

in the feature that could fail. But if that happens, we can move both next_mod_seq

and content_id down together.

Thanks

Best Regards

Quoted 9 lines
Quoted 5 lines
Quoted 2 lines

Hao

Sounds good, so for now I am not touching this patch and keeping it as is other than the file path nit inside the UAPI header file.

Actually, checkpatch is complaining about using the same filename inside of the file and hence I am dropping that comment completely.

Actually, I realized the header file lacked a proper copyright notice, so I'm including that.

Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
lib/codetag.c +1 -0
       mod_id = idr_alloc(&cttype->mod_idr, cmod, 0, 0, GFP_KERNEL);
       if (mod_id >= 0) {
               if (cttype->desc.module_load) {
@@ -368,6 +385,7 @@ void codetag_unload_module(struct module *mod)
                       cttype->count -= range_size(cttype, &cmod->range);
                       idr_remove(&cttype->mod_idr, mod_id);
                       kfree(cmod);
+                     ++cttype->content_id;
               }
               up_write(&cttype->mod_lock);
               if (found && cttype->desc.free_section_mem)