1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/mm.h>
3 #include <linux/mmzone.h>
4 #include <linux/memblock.h>
5 #include <linux/page_ext.h>
6 #include <linux/memory.h>
7 #include <linux/vmalloc.h>
8 #include <linux/kmemleak.h>
9 #include <linux/page_owner.h>
10 #include <linux/page_pinner.h>
11 #include <linux/page_idle.h>
12 #include <linux/page_table_check.h>
13 #include <linux/rcupdate.h>
14 #include <linux/pgalloc_tag.h>
15 
16 /*
17  * struct page extension
18  *
19  * This is the feature to manage memory for extended data per page.
20  *
21  * Until now, we must modify struct page itself to store extra data per page.
22  * This requires rebuilding the kernel and it is really time consuming process.
23  * And, sometimes, rebuild is impossible due to third party module dependency.
24  * At last, enlarging struct page could cause un-wanted system behaviour change.
25  *
26  * This feature is intended to overcome above mentioned problems. This feature
27  * allocates memory for extended data per page in certain place rather than
28  * the struct page itself. This memory can be accessed by the accessor
29  * functions provided by this code. During the boot process, it checks whether
30  * allocation of huge chunk of memory is needed or not. If not, it avoids
31  * allocating memory at all. With this advantage, we can include this feature
32  * into the kernel in default and can avoid rebuild and solve related problems.
33  *
34  * To help these things to work well, there are two callbacks for clients. One
35  * is the need callback which is mandatory if user wants to avoid useless
36  * memory allocation at boot-time. The other is optional, init callback, which
37  * is used to do proper initialization after memory is allocated.
38  *
39  * The need callback is used to decide whether extended memory allocation is
40  * needed or not. Sometimes users want to deactivate some features in this
41  * boot and extra memory would be unnecessary. In this case, to avoid
42  * allocating huge chunk of memory, each clients represent their need of
43  * extra memory through the need callback. If one of the need callbacks
44  * returns true, it means that someone needs extra memory so that
45  * page extension core should allocates memory for page extension. If
46  * none of need callbacks return true, memory isn't needed at all in this boot
47  * and page extension core can skip to allocate memory. As result,
48  * none of memory is wasted.
49  *
50  * When need callback returns true, page_ext checks if there is a request for
51  * extra memory through size in struct page_ext_operations. If it is non-zero,
52  * extra space is allocated for each page_ext entry and offset is returned to
53  * user through offset in struct page_ext_operations.
54  *
55  * The init callback is used to do proper initialization after page extension
56  * is completely initialized. In sparse memory system, extra memory is
57  * allocated some time later than memmap is allocated. In other words, lifetime
58  * of memory for page extension isn't same with memmap for struct page.
59  * Therefore, clients can't store extra data until page extension is
60  * initialized, even if pages are allocated and used freely. This could
61  * cause inadequate state of extra data per page, so, to prevent it, client
62  * can utilize this callback to initialize the state of it correctly.
63  */
64 
65 #ifdef CONFIG_SPARSEMEM
66 #define PAGE_EXT_INVALID       (0x1)
67 #endif
68 
69 #if defined(CONFIG_PAGE_IDLE_FLAG) && !defined(CONFIG_64BIT)
need_page_idle(void)70 static bool need_page_idle(void)
71 {
72 	return true;
73 }
74 static struct page_ext_operations page_idle_ops __initdata = {
75 	.need = need_page_idle,
76 	.need_shared_flags = true,
77 };
78 #endif
79 
80 static struct page_ext_operations *page_ext_ops[] __initdata = {
81 #ifdef CONFIG_PAGE_OWNER
82 	&page_owner_ops,
83 #endif
84 #if defined(CONFIG_PAGE_IDLE_FLAG) && !defined(CONFIG_64BIT)
85 	&page_idle_ops,
86 #endif
87 #ifdef CONFIG_MEM_ALLOC_PROFILING
88 	&page_alloc_tagging_ops,
89 #endif
90 #ifdef CONFIG_PAGE_PINNER
91 	&page_pinner_ops,
92 #endif
93 #ifdef CONFIG_PAGE_TABLE_CHECK
94 	&page_table_check_ops,
95 #endif
96 };
97 
98 unsigned long page_ext_size;
99 
100 static unsigned long total_usage;
101 
102 #ifdef CONFIG_MEM_ALLOC_PROFILING_DEBUG
103 /*
104  * To ensure correct allocation tagging for pages, page_ext should be available
105  * before the first page allocation. Otherwise early task stacks will be
106  * allocated before page_ext initialization and missing tags will be flagged.
107  */
108 bool early_page_ext __meminitdata = true;
109 #else
110 bool early_page_ext __meminitdata;
111 #endif
setup_early_page_ext(char * str)112 static int __init setup_early_page_ext(char *str)
113 {
114 	early_page_ext = true;
115 	return 0;
116 }
117 early_param("early_page_ext", setup_early_page_ext);
118 
invoke_need_callbacks(void)119 static bool __init invoke_need_callbacks(void)
120 {
121 	int i;
122 	int entries = ARRAY_SIZE(page_ext_ops);
123 	bool need = false;
124 
125 	for (i = 0; i < entries; i++) {
126 		if (page_ext_ops[i]->need()) {
127 			if (page_ext_ops[i]->need_shared_flags) {
128 				page_ext_size = sizeof(struct page_ext);
129 				break;
130 			}
131 		}
132 	}
133 
134 	for (i = 0; i < entries; i++) {
135 		if (page_ext_ops[i]->need()) {
136 			page_ext_ops[i]->offset = page_ext_size;
137 			page_ext_size += page_ext_ops[i]->size;
138 			need = true;
139 		}
140 	}
141 
142 	return need;
143 }
144 
invoke_init_callbacks(void)145 static void __init invoke_init_callbacks(void)
146 {
147 	int i;
148 	int entries = ARRAY_SIZE(page_ext_ops);
149 
150 	for (i = 0; i < entries; i++) {
151 		if (page_ext_ops[i]->init)
152 			page_ext_ops[i]->init();
153 	}
154 }
155 
get_entry(void * base,unsigned long index)156 static inline struct page_ext *get_entry(void *base, unsigned long index)
157 {
158 	return base + page_ext_size * index;
159 }
160 
161 #ifndef CONFIG_SPARSEMEM
page_ext_init_flatmem_late(void)162 void __init page_ext_init_flatmem_late(void)
163 {
164 	invoke_init_callbacks();
165 }
166 
pgdat_page_ext_init(struct pglist_data * pgdat)167 void __meminit pgdat_page_ext_init(struct pglist_data *pgdat)
168 {
169 	pgdat->node_page_ext = NULL;
170 }
171 
lookup_page_ext(const struct page * page)172 static struct page_ext *lookup_page_ext(const struct page *page)
173 {
174 	unsigned long pfn = page_to_pfn(page);
175 	unsigned long index;
176 	struct page_ext *base;
177 
178 	WARN_ON_ONCE(!rcu_read_lock_held());
179 	base = NODE_DATA(page_to_nid(page))->node_page_ext;
180 	/*
181 	 * The sanity checks the page allocator does upon freeing a
182 	 * page can reach here before the page_ext arrays are
183 	 * allocated when feeding a range of pages to the allocator
184 	 * for the first time during bootup or memory hotplug.
185 	 */
186 	if (unlikely(!base))
187 		return NULL;
188 	index = pfn - round_down(node_start_pfn(page_to_nid(page)),
189 					MAX_ORDER_NR_PAGES);
190 	return get_entry(base, index);
191 }
192 
alloc_node_page_ext(int nid)193 static int __init alloc_node_page_ext(int nid)
194 {
195 	struct page_ext *base;
196 	unsigned long table_size;
197 	unsigned long nr_pages;
198 
199 	nr_pages = NODE_DATA(nid)->node_spanned_pages;
200 	if (!nr_pages)
201 		return 0;
202 
203 	/*
204 	 * Need extra space if node range is not aligned with
205 	 * MAX_ORDER_NR_PAGES. When page allocator's buddy algorithm
206 	 * checks buddy's status, range could be out of exact node range.
207 	 */
208 	if (!IS_ALIGNED(node_start_pfn(nid), MAX_ORDER_NR_PAGES) ||
209 		!IS_ALIGNED(node_end_pfn(nid), MAX_ORDER_NR_PAGES))
210 		nr_pages += MAX_ORDER_NR_PAGES;
211 
212 	table_size = page_ext_size * nr_pages;
213 
214 	base = memblock_alloc_try_nid(
215 			table_size, PAGE_SIZE, __pa(MAX_DMA_ADDRESS),
216 			MEMBLOCK_ALLOC_ACCESSIBLE, nid);
217 	if (!base)
218 		return -ENOMEM;
219 	NODE_DATA(nid)->node_page_ext = base;
220 	total_usage += table_size;
221 	memmap_boot_pages_add(DIV_ROUND_UP(table_size, PAGE_SIZE));
222 	return 0;
223 }
224 
page_ext_init_flatmem(void)225 void __init page_ext_init_flatmem(void)
226 {
227 
228 	int nid, fail;
229 
230 	if (!invoke_need_callbacks())
231 		return;
232 
233 	for_each_online_node(nid)  {
234 		fail = alloc_node_page_ext(nid);
235 		if (fail)
236 			goto fail;
237 	}
238 	pr_info("allocated %ld bytes of page_ext\n", total_usage);
239 	return;
240 
241 fail:
242 	pr_crit("allocation of page_ext failed.\n");
243 	panic("Out of memory");
244 }
245 
246 #else /* CONFIG_SPARSEMEM */
page_ext_invalid(struct page_ext * page_ext)247 static bool page_ext_invalid(struct page_ext *page_ext)
248 {
249 	return !page_ext || (((unsigned long)page_ext & PAGE_EXT_INVALID) == PAGE_EXT_INVALID);
250 }
251 
lookup_page_ext(const struct page * page)252 static struct page_ext *lookup_page_ext(const struct page *page)
253 {
254 	unsigned long pfn = page_to_pfn(page);
255 	struct mem_section *section = __pfn_to_section(pfn);
256 	struct page_ext *page_ext = READ_ONCE(section->page_ext);
257 
258 	WARN_ON_ONCE(!rcu_read_lock_held());
259 	/*
260 	 * The sanity checks the page allocator does upon freeing a
261 	 * page can reach here before the page_ext arrays are
262 	 * allocated when feeding a range of pages to the allocator
263 	 * for the first time during bootup or memory hotplug.
264 	 */
265 	if (page_ext_invalid(page_ext))
266 		return NULL;
267 	return get_entry(page_ext, pfn);
268 }
269 
alloc_page_ext(size_t size,int nid)270 static void *__meminit alloc_page_ext(size_t size, int nid)
271 {
272 	gfp_t flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN;
273 	void *addr = NULL;
274 
275 	addr = alloc_pages_exact_nid(nid, size, flags);
276 	if (addr)
277 		kmemleak_alloc(addr, size, 1, flags);
278 	else
279 		addr = vzalloc_node(size, nid);
280 
281 	if (addr)
282 		memmap_pages_add(DIV_ROUND_UP(size, PAGE_SIZE));
283 
284 	return addr;
285 }
286 
init_section_page_ext(unsigned long pfn,int nid)287 static int __meminit init_section_page_ext(unsigned long pfn, int nid)
288 {
289 	struct mem_section *section;
290 	struct page_ext *base;
291 	unsigned long table_size;
292 
293 	section = __pfn_to_section(pfn);
294 
295 	if (section->page_ext)
296 		return 0;
297 
298 	table_size = page_ext_size * PAGES_PER_SECTION;
299 	base = alloc_page_ext(table_size, nid);
300 
301 	/*
302 	 * The value stored in section->page_ext is (base - pfn)
303 	 * and it does not point to the memory block allocated above,
304 	 * causing kmemleak false positives.
305 	 */
306 	kmemleak_not_leak(base);
307 
308 	if (!base) {
309 		pr_err("page ext allocation failure\n");
310 		return -ENOMEM;
311 	}
312 
313 	/*
314 	 * The passed "pfn" may not be aligned to SECTION.  For the calculation
315 	 * we need to apply a mask.
316 	 */
317 	pfn &= PAGE_SECTION_MASK;
318 	section->page_ext = (void *)base - page_ext_size * pfn;
319 	total_usage += table_size;
320 	return 0;
321 }
322 
free_page_ext(void * addr)323 static void free_page_ext(void *addr)
324 {
325 	size_t table_size;
326 	struct page *page;
327 
328 	table_size = page_ext_size * PAGES_PER_SECTION;
329 	memmap_pages_add(-1L * (DIV_ROUND_UP(table_size, PAGE_SIZE)));
330 
331 	if (is_vmalloc_addr(addr)) {
332 		vfree(addr);
333 	} else {
334 		page = virt_to_page(addr);
335 		BUG_ON(PageReserved(page));
336 		kmemleak_free(addr);
337 		free_pages_exact(addr, table_size);
338 	}
339 }
340 
__free_page_ext(unsigned long pfn)341 static void __free_page_ext(unsigned long pfn)
342 {
343 	struct mem_section *ms;
344 	struct page_ext *base;
345 
346 	ms = __pfn_to_section(pfn);
347 	if (!ms || !ms->page_ext)
348 		return;
349 
350 	base = READ_ONCE(ms->page_ext);
351 	/*
352 	 * page_ext here can be valid while doing the roll back
353 	 * operation in online_page_ext().
354 	 */
355 	if (page_ext_invalid(base))
356 		base = (void *)base - PAGE_EXT_INVALID;
357 	WRITE_ONCE(ms->page_ext, NULL);
358 
359 	base = get_entry(base, pfn);
360 	free_page_ext(base);
361 }
362 
__invalidate_page_ext(unsigned long pfn)363 static void __invalidate_page_ext(unsigned long pfn)
364 {
365 	struct mem_section *ms;
366 	void *val;
367 
368 	ms = __pfn_to_section(pfn);
369 	if (!ms || !ms->page_ext)
370 		return;
371 	val = (void *)ms->page_ext + PAGE_EXT_INVALID;
372 	WRITE_ONCE(ms->page_ext, val);
373 }
374 
online_page_ext(unsigned long start_pfn,unsigned long nr_pages,int nid)375 static int __meminit online_page_ext(unsigned long start_pfn,
376 				unsigned long nr_pages,
377 				int nid)
378 {
379 	unsigned long start, end, pfn;
380 	int fail = 0;
381 
382 	start = SECTION_ALIGN_DOWN(start_pfn);
383 	end = SECTION_ALIGN_UP(start_pfn + nr_pages);
384 
385 	if (nid == NUMA_NO_NODE) {
386 		/*
387 		 * In this case, "nid" already exists and contains valid memory.
388 		 * "start_pfn" passed to us is a pfn which is an arg for
389 		 * online__pages(), and start_pfn should exist.
390 		 */
391 		nid = pfn_to_nid(start_pfn);
392 		VM_BUG_ON(!node_online(nid));
393 	}
394 
395 	for (pfn = start; !fail && pfn < end; pfn += PAGES_PER_SECTION)
396 		fail = init_section_page_ext(pfn, nid);
397 	if (!fail)
398 		return 0;
399 
400 	/* rollback */
401 	end = pfn - PAGES_PER_SECTION;
402 	for (pfn = start; pfn < end; pfn += PAGES_PER_SECTION)
403 		__free_page_ext(pfn);
404 
405 	return -ENOMEM;
406 }
407 
offline_page_ext(unsigned long start_pfn,unsigned long nr_pages)408 static void __meminit offline_page_ext(unsigned long start_pfn,
409 				unsigned long nr_pages)
410 {
411 	unsigned long start, end, pfn;
412 
413 	start = SECTION_ALIGN_DOWN(start_pfn);
414 	end = SECTION_ALIGN_UP(start_pfn + nr_pages);
415 
416 	/*
417 	 * Freeing of page_ext is done in 3 steps to avoid
418 	 * use-after-free of it:
419 	 * 1) Traverse all the sections and mark their page_ext
420 	 *    as invalid.
421 	 * 2) Wait for all the existing users of page_ext who
422 	 *    started before invalidation to finish.
423 	 * 3) Free the page_ext.
424 	 */
425 	for (pfn = start; pfn < end; pfn += PAGES_PER_SECTION)
426 		__invalidate_page_ext(pfn);
427 
428 	synchronize_rcu();
429 
430 	for (pfn = start; pfn < end; pfn += PAGES_PER_SECTION)
431 		__free_page_ext(pfn);
432 }
433 
page_ext_callback(struct notifier_block * self,unsigned long action,void * arg)434 static int __meminit page_ext_callback(struct notifier_block *self,
435 			       unsigned long action, void *arg)
436 {
437 	struct memory_notify *mn = arg;
438 	int ret = 0;
439 
440 	switch (action) {
441 	case MEM_GOING_ONLINE:
442 		ret = online_page_ext(mn->start_pfn,
443 				   mn->nr_pages, mn->status_change_nid);
444 		break;
445 	case MEM_OFFLINE:
446 		offline_page_ext(mn->start_pfn,
447 				mn->nr_pages);
448 		break;
449 	case MEM_CANCEL_ONLINE:
450 		offline_page_ext(mn->start_pfn,
451 				mn->nr_pages);
452 		break;
453 	case MEM_GOING_OFFLINE:
454 		break;
455 	case MEM_ONLINE:
456 	case MEM_CANCEL_OFFLINE:
457 		break;
458 	}
459 
460 	return notifier_from_errno(ret);
461 }
462 
page_ext_init(void)463 void __init page_ext_init(void)
464 {
465 	unsigned long pfn;
466 	int nid;
467 
468 	if (!invoke_need_callbacks())
469 		return;
470 
471 	for_each_node_state(nid, N_MEMORY) {
472 		unsigned long start_pfn, end_pfn;
473 
474 		start_pfn = node_start_pfn(nid);
475 		end_pfn = node_end_pfn(nid);
476 		/*
477 		 * start_pfn and end_pfn may not be aligned to SECTION and the
478 		 * page->flags of out of node pages are not initialized.  So we
479 		 * scan [start_pfn, the biggest section's pfn < end_pfn) here.
480 		 */
481 		for (pfn = start_pfn; pfn < end_pfn;
482 			pfn = ALIGN(pfn + 1, PAGES_PER_SECTION)) {
483 
484 			if (!pfn_valid(pfn))
485 				continue;
486 			/*
487 			 * Nodes's pfns can be overlapping.
488 			 * We know some arch can have a nodes layout such as
489 			 * -------------pfn-------------->
490 			 * N0 | N1 | N2 | N0 | N1 | N2|....
491 			 */
492 			if (pfn_to_nid(pfn) != nid)
493 				continue;
494 			if (init_section_page_ext(pfn, nid))
495 				goto oom;
496 			cond_resched();
497 		}
498 	}
499 	hotplug_memory_notifier(page_ext_callback, DEFAULT_CALLBACK_PRI);
500 	pr_info("allocated %ld bytes of page_ext\n", total_usage);
501 	invoke_init_callbacks();
502 	return;
503 
504 oom:
505 	panic("Out of memory");
506 }
507 
pgdat_page_ext_init(struct pglist_data * pgdat)508 void __meminit pgdat_page_ext_init(struct pglist_data *pgdat)
509 {
510 }
511 
512 #endif
513 
514 /**
515  * page_ext_get() - Get the extended information for a page.
516  * @page: The page we're interested in.
517  *
518  * Ensures that the page_ext will remain valid until page_ext_put()
519  * is called.
520  *
521  * Return: NULL if no page_ext exists for this page.
522  * Context: Any context.  Caller may not sleep until they have called
523  * page_ext_put().
524  */
page_ext_get(const struct page * page)525 struct page_ext *page_ext_get(const struct page *page)
526 {
527 	struct page_ext *page_ext;
528 
529 	rcu_read_lock();
530 	page_ext = lookup_page_ext(page);
531 	if (!page_ext) {
532 		rcu_read_unlock();
533 		return NULL;
534 	}
535 
536 	return page_ext;
537 }
538 EXPORT_SYMBOL_NS_GPL(page_ext_get, MINIDUMP);
539 
540 /**
541  * page_ext_put() - Working with page extended information is done.
542  * @page_ext: Page extended information received from page_ext_get().
543  *
544  * The page extended information of the page may not be valid after this
545  * function is called.
546  *
547  * Return: None.
548  * Context: Any context with corresponding page_ext_get() is called.
549  */
page_ext_put(struct page_ext * page_ext)550 void page_ext_put(struct page_ext *page_ext)
551 {
552 	if (unlikely(!page_ext))
553 		return;
554 
555 	rcu_read_unlock();
556 }
557 EXPORT_SYMBOL_NS_GPL(page_ext_put, MINIDUMP);
558