xref: /linux/lib/alloc_tag.c (revision 995832b2cebe6969d1b42635db698803ee31294d)
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 #define ALLOCINFO_FILE_NAME		"allocinfo"
19 #define MODULE_ALLOC_TAG_VMAP_SIZE	(100000UL * sizeof(struct alloc_tag))
20 #define SECTION_START(NAME)		(CODETAG_SECTION_START_PREFIX NAME)
21 #define SECTION_STOP(NAME)		(CODETAG_SECTION_STOP_PREFIX NAME)
22 
23 #ifdef CONFIG_MEM_ALLOC_PROFILING_ENABLED_BY_DEFAULT
24 static bool mem_profiling_support = true;
25 #else
26 static bool mem_profiling_support;
27 #endif
28 
29 static struct codetag_type *alloc_tag_cttype;
30 
31 #ifdef CONFIG_ARCH_MODULE_NEEDS_WEAK_PER_CPU
32 DEFINE_PER_CPU(struct alloc_tag_counters, _shared_alloc_tag);
33 EXPORT_SYMBOL(_shared_alloc_tag);
34 #endif
35 
36 DEFINE_STATIC_KEY_MAYBE(CONFIG_MEM_ALLOC_PROFILING_ENABLED_BY_DEFAULT,
37 			mem_alloc_profiling_key);
38 EXPORT_SYMBOL(mem_alloc_profiling_key);
39 
40 DEFINE_STATIC_KEY_FALSE(mem_profiling_compressed);
41 
42 struct alloc_tag_kernel_section kernel_tags = { NULL, 0 };
43 unsigned long alloc_tag_ref_mask;
44 int alloc_tag_ref_offs;
45 
46 struct allocinfo_private {
47 	struct codetag_iterator iter;
48 	struct codetag_iterator reported_iter;
49 	bool print_header;
50 };
51 
52 static void *allocinfo_start(struct seq_file *m, loff_t *pos)
53 {
54 	struct allocinfo_private *priv;
55 	loff_t node = *pos;
56 
57 	priv = (struct allocinfo_private *)m->private;
58 	codetag_lock_module_list(alloc_tag_cttype);
59 	if (node == 0) {
60 		priv->print_header = true;
61 		priv->iter = codetag_get_ct_iter(alloc_tag_cttype);
62 	} else {
63 		priv->iter = priv->reported_iter;
64 	}
65 	codetag_next_ct(&priv->iter);
66 	return priv->iter.ct ? priv : NULL;
67 }
68 
69 static void *allocinfo_next(struct seq_file *m, void *arg, loff_t *pos)
70 {
71 	struct allocinfo_private *priv = (struct allocinfo_private *)arg;
72 	struct codetag *ct;
73 
74 	priv->reported_iter = priv->iter;
75 	ct = codetag_next_ct(&priv->iter);
76 	(*pos)++;
77 	if (!ct)
78 		return NULL;
79 
80 	return priv;
81 }
82 
83 static void allocinfo_stop(struct seq_file *m, void *arg)
84 {
85 	codetag_unlock_module_list(alloc_tag_cttype);
86 }
87 
88 static void print_allocinfo_header(struct seq_buf *buf)
89 {
90 	/* Output format version, so we can change it. */
91 	seq_buf_printf(buf, "allocinfo - version: 2.0\n");
92 	seq_buf_printf(buf, "#     <size>  <calls> <tag info>\n");
93 }
94 
95 static void alloc_tag_to_text(struct seq_buf *out, struct codetag *ct)
96 {
97 	struct alloc_tag *tag = ct_to_alloc_tag(ct);
98 	struct alloc_tag_counters counter = alloc_tag_read(tag);
99 	s64 bytes = counter.bytes;
100 
101 	seq_buf_printf(out, "%12lli %8llu ", bytes, counter.calls);
102 	codetag_to_text(out, ct);
103 	if (unlikely(alloc_tag_is_inaccurate(tag)))
104 		seq_buf_printf(out, " accurate:no");
105 	seq_buf_putc(out, ' ');
106 	seq_buf_putc(out, '\n');
107 }
108 
109 static int allocinfo_show(struct seq_file *m, void *arg)
110 {
111 	struct allocinfo_private *priv = (struct allocinfo_private *)arg;
112 	char *bufp;
113 	size_t n = seq_get_buf(m, &bufp);
114 	struct seq_buf buf;
115 
116 	seq_buf_init(&buf, bufp, n);
117 	if (priv->print_header) {
118 		print_allocinfo_header(&buf);
119 		priv->print_header = false;
120 	}
121 	alloc_tag_to_text(&buf, priv->iter.ct);
122 	seq_commit(m, seq_buf_used(&buf));
123 	return 0;
124 }
125 
126 static const struct seq_operations allocinfo_seq_op = {
127 	.start	= allocinfo_start,
128 	.next	= allocinfo_next,
129 	.stop	= allocinfo_stop,
130 	.show	= allocinfo_show,
131 };
132 
133 size_t alloc_tag_top_users(struct codetag_bytes *tags, size_t count, bool can_sleep)
134 {
135 	struct codetag_iterator iter;
136 	struct codetag *ct;
137 	struct codetag_bytes n;
138 	unsigned int i, nr = 0;
139 
140 	if (IS_ERR_OR_NULL(alloc_tag_cttype))
141 		return 0;
142 
143 	if (can_sleep)
144 		codetag_lock_module_list(alloc_tag_cttype);
145 	else if (!codetag_trylock_module_list(alloc_tag_cttype))
146 		return 0;
147 
148 	iter = codetag_get_ct_iter(alloc_tag_cttype);
149 	while ((ct = codetag_next_ct(&iter))) {
150 		struct alloc_tag_counters counter = alloc_tag_read(ct_to_alloc_tag(ct));
151 
152 		n.ct	= ct;
153 		n.bytes = counter.bytes;
154 
155 		for (i = 0; i < nr; i++)
156 			if (n.bytes > tags[i].bytes)
157 				break;
158 
159 		if (i < count) {
160 			nr -= nr == count;
161 			memmove(&tags[i + 1],
162 				&tags[i],
163 				sizeof(tags[0]) * (nr - i));
164 			nr++;
165 			tags[i] = n;
166 		}
167 	}
168 
169 	codetag_unlock_module_list(alloc_tag_cttype);
170 
171 	return nr;
172 }
173 
174 void pgalloc_tag_split(struct folio *folio, int old_order, int new_order)
175 {
176 	int i;
177 	struct alloc_tag *tag;
178 	unsigned int nr_pages = 1 << new_order;
179 
180 	if (!mem_alloc_profiling_enabled())
181 		return;
182 
183 	tag = __pgalloc_tag_get(&folio->page);
184 	if (!tag)
185 		return;
186 
187 	for (i = nr_pages; i < (1 << old_order); i += nr_pages) {
188 		union pgtag_ref_handle handle;
189 		union codetag_ref ref;
190 
191 		if (get_page_tag_ref(folio_page(folio, i), &ref, &handle)) {
192 			/* Set new reference to point to the original tag */
193 			alloc_tag_ref_set(&ref, tag);
194 			update_page_tag_ref(handle, &ref);
195 			put_page_tag_ref(handle);
196 		}
197 	}
198 }
199 
200 void pgalloc_tag_swap(struct folio *new, struct folio *old)
201 {
202 	union pgtag_ref_handle handle_old, handle_new;
203 	union codetag_ref ref_old, ref_new;
204 	struct alloc_tag *tag_old, *tag_new;
205 
206 	if (!mem_alloc_profiling_enabled())
207 		return;
208 
209 	tag_old = __pgalloc_tag_get(&old->page);
210 	if (!tag_old)
211 		return;
212 	tag_new = __pgalloc_tag_get(&new->page);
213 	if (!tag_new)
214 		return;
215 
216 	if (!get_page_tag_ref(&old->page, &ref_old, &handle_old))
217 		return;
218 	if (!get_page_tag_ref(&new->page, &ref_new, &handle_new)) {
219 		put_page_tag_ref(handle_old);
220 		return;
221 	}
222 
223 	/*
224 	 * Clear tag references to avoid debug warning when using
225 	 * __alloc_tag_ref_set() with non-empty reference.
226 	 */
227 	set_codetag_empty(&ref_old);
228 	set_codetag_empty(&ref_new);
229 
230 	/* swap tags */
231 	__alloc_tag_ref_set(&ref_old, tag_new);
232 	update_page_tag_ref(handle_old, &ref_old);
233 	__alloc_tag_ref_set(&ref_new, tag_old);
234 	update_page_tag_ref(handle_new, &ref_new);
235 
236 	put_page_tag_ref(handle_old);
237 	put_page_tag_ref(handle_new);
238 }
239 
240 static void shutdown_mem_profiling(bool remove_file)
241 {
242 	if (mem_alloc_profiling_enabled())
243 		static_branch_disable(&mem_alloc_profiling_key);
244 
245 	if (!mem_profiling_support)
246 		return;
247 
248 	if (remove_file)
249 		remove_proc_entry(ALLOCINFO_FILE_NAME, NULL);
250 	mem_profiling_support = false;
251 }
252 
253 void __init alloc_tag_sec_init(void)
254 {
255 	struct alloc_tag *last_codetag;
256 
257 	if (!mem_profiling_support)
258 		return;
259 
260 	if (!static_key_enabled(&mem_profiling_compressed))
261 		return;
262 
263 	kernel_tags.first_tag = (struct alloc_tag *)kallsyms_lookup_name(
264 					SECTION_START(ALLOC_TAG_SECTION_NAME));
265 	last_codetag = (struct alloc_tag *)kallsyms_lookup_name(
266 					SECTION_STOP(ALLOC_TAG_SECTION_NAME));
267 	kernel_tags.count = last_codetag - kernel_tags.first_tag;
268 
269 	/* Check if kernel tags fit into page flags */
270 	if (kernel_tags.count > (1UL << NR_UNUSED_PAGEFLAG_BITS)) {
271 		shutdown_mem_profiling(false); /* allocinfo file does not exist yet */
272 		pr_err("%lu allocation tags cannot be references using %d available page flag bits. Memory allocation profiling is disabled!\n",
273 			kernel_tags.count, NR_UNUSED_PAGEFLAG_BITS);
274 		return;
275 	}
276 
277 	alloc_tag_ref_offs = (LRU_REFS_PGOFF - NR_UNUSED_PAGEFLAG_BITS);
278 	alloc_tag_ref_mask = ((1UL << NR_UNUSED_PAGEFLAG_BITS) - 1);
279 	pr_debug("Memory allocation profiling compression is using %d page flag bits!\n",
280 		 NR_UNUSED_PAGEFLAG_BITS);
281 }
282 
283 #ifdef CONFIG_MODULES
284 
285 static struct maple_tree mod_area_mt = MTREE_INIT(mod_area_mt, MT_FLAGS_ALLOC_RANGE);
286 static struct vm_struct *vm_module_tags;
287 /* A dummy object used to indicate an unloaded module */
288 static struct module unloaded_mod;
289 /* A dummy object used to indicate a module prepended area */
290 static struct module prepend_mod;
291 
292 struct alloc_tag_module_section module_tags;
293 
294 static inline unsigned long alloc_tag_align(unsigned long val)
295 {
296 	if (!static_key_enabled(&mem_profiling_compressed)) {
297 		/* No alignment requirements when we are not indexing the tags */
298 		return val;
299 	}
300 
301 	if (val % sizeof(struct alloc_tag) == 0)
302 		return val;
303 	return ((val / sizeof(struct alloc_tag)) + 1) * sizeof(struct alloc_tag);
304 }
305 
306 static bool ensure_alignment(unsigned long align, unsigned int *prepend)
307 {
308 	if (!static_key_enabled(&mem_profiling_compressed)) {
309 		/* No alignment requirements when we are not indexing the tags */
310 		return true;
311 	}
312 
313 	/*
314 	 * If alloc_tag size is not a multiple of required alignment, tag
315 	 * indexing does not work.
316 	 */
317 	if (!IS_ALIGNED(sizeof(struct alloc_tag), align))
318 		return false;
319 
320 	/* Ensure prepend consumes multiple of alloc_tag-sized blocks */
321 	if (*prepend)
322 		*prepend = alloc_tag_align(*prepend);
323 
324 	return true;
325 }
326 
327 static inline bool tags_addressable(void)
328 {
329 	unsigned long tag_idx_count;
330 
331 	if (!static_key_enabled(&mem_profiling_compressed))
332 		return true; /* with page_ext tags are always addressable */
333 
334 	tag_idx_count = CODETAG_ID_FIRST + kernel_tags.count +
335 			module_tags.size / sizeof(struct alloc_tag);
336 
337 	return tag_idx_count < (1UL << NR_UNUSED_PAGEFLAG_BITS);
338 }
339 
340 static bool needs_section_mem(struct module *mod, unsigned long size)
341 {
342 	if (!mem_profiling_support)
343 		return false;
344 
345 	return size >= sizeof(struct alloc_tag);
346 }
347 
348 static bool clean_unused_counters(struct alloc_tag *start_tag,
349 				  struct alloc_tag *end_tag)
350 {
351 	struct alloc_tag *tag;
352 	bool ret = true;
353 
354 	for (tag = start_tag; tag <= end_tag; tag++) {
355 		struct alloc_tag_counters counter;
356 
357 		if (!tag->counters)
358 			continue;
359 
360 		counter = alloc_tag_read(tag);
361 		if (!counter.bytes) {
362 			free_percpu(tag->counters);
363 			tag->counters = NULL;
364 		} else {
365 			ret = false;
366 		}
367 	}
368 
369 	return ret;
370 }
371 
372 /* Called with mod_area_mt locked */
373 static void clean_unused_module_areas_locked(void)
374 {
375 	MA_STATE(mas, &mod_area_mt, 0, module_tags.size);
376 	struct module *val;
377 
378 	mas_for_each(&mas, val, module_tags.size) {
379 		struct alloc_tag *start_tag;
380 		struct alloc_tag *end_tag;
381 
382 		if (val != &unloaded_mod)
383 			continue;
384 
385 		/* Release area if all tags are unused */
386 		start_tag = (struct alloc_tag *)(module_tags.start_addr + mas.index);
387 		end_tag = (struct alloc_tag *)(module_tags.start_addr + mas.last);
388 		if (clean_unused_counters(start_tag, end_tag))
389 			mas_erase(&mas);
390 	}
391 }
392 
393 /* Called with mod_area_mt locked */
394 static bool find_aligned_area(struct ma_state *mas, unsigned long section_size,
395 			      unsigned long size, unsigned int prepend, unsigned long align)
396 {
397 	bool cleanup_done = false;
398 
399 repeat:
400 	/* Try finding exact size and hope the start is aligned */
401 	if (!mas_empty_area(mas, 0, section_size - 1, prepend + size)) {
402 		if (IS_ALIGNED(mas->index + prepend, align))
403 			return true;
404 
405 		/* Try finding larger area to align later */
406 		mas_reset(mas);
407 		if (!mas_empty_area(mas, 0, section_size - 1,
408 				    size + prepend + align - 1))
409 			return true;
410 	}
411 
412 	/* No free area, try cleanup stale data and repeat the search once */
413 	if (!cleanup_done) {
414 		clean_unused_module_areas_locked();
415 		cleanup_done = true;
416 		mas_reset(mas);
417 		goto repeat;
418 	}
419 
420 	return false;
421 }
422 
423 static int vm_module_tags_populate(void)
424 {
425 	unsigned long phys_end = ALIGN_DOWN(module_tags.start_addr, PAGE_SIZE) +
426 				 (vm_module_tags->nr_pages << PAGE_SHIFT);
427 	unsigned long new_end = module_tags.start_addr + module_tags.size;
428 
429 	if (phys_end < new_end) {
430 		struct page **next_page = vm_module_tags->pages + vm_module_tags->nr_pages;
431 		unsigned long old_shadow_end = ALIGN(phys_end, MODULE_ALIGN);
432 		unsigned long new_shadow_end = ALIGN(new_end, MODULE_ALIGN);
433 		unsigned long more_pages;
434 		unsigned long nr = 0;
435 
436 		more_pages = ALIGN(new_end - phys_end, PAGE_SIZE) >> PAGE_SHIFT;
437 		while (nr < more_pages) {
438 			unsigned long allocated;
439 
440 			allocated = alloc_pages_bulk_node(GFP_KERNEL | __GFP_NOWARN,
441 				NUMA_NO_NODE, more_pages - nr, next_page + nr);
442 
443 			if (!allocated)
444 				break;
445 			nr += allocated;
446 		}
447 
448 		if (nr < more_pages ||
449 		    vmap_pages_range(phys_end, phys_end + (nr << PAGE_SHIFT), PAGE_KERNEL,
450 				     next_page, PAGE_SHIFT) < 0) {
451 			release_pages_arg arg = { .pages = next_page };
452 
453 			/* Clean up and error out */
454 			release_pages(arg, nr);
455 			return -ENOMEM;
456 		}
457 
458 		vm_module_tags->nr_pages += nr;
459 
460 		/*
461 		 * Kasan allocates 1 byte of shadow for every 8 bytes of data.
462 		 * When kasan_alloc_module_shadow allocates shadow memory,
463 		 * its unit of allocation is a page.
464 		 * Therefore, here we need to align to MODULE_ALIGN.
465 		 */
466 		if (old_shadow_end < new_shadow_end)
467 			kasan_alloc_module_shadow((void *)old_shadow_end,
468 						  new_shadow_end - old_shadow_end,
469 						  GFP_KERNEL);
470 	}
471 
472 	/*
473 	 * Mark the pages as accessible, now that they are mapped.
474 	 * With hardware tag-based KASAN, marking is skipped for
475 	 * non-VM_ALLOC mappings, see __kasan_unpoison_vmalloc().
476 	 */
477 	kasan_unpoison_vmalloc((void *)module_tags.start_addr,
478 				new_end - module_tags.start_addr,
479 				KASAN_VMALLOC_PROT_NORMAL);
480 
481 	return 0;
482 }
483 
484 static void *reserve_module_tags(struct module *mod, unsigned long size,
485 				 unsigned int prepend, unsigned long align)
486 {
487 	unsigned long section_size = module_tags.end_addr - module_tags.start_addr;
488 	MA_STATE(mas, &mod_area_mt, 0, section_size - 1);
489 	unsigned long offset;
490 	void *ret = NULL;
491 
492 	/* If no tags return error */
493 	if (size < sizeof(struct alloc_tag))
494 		return ERR_PTR(-EINVAL);
495 
496 	/*
497 	 * align is always power of 2, so we can use IS_ALIGNED and ALIGN.
498 	 * align 0 or 1 means no alignment, to simplify set to 1.
499 	 */
500 	if (!align)
501 		align = 1;
502 
503 	if (!ensure_alignment(align, &prepend)) {
504 		shutdown_mem_profiling(true);
505 		pr_err("%s: alignment %lu is incompatible with allocation tag indexing. Memory allocation profiling is disabled!\n",
506 			mod->name, align);
507 		return ERR_PTR(-EINVAL);
508 	}
509 
510 	mas_lock(&mas);
511 	if (!find_aligned_area(&mas, section_size, size, prepend, align)) {
512 		ret = ERR_PTR(-ENOMEM);
513 		goto unlock;
514 	}
515 
516 	/* Mark found area as reserved */
517 	offset = mas.index;
518 	offset += prepend;
519 	offset = ALIGN(offset, align);
520 	if (offset != mas.index) {
521 		unsigned long pad_start = mas.index;
522 
523 		mas.last = offset - 1;
524 		mas_store(&mas, &prepend_mod);
525 		if (mas_is_err(&mas)) {
526 			ret = ERR_PTR(xa_err(mas.node));
527 			goto unlock;
528 		}
529 		mas.index = offset;
530 		mas.last = offset + size - 1;
531 		mas_store(&mas, mod);
532 		if (mas_is_err(&mas)) {
533 			mas.index = pad_start;
534 			mas_erase(&mas);
535 			ret = ERR_PTR(xa_err(mas.node));
536 		}
537 	} else {
538 		mas.last = offset + size - 1;
539 		mas_store(&mas, mod);
540 		if (mas_is_err(&mas))
541 			ret = ERR_PTR(xa_err(mas.node));
542 	}
543 unlock:
544 	mas_unlock(&mas);
545 
546 	if (IS_ERR(ret))
547 		return ret;
548 
549 	if (module_tags.size < offset + size) {
550 		int grow_res;
551 
552 		module_tags.size = offset + size;
553 		if (mem_alloc_profiling_enabled() && !tags_addressable()) {
554 			shutdown_mem_profiling(true);
555 			pr_warn("With module %s there are too many tags to fit in %d page flag bits. Memory allocation profiling is disabled!\n",
556 				mod->name, NR_UNUSED_PAGEFLAG_BITS);
557 		}
558 
559 		grow_res = vm_module_tags_populate();
560 		if (grow_res) {
561 			shutdown_mem_profiling(true);
562 			pr_err("Failed to allocate memory for allocation tags in the module %s. Memory allocation profiling is disabled!\n",
563 			       mod->name);
564 			return ERR_PTR(grow_res);
565 		}
566 	}
567 
568 	return (struct alloc_tag *)(module_tags.start_addr + offset);
569 }
570 
571 static void release_module_tags(struct module *mod, bool used)
572 {
573 	MA_STATE(mas, &mod_area_mt, module_tags.size, module_tags.size);
574 	struct alloc_tag *start_tag;
575 	struct alloc_tag *end_tag;
576 	struct module *val;
577 
578 	mas_lock(&mas);
579 	mas_for_each_rev(&mas, val, 0)
580 		if (val == mod)
581 			break;
582 
583 	if (!val) /* module not found */
584 		goto out;
585 
586 	if (!used)
587 		goto release_area;
588 
589 	start_tag = (struct alloc_tag *)(module_tags.start_addr + mas.index);
590 	end_tag = (struct alloc_tag *)(module_tags.start_addr + mas.last);
591 	if (!clean_unused_counters(start_tag, end_tag)) {
592 		struct alloc_tag *tag;
593 
594 		for (tag = start_tag; tag <= end_tag; tag++) {
595 			struct alloc_tag_counters counter;
596 
597 			if (!tag->counters)
598 				continue;
599 
600 			counter = alloc_tag_read(tag);
601 			pr_info("%s:%u module %s func:%s has %llu allocated at module unload\n",
602 				tag->ct.filename, tag->ct.lineno, tag->ct.modname,
603 				tag->ct.function, counter.bytes);
604 		}
605 	} else {
606 		used = false;
607 	}
608 release_area:
609 	mas_store(&mas, used ? &unloaded_mod : NULL);
610 	val = mas_prev_range(&mas, 0);
611 	if (val == &prepend_mod)
612 		mas_store(&mas, NULL);
613 out:
614 	mas_unlock(&mas);
615 }
616 
617 static int load_module(struct module *mod, struct codetag *start, struct codetag *stop)
618 {
619 	/* Allocate module alloc_tag percpu counters */
620 	struct alloc_tag *start_tag;
621 	struct alloc_tag *stop_tag;
622 	struct alloc_tag *tag;
623 
624 	/* percpu counters for core allocations are already statically allocated */
625 	if (!mod)
626 		return 0;
627 
628 	start_tag = ct_to_alloc_tag(start);
629 	stop_tag = ct_to_alloc_tag(stop);
630 	for (tag = start_tag; tag < stop_tag; tag++) {
631 		WARN_ON(tag->counters);
632 		tag->counters = alloc_percpu(struct alloc_tag_counters);
633 		if (!tag->counters) {
634 			while (--tag >= start_tag) {
635 				free_percpu(tag->counters);
636 				tag->counters = NULL;
637 			}
638 			pr_err("Failed to allocate memory for allocation tag percpu counters in the module %s\n",
639 			       mod->name);
640 			return -ENOMEM;
641 		}
642 
643 		/*
644 		 * Avoid a kmemleak false positive. The pointer to the counters is stored
645 		 * in the alloc_tag section of the module and cannot be directly accessed.
646 		 */
647 		kmemleak_ignore_percpu(tag->counters);
648 	}
649 	return 0;
650 }
651 
652 static void replace_module(struct module *mod, struct module *new_mod)
653 {
654 	MA_STATE(mas, &mod_area_mt, 0, module_tags.size);
655 	struct module *val;
656 
657 	mas_lock(&mas);
658 	mas_for_each(&mas, val, module_tags.size) {
659 		if (val != mod)
660 			continue;
661 
662 		mas_store_gfp(&mas, new_mod, GFP_KERNEL);
663 		break;
664 	}
665 	mas_unlock(&mas);
666 }
667 
668 static int __init alloc_mod_tags_mem(void)
669 {
670 	/* Map space to copy allocation tags */
671 	vm_module_tags = execmem_vmap(MODULE_ALLOC_TAG_VMAP_SIZE);
672 	if (!vm_module_tags) {
673 		pr_err("Failed to map %lu bytes for module allocation tags\n",
674 			MODULE_ALLOC_TAG_VMAP_SIZE);
675 		module_tags.start_addr = 0;
676 		return -ENOMEM;
677 	}
678 
679 	vm_module_tags->pages = kmalloc_objs(struct page *,
680 					     get_vm_area_size(vm_module_tags) >> PAGE_SHIFT,
681 					     GFP_KERNEL | __GFP_ZERO);
682 	if (!vm_module_tags->pages) {
683 		free_vm_area(vm_module_tags);
684 		return -ENOMEM;
685 	}
686 
687 	module_tags.start_addr = (unsigned long)vm_module_tags->addr;
688 	module_tags.end_addr = module_tags.start_addr + MODULE_ALLOC_TAG_VMAP_SIZE;
689 	/* Ensure the base is alloc_tag aligned when required for indexing */
690 	module_tags.start_addr = alloc_tag_align(module_tags.start_addr);
691 
692 	return 0;
693 }
694 
695 static void __init free_mod_tags_mem(void)
696 {
697 	release_pages_arg arg = { .pages = vm_module_tags->pages };
698 
699 	module_tags.start_addr = 0;
700 	release_pages(arg, vm_module_tags->nr_pages);
701 	kfree(vm_module_tags->pages);
702 	free_vm_area(vm_module_tags);
703 }
704 
705 #else /* CONFIG_MODULES */
706 
707 static inline int alloc_mod_tags_mem(void) { return 0; }
708 static inline void free_mod_tags_mem(void) {}
709 
710 #endif /* CONFIG_MODULES */
711 
712 /* See: Documentation/mm/allocation-profiling.rst */
713 static int __init setup_early_mem_profiling(char *str)
714 {
715 	bool compressed = false;
716 	bool enable;
717 
718 	if (!str || !str[0])
719 		return -EINVAL;
720 
721 	if (!strncmp(str, "never", 5)) {
722 		enable = false;
723 		mem_profiling_support = false;
724 		pr_info("Memory allocation profiling is disabled!\n");
725 	} else {
726 		char *token = strsep(&str, ",");
727 
728 		if (kstrtobool(token, &enable))
729 			return -EINVAL;
730 
731 		if (str) {
732 
733 			if (strcmp(str, "compressed"))
734 				return -EINVAL;
735 
736 			compressed = true;
737 		}
738 		mem_profiling_support = true;
739 		pr_info("Memory allocation profiling is enabled %s compression and is turned %s!\n",
740 			compressed ? "with" : "without", str_on_off(enable));
741 	}
742 
743 	if (enable != mem_alloc_profiling_enabled()) {
744 		if (enable)
745 			static_branch_enable(&mem_alloc_profiling_key);
746 		else
747 			static_branch_disable(&mem_alloc_profiling_key);
748 	}
749 	if (compressed != static_key_enabled(&mem_profiling_compressed)) {
750 		if (compressed)
751 			static_branch_enable(&mem_profiling_compressed);
752 		else
753 			static_branch_disable(&mem_profiling_compressed);
754 	}
755 
756 	return 0;
757 }
758 early_param("sysctl.vm.mem_profiling", setup_early_mem_profiling);
759 
760 static __init bool need_page_alloc_tagging(void)
761 {
762 	if (static_key_enabled(&mem_profiling_compressed))
763 		return false;
764 
765 	return mem_profiling_support;
766 }
767 
768 #ifdef CONFIG_MEM_ALLOC_PROFILING_DEBUG
769 /*
770  * Track page allocations before page_ext is initialized.
771  * Some pages are allocated before page_ext becomes available, leaving
772  * their codetag uninitialized. Track these early PFNs so we can clear
773  * their codetag refs later to avoid warnings when they are freed.
774  *
775  * Each page is cast to a pfn_pool: the first few bytes hold metadata
776  * (next pointer and slot count), the remainder stores PFNs.
777  */
778 struct pfn_pool {
779 	struct pfn_pool *next;
780 	atomic_t count;
781 	unsigned long pfns[];
782 };
783 
784 #define PFN_POOL_SIZE			((PAGE_SIZE - offsetof(struct pfn_pool, pfns)) / \
785 					 sizeof(unsigned long))
786 
787 /*
788  * Skip early PFN recording for a page allocation.  Reuses the
789  * %__GFP_NO_OBJ_EXT bit.  Used by __alloc_tag_add_early_pfn() to avoid
790  * recursion when allocating pages for the early PFN tracking list
791  * itself.
792  *
793  * Codetags of the pages allocated with __GFP_NO_CODETAG should be
794  * cleared (via clear_page_tag_ref()) before freeing the pages to prevent
795  * alloc_tag_sub_check() from triggering a warning.
796  */
797 #define __GFP_NO_CODETAG		__GFP_NO_OBJ_EXT
798 
799 static struct pfn_pool *current_pfn_pool __initdata;
800 
801 static void __init __alloc_tag_add_early_pfn(unsigned long pfn)
802 {
803 	struct pfn_pool *pool;
804 	int idx;
805 
806 	do {
807 		pool = READ_ONCE(current_pfn_pool);
808 		if (!pool || atomic_read(&pool->count) >= PFN_POOL_SIZE) {
809 			struct page *new_page = alloc_page(__GFP_HIGH | __GFP_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, gfp_t gfp_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 (gfp_flags & __GFP_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