xref: /linux/mm/alloc_tag.c (revision d25711a9f32ac99d5c04a48d00d802596a8a1814)
1 // SPDX-License-Identifier: GPL-2.0-only
2 #include <linux/alloc_tag.h>
3 #include <linux/execmem.h>
4 #include <linux/fs.h>
5 #include <linux/gfp.h>
6 #include <linux/kallsyms.h>
7 #include <linux/module.h>
8 #include <linux/page_ext.h>
9 #include <linux/pgalloc_tag.h>
10 #include <linux/proc_fs.h>
11 #include <linux/rcupdate.h>
12 #include <linux/seq_buf.h>
13 #include <linux/seq_file.h>
14 #include <linux/string_choices.h>
15 #include <linux/vmalloc.h>
16 #include <linux/kmemleak.h>
17 
18 #include "internal.h"
19 #include "page_alloc.h"
20 
21 #define ALLOCINFO_FILE_NAME		"allocinfo"
22 #define MODULE_ALLOC_TAG_VMAP_SIZE	(100000UL * sizeof(struct alloc_tag))
23 #define SECTION_START(NAME)		(CODETAG_SECTION_START_PREFIX NAME)
24 #define SECTION_STOP(NAME)		(CODETAG_SECTION_STOP_PREFIX NAME)
25 
26 #ifdef CONFIG_MEM_ALLOC_PROFILING_ENABLED_BY_DEFAULT
27 static bool mem_profiling_support = true;
28 #else
29 static bool mem_profiling_support;
30 #endif
31 
32 /*
33  * Memory allocation profiling is permanently disabled and cannot be enabled.
34  * Must be called after setup_early_mem_profiling().
35  */
36 bool mem_alloc_profiling_permanently_disabled(void)
37 {
38 	return !mem_profiling_support;
39 }
40 
41 static struct codetag_type *alloc_tag_cttype;
42 
43 #ifdef CONFIG_ARCH_MODULE_NEEDS_WEAK_PER_CPU
44 DEFINE_PER_CPU(struct alloc_tag_counters, _shared_alloc_tag);
45 EXPORT_SYMBOL(_shared_alloc_tag);
46 #endif
47 
48 DEFINE_STATIC_KEY_MAYBE(CONFIG_MEM_ALLOC_PROFILING_ENABLED_BY_DEFAULT,
49 			mem_alloc_profiling_key);
50 EXPORT_SYMBOL(mem_alloc_profiling_key);
51 
52 DEFINE_STATIC_KEY_FALSE(mem_profiling_compressed);
53 
54 struct alloc_tag_kernel_section kernel_tags = { NULL, 0 };
55 unsigned long alloc_tag_ref_mask;
56 int alloc_tag_ref_offs;
57 
58 struct allocinfo_private {
59 	struct codetag_iterator iter;
60 	struct codetag_iterator reported_iter;
61 	bool print_header;
62 };
63 
64 static void *allocinfo_start(struct seq_file *m, loff_t *pos)
65 {
66 	struct allocinfo_private *priv;
67 	loff_t node = *pos;
68 
69 	priv = (struct allocinfo_private *)m->private;
70 	codetag_lock_module_list(alloc_tag_cttype);
71 	if (node == 0) {
72 		priv->print_header = true;
73 		priv->iter = codetag_get_ct_iter(alloc_tag_cttype);
74 	} else {
75 		priv->iter = priv->reported_iter;
76 	}
77 	codetag_next_ct(&priv->iter);
78 	return priv->iter.ct ? priv : NULL;
79 }
80 
81 static void *allocinfo_next(struct seq_file *m, void *arg, loff_t *pos)
82 {
83 	struct allocinfo_private *priv = (struct allocinfo_private *)arg;
84 	struct codetag *ct;
85 
86 	priv->reported_iter = priv->iter;
87 	ct = codetag_next_ct(&priv->iter);
88 	(*pos)++;
89 	if (!ct)
90 		return NULL;
91 
92 	return priv;
93 }
94 
95 static void allocinfo_stop(struct seq_file *m, void *arg)
96 {
97 	codetag_unlock_module_list(alloc_tag_cttype);
98 }
99 
100 static void print_allocinfo_header(struct seq_buf *buf)
101 {
102 	/* Output format version, so we can change it. */
103 	seq_buf_printf(buf, "allocinfo - version: 2.0\n");
104 	seq_buf_printf(buf, "#     <size>  <calls> <tag info>\n");
105 }
106 
107 static void alloc_tag_to_text(struct seq_buf *out, struct codetag *ct)
108 {
109 	struct alloc_tag *tag = ct_to_alloc_tag(ct);
110 	struct alloc_tag_counters counter = alloc_tag_read(tag);
111 	s64 bytes = counter.bytes;
112 
113 	seq_buf_printf(out, "%12lli %8llu ", bytes, counter.calls);
114 	codetag_to_text(out, ct);
115 	if (unlikely(alloc_tag_is_inaccurate(tag)))
116 		seq_buf_printf(out, " accurate:no");
117 	seq_buf_putc(out, ' ');
118 	seq_buf_putc(out, '\n');
119 }
120 
121 static int allocinfo_show(struct seq_file *m, void *arg)
122 {
123 	struct allocinfo_private *priv = (struct allocinfo_private *)arg;
124 	char *bufp;
125 	size_t n = seq_get_buf(m, &bufp);
126 	struct seq_buf buf;
127 
128 	seq_buf_init(&buf, bufp, n);
129 	if (priv->print_header) {
130 		print_allocinfo_header(&buf);
131 		priv->print_header = false;
132 	}
133 	alloc_tag_to_text(&buf, priv->iter.ct);
134 	seq_commit(m, seq_buf_used(&buf));
135 	return 0;
136 }
137 
138 static const struct seq_operations allocinfo_seq_op = {
139 	.start	= allocinfo_start,
140 	.next	= allocinfo_next,
141 	.stop	= allocinfo_stop,
142 	.show	= allocinfo_show,
143 };
144 
145 size_t alloc_tag_top_users(struct codetag_bytes *tags, size_t count, bool can_sleep)
146 {
147 	struct codetag_iterator iter;
148 	struct codetag *ct;
149 	struct codetag_bytes n;
150 	unsigned int i, nr = 0;
151 
152 	if (IS_ERR_OR_NULL(alloc_tag_cttype))
153 		return 0;
154 
155 	if (can_sleep)
156 		codetag_lock_module_list(alloc_tag_cttype);
157 	else if (!codetag_trylock_module_list(alloc_tag_cttype))
158 		return 0;
159 
160 	iter = codetag_get_ct_iter(alloc_tag_cttype);
161 	while ((ct = codetag_next_ct(&iter))) {
162 		struct alloc_tag_counters counter = alloc_tag_read(ct_to_alloc_tag(ct));
163 
164 		n.ct	= ct;
165 		n.bytes = counter.bytes;
166 
167 		for (i = 0; i < nr; i++)
168 			if (n.bytes > tags[i].bytes)
169 				break;
170 
171 		if (i < count) {
172 			nr -= nr == count;
173 			memmove(&tags[i + 1],
174 				&tags[i],
175 				sizeof(tags[0]) * (nr - i));
176 			nr++;
177 			tags[i] = n;
178 		}
179 	}
180 
181 	codetag_unlock_module_list(alloc_tag_cttype);
182 
183 	return nr;
184 }
185 
186 void pgalloc_tag_split(struct folio *folio, int old_order, int new_order)
187 {
188 	int i;
189 	struct alloc_tag *tag;
190 	unsigned int nr_pages = 1 << new_order;
191 
192 	if (!mem_alloc_profiling_enabled())
193 		return;
194 
195 	tag = __pgalloc_tag_get(&folio->page);
196 	if (!tag)
197 		return;
198 
199 	for (i = nr_pages; i < (1 << old_order); i += nr_pages) {
200 		union pgtag_ref_handle handle;
201 		union codetag_ref ref;
202 
203 		if (get_page_tag_ref(folio_page(folio, i), &ref, &handle)) {
204 			/* Set new reference to point to the original tag */
205 			alloc_tag_ref_set(&ref, tag);
206 			update_page_tag_ref(handle, &ref);
207 			put_page_tag_ref(handle);
208 		}
209 	}
210 }
211 
212 void pgalloc_tag_swap(struct folio *new, struct folio *old)
213 {
214 	union pgtag_ref_handle handle_old, handle_new;
215 	union codetag_ref ref_old, ref_new;
216 	struct alloc_tag *tag_old, *tag_new;
217 
218 	if (!mem_alloc_profiling_enabled())
219 		return;
220 
221 	tag_old = __pgalloc_tag_get(&old->page);
222 	if (!tag_old)
223 		return;
224 	tag_new = __pgalloc_tag_get(&new->page);
225 	if (!tag_new)
226 		return;
227 
228 	if (!get_page_tag_ref(&old->page, &ref_old, &handle_old))
229 		return;
230 	if (!get_page_tag_ref(&new->page, &ref_new, &handle_new)) {
231 		put_page_tag_ref(handle_old);
232 		return;
233 	}
234 
235 	/*
236 	 * Clear tag references to avoid debug warning when using
237 	 * __alloc_tag_ref_set() with non-empty reference.
238 	 */
239 	set_codetag_empty(&ref_old);
240 	set_codetag_empty(&ref_new);
241 
242 	/* swap tags */
243 	__alloc_tag_ref_set(&ref_old, tag_new);
244 	update_page_tag_ref(handle_old, &ref_old);
245 	__alloc_tag_ref_set(&ref_new, tag_old);
246 	update_page_tag_ref(handle_new, &ref_new);
247 
248 	put_page_tag_ref(handle_old);
249 	put_page_tag_ref(handle_new);
250 }
251 
252 static void shutdown_mem_profiling(bool remove_file)
253 {
254 	if (mem_alloc_profiling_enabled())
255 		static_branch_disable(&mem_alloc_profiling_key);
256 
257 	if (!mem_profiling_support)
258 		return;
259 
260 	if (remove_file)
261 		remove_proc_entry(ALLOCINFO_FILE_NAME, NULL);
262 	mem_profiling_support = false;
263 }
264 
265 void __init alloc_tag_sec_init(void)
266 {
267 	struct alloc_tag *last_codetag;
268 
269 	if (!mem_profiling_support)
270 		return;
271 
272 	if (!static_key_enabled(&mem_profiling_compressed))
273 		return;
274 
275 	kernel_tags.first_tag = (struct alloc_tag *)kallsyms_lookup_name(
276 					SECTION_START(ALLOC_TAG_SECTION_NAME));
277 	last_codetag = (struct alloc_tag *)kallsyms_lookup_name(
278 					SECTION_STOP(ALLOC_TAG_SECTION_NAME));
279 	kernel_tags.count = last_codetag - kernel_tags.first_tag;
280 
281 	/* Check if kernel tags fit into page flags */
282 	if (kernel_tags.count > (1UL << NR_UNUSED_PAGEFLAG_BITS)) {
283 		shutdown_mem_profiling(false); /* allocinfo file does not exist yet */
284 		pr_err("%lu allocation tags cannot be references using %d available page flag bits. Memory allocation profiling is disabled!\n",
285 			kernel_tags.count, NR_UNUSED_PAGEFLAG_BITS);
286 		return;
287 	}
288 
289 	alloc_tag_ref_offs = (LRU_REFS_PGOFF - NR_UNUSED_PAGEFLAG_BITS);
290 	alloc_tag_ref_mask = ((1UL << NR_UNUSED_PAGEFLAG_BITS) - 1);
291 	pr_debug("Memory allocation profiling compression is using %d page flag bits!\n",
292 		 NR_UNUSED_PAGEFLAG_BITS);
293 }
294 
295 #ifdef CONFIG_MODULES
296 
297 static struct maple_tree mod_area_mt = MTREE_INIT(mod_area_mt, MT_FLAGS_ALLOC_RANGE);
298 static struct vm_struct *vm_module_tags;
299 /* A dummy object used to indicate an unloaded module */
300 static struct module unloaded_mod;
301 /* A dummy object used to indicate a module prepended area */
302 static struct module prepend_mod;
303 
304 struct alloc_tag_module_section module_tags;
305 
306 static inline unsigned long alloc_tag_align(unsigned long val)
307 {
308 	if (!static_key_enabled(&mem_profiling_compressed)) {
309 		/* No alignment requirements when we are not indexing the tags */
310 		return val;
311 	}
312 
313 	if (val % sizeof(struct alloc_tag) == 0)
314 		return val;
315 	return ((val / sizeof(struct alloc_tag)) + 1) * sizeof(struct alloc_tag);
316 }
317 
318 static bool ensure_alignment(unsigned long align, unsigned int *prepend)
319 {
320 	if (!static_key_enabled(&mem_profiling_compressed)) {
321 		/* No alignment requirements when we are not indexing the tags */
322 		return true;
323 	}
324 
325 	/*
326 	 * If alloc_tag size is not a multiple of required alignment, tag
327 	 * indexing does not work.
328 	 */
329 	if (!IS_ALIGNED(sizeof(struct alloc_tag), align))
330 		return false;
331 
332 	/* Ensure prepend consumes multiple of alloc_tag-sized blocks */
333 	if (*prepend)
334 		*prepend = alloc_tag_align(*prepend);
335 
336 	return true;
337 }
338 
339 static inline bool tags_addressable(void)
340 {
341 	unsigned long tag_idx_count;
342 
343 	if (!static_key_enabled(&mem_profiling_compressed))
344 		return true; /* with page_ext tags are always addressable */
345 
346 	tag_idx_count = CODETAG_ID_FIRST + kernel_tags.count +
347 			module_tags.size / sizeof(struct alloc_tag);
348 
349 	return tag_idx_count < (1UL << NR_UNUSED_PAGEFLAG_BITS);
350 }
351 
352 static bool needs_section_mem(struct module *mod, unsigned long size)
353 {
354 	if (!mem_profiling_support)
355 		return false;
356 
357 	return size >= sizeof(struct alloc_tag);
358 }
359 
360 static bool clean_unused_counters(struct alloc_tag *start_tag,
361 				  struct alloc_tag *end_tag)
362 {
363 	struct alloc_tag *tag;
364 	bool ret = true;
365 
366 	for (tag = start_tag; tag <= end_tag; tag++) {
367 		struct alloc_tag_counters counter;
368 
369 		if (!tag->counters)
370 			continue;
371 
372 		counter = alloc_tag_read(tag);
373 		if (!counter.bytes) {
374 			free_percpu(tag->counters);
375 			tag->counters = NULL;
376 		} else {
377 			ret = false;
378 		}
379 	}
380 
381 	return ret;
382 }
383 
384 /* Called with mod_area_mt locked */
385 static void clean_unused_module_areas_locked(void)
386 {
387 	MA_STATE(mas, &mod_area_mt, 0, module_tags.size);
388 	struct module *val;
389 
390 	mas_for_each(&mas, val, module_tags.size) {
391 		struct alloc_tag *start_tag;
392 		struct alloc_tag *end_tag;
393 
394 		if (val != &unloaded_mod)
395 			continue;
396 
397 		/* Release area if all tags are unused */
398 		start_tag = (struct alloc_tag *)(module_tags.start_addr + mas.index);
399 		end_tag = (struct alloc_tag *)(module_tags.start_addr + mas.last);
400 		if (clean_unused_counters(start_tag, end_tag))
401 			mas_erase(&mas);
402 	}
403 }
404 
405 /* Called with mod_area_mt locked */
406 static bool find_aligned_area(struct ma_state *mas, unsigned long section_size,
407 			      unsigned long size, unsigned int prepend, unsigned long align)
408 {
409 	bool cleanup_done = false;
410 
411 repeat:
412 	/* Try finding exact size and hope the start is aligned */
413 	if (!mas_empty_area(mas, 0, section_size - 1, prepend + size)) {
414 		if (IS_ALIGNED(mas->index + prepend, align))
415 			return true;
416 
417 		/* Try finding larger area to align later */
418 		mas_reset(mas);
419 		if (!mas_empty_area(mas, 0, section_size - 1,
420 				    size + prepend + align - 1))
421 			return true;
422 	}
423 
424 	/* No free area, try cleanup stale data and repeat the search once */
425 	if (!cleanup_done) {
426 		clean_unused_module_areas_locked();
427 		cleanup_done = true;
428 		mas_reset(mas);
429 		goto repeat;
430 	}
431 
432 	return false;
433 }
434 
435 static int vm_module_tags_populate(void)
436 {
437 	unsigned long phys_end = ALIGN_DOWN(module_tags.start_addr, PAGE_SIZE) +
438 				 (vm_module_tags->nr_pages << PAGE_SHIFT);
439 	unsigned long new_end = module_tags.start_addr + module_tags.size;
440 
441 	if (phys_end < new_end) {
442 		struct page **next_page = vm_module_tags->pages + vm_module_tags->nr_pages;
443 		unsigned long old_shadow_end = ALIGN(phys_end, MODULE_ALIGN);
444 		unsigned long new_shadow_end = ALIGN(new_end, MODULE_ALIGN);
445 		unsigned long more_pages;
446 		unsigned long nr = 0;
447 
448 		more_pages = ALIGN(new_end - phys_end, PAGE_SIZE) >> PAGE_SHIFT;
449 		while (nr < more_pages) {
450 			unsigned long allocated;
451 
452 			allocated = alloc_pages_bulk_node(GFP_KERNEL | __GFP_NOWARN,
453 				NUMA_NO_NODE, more_pages - nr, next_page + nr);
454 
455 			if (!allocated)
456 				break;
457 			nr += allocated;
458 		}
459 
460 		if (nr < more_pages ||
461 		    vmap_pages_range(phys_end, phys_end + (nr << PAGE_SHIFT), PAGE_KERNEL,
462 				     next_page, PAGE_SHIFT) < 0) {
463 			release_pages_arg arg = { .pages = next_page };
464 
465 			/* Clean up and error out */
466 			release_pages(arg, nr);
467 			return -ENOMEM;
468 		}
469 
470 		vm_module_tags->nr_pages += nr;
471 
472 		/*
473 		 * Kasan allocates 1 byte of shadow for every 8 bytes of data.
474 		 * When kasan_alloc_module_shadow allocates shadow memory,
475 		 * its unit of allocation is a page.
476 		 * Therefore, here we need to align to MODULE_ALIGN.
477 		 */
478 		if (old_shadow_end < new_shadow_end)
479 			kasan_alloc_module_shadow((void *)old_shadow_end,
480 						  new_shadow_end - old_shadow_end,
481 						  GFP_KERNEL);
482 	}
483 
484 	/*
485 	 * Mark the pages as accessible, now that they are mapped.
486 	 * With hardware tag-based KASAN, marking is skipped for
487 	 * non-VM_ALLOC mappings, see __kasan_unpoison_vmalloc().
488 	 */
489 	kasan_unpoison_vmalloc((void *)module_tags.start_addr,
490 				new_end - module_tags.start_addr,
491 				KASAN_VMALLOC_PROT_NORMAL);
492 
493 	return 0;
494 }
495 
496 static void *reserve_module_tags(struct module *mod, unsigned long size,
497 				 unsigned int prepend, unsigned long align)
498 {
499 	unsigned long section_size = module_tags.end_addr - module_tags.start_addr;
500 	MA_STATE(mas, &mod_area_mt, 0, section_size - 1);
501 	unsigned long offset;
502 	void *ret = NULL;
503 
504 	/* If no tags return error */
505 	if (size < sizeof(struct alloc_tag))
506 		return ERR_PTR(-EINVAL);
507 
508 	/*
509 	 * align is always power of 2, so we can use IS_ALIGNED and ALIGN.
510 	 * align 0 or 1 means no alignment, to simplify set to 1.
511 	 */
512 	if (!align)
513 		align = 1;
514 
515 	if (!ensure_alignment(align, &prepend)) {
516 		shutdown_mem_profiling(true);
517 		pr_err("%s: alignment %lu is incompatible with allocation tag indexing. Memory allocation profiling is disabled!\n",
518 			mod->name, align);
519 		return ERR_PTR(-EINVAL);
520 	}
521 
522 	mas_lock(&mas);
523 	if (!find_aligned_area(&mas, section_size, size, prepend, align)) {
524 		ret = ERR_PTR(-ENOMEM);
525 		goto unlock;
526 	}
527 
528 	/* Mark found area as reserved */
529 	offset = mas.index;
530 	offset += prepend;
531 	offset = ALIGN(offset, align);
532 	if (offset != mas.index) {
533 		unsigned long pad_start = mas.index;
534 
535 		mas.last = offset - 1;
536 		mas_store(&mas, &prepend_mod);
537 		if (mas_is_err(&mas)) {
538 			ret = ERR_PTR(xa_err(mas.node));
539 			goto unlock;
540 		}
541 		mas.index = offset;
542 		mas.last = offset + size - 1;
543 		mas_store(&mas, mod);
544 		if (mas_is_err(&mas)) {
545 			mas.index = pad_start;
546 			mas_erase(&mas);
547 			ret = ERR_PTR(xa_err(mas.node));
548 		}
549 	} else {
550 		mas.last = offset + size - 1;
551 		mas_store(&mas, mod);
552 		if (mas_is_err(&mas))
553 			ret = ERR_PTR(xa_err(mas.node));
554 	}
555 unlock:
556 	mas_unlock(&mas);
557 
558 	if (IS_ERR(ret))
559 		return ret;
560 
561 	if (module_tags.size < offset + size) {
562 		int grow_res;
563 
564 		module_tags.size = offset + size;
565 		if (mem_alloc_profiling_enabled() && !tags_addressable()) {
566 			shutdown_mem_profiling(true);
567 			pr_warn("With module %s there are too many tags to fit in %d page flag bits. Memory allocation profiling is disabled!\n",
568 				mod->name, NR_UNUSED_PAGEFLAG_BITS);
569 		}
570 
571 		grow_res = vm_module_tags_populate();
572 		if (grow_res) {
573 			shutdown_mem_profiling(true);
574 			pr_err("Failed to allocate memory for allocation tags in the module %s. Memory allocation profiling is disabled!\n",
575 			       mod->name);
576 			return ERR_PTR(grow_res);
577 		}
578 	}
579 
580 	return (struct alloc_tag *)(module_tags.start_addr + offset);
581 }
582 
583 static void release_module_tags(struct module *mod, bool used)
584 {
585 	MA_STATE(mas, &mod_area_mt, module_tags.size, module_tags.size);
586 	struct alloc_tag *start_tag;
587 	struct alloc_tag *end_tag;
588 	struct module *val;
589 
590 	mas_lock(&mas);
591 	mas_for_each_rev(&mas, val, 0)
592 		if (val == mod)
593 			break;
594 
595 	if (!val) /* module not found */
596 		goto out;
597 
598 	if (!used)
599 		goto release_area;
600 
601 	start_tag = (struct alloc_tag *)(module_tags.start_addr + mas.index);
602 	end_tag = (struct alloc_tag *)(module_tags.start_addr + mas.last);
603 	if (!clean_unused_counters(start_tag, end_tag)) {
604 		struct alloc_tag *tag;
605 
606 		for (tag = start_tag; tag <= end_tag; tag++) {
607 			struct alloc_tag_counters counter;
608 
609 			if (!tag->counters)
610 				continue;
611 
612 			counter = alloc_tag_read(tag);
613 			pr_info("%s:%u module %s func:%s has %llu allocated at module unload\n",
614 				tag->ct.filename, tag->ct.lineno, tag->ct.modname,
615 				tag->ct.function, counter.bytes);
616 		}
617 	} else {
618 		used = false;
619 	}
620 release_area:
621 	mas_store(&mas, used ? &unloaded_mod : NULL);
622 	val = mas_prev_range(&mas, 0);
623 	if (val == &prepend_mod)
624 		mas_store(&mas, NULL);
625 out:
626 	mas_unlock(&mas);
627 }
628 
629 static int load_module(struct module *mod, struct codetag *start, struct codetag *stop)
630 {
631 	/* Allocate module alloc_tag percpu counters */
632 	struct alloc_tag *start_tag;
633 	struct alloc_tag *stop_tag;
634 	struct alloc_tag *tag;
635 
636 	/* percpu counters for core allocations are already statically allocated */
637 	if (!mod)
638 		return 0;
639 
640 	start_tag = ct_to_alloc_tag(start);
641 	stop_tag = ct_to_alloc_tag(stop);
642 	for (tag = start_tag; tag < stop_tag; tag++) {
643 		WARN_ON(tag->counters);
644 		tag->counters = alloc_percpu(struct alloc_tag_counters);
645 		if (!tag->counters) {
646 			while (--tag >= start_tag) {
647 				free_percpu(tag->counters);
648 				tag->counters = NULL;
649 			}
650 			pr_err("Failed to allocate memory for allocation tag percpu counters in the module %s\n",
651 			       mod->name);
652 			return -ENOMEM;
653 		}
654 
655 		/*
656 		 * Avoid a kmemleak false positive. The pointer to the counters is stored
657 		 * in the alloc_tag section of the module and cannot be directly accessed.
658 		 */
659 		kmemleak_ignore_percpu(tag->counters);
660 	}
661 	return 0;
662 }
663 
664 static void replace_module(struct module *mod, struct module *new_mod)
665 {
666 	MA_STATE(mas, &mod_area_mt, 0, module_tags.size);
667 	struct module *val;
668 
669 	mas_lock(&mas);
670 	mas_for_each(&mas, val, module_tags.size) {
671 		if (val != mod)
672 			continue;
673 
674 		mas_store_gfp(&mas, new_mod, GFP_KERNEL);
675 		break;
676 	}
677 	mas_unlock(&mas);
678 }
679 
680 static int __init alloc_mod_tags_mem(void)
681 {
682 	/* Map space to copy allocation tags */
683 	vm_module_tags = execmem_vmap(MODULE_ALLOC_TAG_VMAP_SIZE);
684 	if (!vm_module_tags) {
685 		pr_err("Failed to map %lu bytes for module allocation tags\n",
686 			MODULE_ALLOC_TAG_VMAP_SIZE);
687 		module_tags.start_addr = 0;
688 		return -ENOMEM;
689 	}
690 
691 	vm_module_tags->pages = kmalloc_objs(struct page *,
692 					     get_vm_area_size(vm_module_tags) >> PAGE_SHIFT,
693 					     GFP_KERNEL | __GFP_ZERO);
694 	if (!vm_module_tags->pages) {
695 		free_vm_area(vm_module_tags);
696 		return -ENOMEM;
697 	}
698 
699 	module_tags.start_addr = (unsigned long)vm_module_tags->addr;
700 	module_tags.end_addr = module_tags.start_addr + MODULE_ALLOC_TAG_VMAP_SIZE;
701 	/* Ensure the base is alloc_tag aligned when required for indexing */
702 	module_tags.start_addr = alloc_tag_align(module_tags.start_addr);
703 
704 	return 0;
705 }
706 
707 static void __init free_mod_tags_mem(void)
708 {
709 	release_pages_arg arg = { .pages = vm_module_tags->pages };
710 
711 	module_tags.start_addr = 0;
712 	release_pages(arg, vm_module_tags->nr_pages);
713 	kfree(vm_module_tags->pages);
714 	free_vm_area(vm_module_tags);
715 }
716 
717 #else /* CONFIG_MODULES */
718 
719 static inline int alloc_mod_tags_mem(void) { return 0; }
720 static inline void free_mod_tags_mem(void) {}
721 
722 #endif /* CONFIG_MODULES */
723 
724 /* See: Documentation/mm/allocation-profiling.rst */
725 static int __init setup_early_mem_profiling(char *str)
726 {
727 	bool compressed = false;
728 	bool enable;
729 
730 	if (!str || !str[0])
731 		return -EINVAL;
732 
733 	if (!strncmp(str, "never", 5)) {
734 		enable = false;
735 		mem_profiling_support = false;
736 		pr_info("Memory allocation profiling is disabled!\n");
737 	} else {
738 		char *token = strsep(&str, ",");
739 
740 		if (kstrtobool(token, &enable))
741 			return -EINVAL;
742 
743 		if (str) {
744 
745 			if (strcmp(str, "compressed"))
746 				return -EINVAL;
747 
748 			compressed = true;
749 		}
750 		mem_profiling_support = true;
751 		pr_info("Memory allocation profiling is enabled %s compression and is turned %s!\n",
752 			compressed ? "with" : "without", str_on_off(enable));
753 	}
754 
755 	if (enable != mem_alloc_profiling_enabled()) {
756 		if (enable)
757 			static_branch_enable(&mem_alloc_profiling_key);
758 		else
759 			static_branch_disable(&mem_alloc_profiling_key);
760 	}
761 	if (compressed != static_key_enabled(&mem_profiling_compressed)) {
762 		if (compressed)
763 			static_branch_enable(&mem_profiling_compressed);
764 		else
765 			static_branch_disable(&mem_profiling_compressed);
766 	}
767 
768 	return 0;
769 }
770 early_param("sysctl.vm.mem_profiling", setup_early_mem_profiling);
771 
772 static __init bool need_page_alloc_tagging(void)
773 {
774 	if (static_key_enabled(&mem_profiling_compressed))
775 		return false;
776 
777 	return mem_profiling_support;
778 }
779 
780 #ifdef CONFIG_MEM_ALLOC_PROFILING_DEBUG
781 /*
782  * Track page allocations before page_ext is initialized.
783  * Some pages are allocated before page_ext becomes available, leaving
784  * their codetag uninitialized. Track these early PFNs so we can clear
785  * their codetag refs later to avoid warnings when they are freed.
786  *
787  * Each page is cast to a pfn_pool: the first few bytes hold metadata
788  * (next pointer and slot count), the remainder stores PFNs.
789  */
790 struct pfn_pool {
791 	struct pfn_pool *next;
792 	atomic_t count;
793 	unsigned long pfns[];
794 };
795 
796 #define PFN_POOL_SIZE			((PAGE_SIZE - offsetof(struct pfn_pool, pfns)) / \
797 					 sizeof(unsigned long))
798 static struct pfn_pool *current_pfn_pool __initdata;
799 
800 static void __init __alloc_tag_add_early_pfn(unsigned long pfn)
801 {
802 	struct pfn_pool *pool;
803 	int idx;
804 
805 	do {
806 		pool = READ_ONCE(current_pfn_pool);
807 		if (!pool || atomic_read(&pool->count) >= PFN_POOL_SIZE) {
808 			struct page *new_page = __alloc_pages(__GFP_HIGH, 0, numa_mem_id(),
809 							      NULL, ALLOC_NO_CODETAG);
810 			struct pfn_pool *new;
811 
812 			if (!new_page) {
813 				pr_warn_once("early PFN tracking page allocation failed\n");
814 				return;
815 			}
816 			new = page_address(new_page);
817 			new->next = pool;
818 			atomic_set(&new->count, 0);
819 			if (cmpxchg(&current_pfn_pool, pool, new) != pool) {
820 				clear_page_tag_ref(new_page);
821 				__free_page(new_page);
822 				continue;
823 			}
824 			pool = new;
825 		}
826 		idx = atomic_read(&pool->count);
827 		if (idx >= PFN_POOL_SIZE)
828 			continue;
829 		if (atomic_cmpxchg(&pool->count, idx, idx + 1) == idx)
830 			break;
831 	} while (1);
832 
833 	pool->pfns[idx] = pfn;
834 }
835 
836 typedef void alloc_tag_add_func(unsigned long pfn);
837 static alloc_tag_add_func __rcu *alloc_tag_add_early_pfn_ptr __refdata =
838 	RCU_INITIALIZER(__alloc_tag_add_early_pfn);
839 
840 void alloc_tag_add_early_pfn(unsigned long pfn, unsigned int alloc_flags)
841 {
842 	alloc_tag_add_func *alloc_tag_add;
843 
844 	if (static_key_enabled(&mem_profiling_compressed))
845 		return;
846 
847 	/* Skip allocations for the tracking list itself to avoid recursion. */
848 	if (alloc_flags & ALLOC_NO_CODETAG)
849 		return;
850 
851 	rcu_read_lock();
852 	alloc_tag_add = rcu_dereference(alloc_tag_add_early_pfn_ptr);
853 	if (alloc_tag_add)
854 		alloc_tag_add(pfn);
855 	rcu_read_unlock();
856 }
857 
858 static void __init clear_early_alloc_pfn_tag_refs(void)
859 {
860 	struct pfn_pool *pool, *next;
861 	struct page *page;
862 	int i;
863 
864 	if (static_key_enabled(&mem_profiling_compressed))
865 		return;
866 
867 	rcu_assign_pointer(alloc_tag_add_early_pfn_ptr, NULL);
868 	/* Make sure we are not racing with __alloc_tag_add_early_pfn() */
869 	synchronize_rcu();
870 
871 	for (pool = current_pfn_pool; pool; pool = next) {
872 		int nr_pfns = atomic_read(&pool->count);
873 
874 		for (i = 0; i < nr_pfns; i++) {
875 			unsigned long pfn = pool->pfns[i];
876 
877 			if (pfn_valid(pfn)) {
878 				union pgtag_ref_handle handle;
879 				union codetag_ref ref;
880 
881 				if (get_page_tag_ref(pfn_to_page(pfn), &ref, &handle)) {
882 					/*
883 					 * An early-allocated page could be freed and reallocated
884 					 * after its page_ext is initialized but before we clear it.
885 					 * In that case, it already has a valid tag set.
886 					 * We should not overwrite that valid tag
887 					 * with CODETAG_EMPTY.
888 					 *
889 					 * Note: there is still a small race window between checking
890 					 * ref.ct and calling set_codetag_empty(). We accept this
891 					 * race as it's unlikely and the extra complexity of atomic
892 					 * cmpxchg is not worth it for this debug-only code path.
893 					 */
894 					if (ref.ct) {
895 						put_page_tag_ref(handle);
896 						continue;
897 					}
898 
899 					set_codetag_empty(&ref);
900 					update_page_tag_ref(handle, &ref);
901 					put_page_tag_ref(handle);
902 				}
903 			}
904 		}
905 
906 		next = pool->next;
907 		page = virt_to_page(pool);
908 		clear_page_tag_ref(page);
909 		__free_page(page);
910 	}
911 }
912 #else /* !CONFIG_MEM_ALLOC_PROFILING_DEBUG */
913 static inline void __init clear_early_alloc_pfn_tag_refs(void) {}
914 #endif /* CONFIG_MEM_ALLOC_PROFILING_DEBUG */
915 
916 static __init void init_page_alloc_tagging(void)
917 {
918 	clear_early_alloc_pfn_tag_refs();
919 }
920 
921 struct page_ext_operations page_alloc_tagging_ops = {
922 	.size = sizeof(union codetag_ref),
923 	.need = need_page_alloc_tagging,
924 	.init = init_page_alloc_tagging,
925 };
926 EXPORT_SYMBOL(page_alloc_tagging_ops);
927 
928 #ifdef CONFIG_SYSCTL
929 /*
930  * Not using proc_do_static_key() directly to prevent enabling profiling
931  * after it was shut down.
932  */
933 static int proc_mem_profiling_handler(const struct ctl_table *table, int write,
934 				      void *buffer, size_t *lenp, loff_t *ppos)
935 {
936 	if (write) {
937 		/*
938 		 * Call from do_sysctl_args() which is a no-op since the same
939 		 * value was already set by setup_early_mem_profiling.
940 		 * Return success to avoid warnings from do_sysctl_args().
941 		 */
942 		if (!current->mm)
943 			return 0;
944 
945 #ifdef CONFIG_MEM_ALLOC_PROFILING_DEBUG
946 		/* User can't toggle profiling while debugging */
947 		return -EACCES;
948 #endif
949 		if (!mem_profiling_support)
950 			return -EINVAL;
951 	}
952 
953 	return proc_do_static_key(table, write, buffer, lenp, ppos);
954 }
955 
956 
957 static const struct ctl_table memory_allocation_profiling_sysctls[] = {
958 	{
959 		.procname	= "mem_profiling",
960 		.data		= &mem_alloc_profiling_key,
961 		.mode		= 0644,
962 		.proc_handler	= proc_mem_profiling_handler,
963 	},
964 };
965 
966 static void __init sysctl_init(void)
967 {
968 	register_sysctl_init("vm", memory_allocation_profiling_sysctls);
969 }
970 #else /* CONFIG_SYSCTL */
971 static inline void sysctl_init(void) {}
972 #endif /* CONFIG_SYSCTL */
973 
974 static int __init alloc_tag_init(void)
975 {
976 	const struct codetag_type_desc desc = {
977 		.section		= ALLOC_TAG_SECTION_NAME,
978 		.tag_size		= sizeof(struct alloc_tag),
979 #ifdef CONFIG_MODULES
980 		.needs_section_mem	= needs_section_mem,
981 		.alloc_section_mem	= reserve_module_tags,
982 		.free_section_mem	= release_module_tags,
983 		.module_load		= load_module,
984 		.module_replaced	= replace_module,
985 #endif
986 	};
987 	int res;
988 
989 	sysctl_init();
990 
991 	if (!mem_profiling_support) {
992 		pr_info("Memory allocation profiling is not supported!\n");
993 		return 0;
994 	}
995 
996 	if (!proc_create_seq_private(ALLOCINFO_FILE_NAME, 0400, NULL, &allocinfo_seq_op,
997 				     sizeof(struct allocinfo_private), NULL)) {
998 		pr_err("Failed to create %s file\n", ALLOCINFO_FILE_NAME);
999 		shutdown_mem_profiling(false);
1000 		return -ENOMEM;
1001 	}
1002 
1003 	res = alloc_mod_tags_mem();
1004 	if (res) {
1005 		pr_err("Failed to reserve address space for module tags, errno = %d\n", res);
1006 		shutdown_mem_profiling(true);
1007 		return res;
1008 	}
1009 
1010 	alloc_tag_cttype = codetag_register_type(&desc);
1011 	if (IS_ERR(alloc_tag_cttype)) {
1012 		pr_err("Allocation tags registration failed, errno = %pe\n", alloc_tag_cttype);
1013 		free_mod_tags_mem();
1014 		shutdown_mem_profiling(true);
1015 		return PTR_ERR(alloc_tag_cttype);
1016 	}
1017 
1018 	return 0;
1019 }
1020 module_init(alloc_tag_init);
1021