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_idle.h>
11 #include <linux/page_table_check.h>
12 #include <linux/rcupdate.h>
13 #include <linux/pgalloc_tag.h>
14 #include <linux/iommu-debug-pagealloc.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_TABLE_CHECK
91 &page_table_check_ops,
92 #endif
93 #ifdef CONFIG_IOMMU_DEBUG_PAGEALLOC
94 &page_iommu_debug_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)375 static int __meminit online_page_ext(unsigned long start_pfn,
376 unsigned long nr_pages)
377 {
378 int nid = pfn_to_nid(start_pfn);
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 for (pfn = start; !fail && pfn < end; pfn += PAGES_PER_SECTION)
386 fail = init_section_page_ext(pfn, nid);
387 if (!fail)
388 return 0;
389
390 /* rollback */
391 end = pfn - PAGES_PER_SECTION;
392 for (pfn = start; pfn < end; pfn += PAGES_PER_SECTION)
393 __free_page_ext(pfn);
394
395 return -ENOMEM;
396 }
397
offline_page_ext(unsigned long start_pfn,unsigned long nr_pages)398 static void __meminit offline_page_ext(unsigned long start_pfn,
399 unsigned long nr_pages)
400 {
401 unsigned long start, end, pfn;
402
403 start = SECTION_ALIGN_DOWN(start_pfn);
404 end = SECTION_ALIGN_UP(start_pfn + nr_pages);
405
406 /*
407 * Freeing of page_ext is done in 3 steps to avoid
408 * use-after-free of it:
409 * 1) Traverse all the sections and mark their page_ext
410 * as invalid.
411 * 2) Wait for all the existing users of page_ext who
412 * started before invalidation to finish.
413 * 3) Free the page_ext.
414 */
415 for (pfn = start; pfn < end; pfn += PAGES_PER_SECTION)
416 __invalidate_page_ext(pfn);
417
418 synchronize_rcu();
419
420 for (pfn = start; pfn < end; pfn += PAGES_PER_SECTION)
421 __free_page_ext(pfn);
422 }
423
page_ext_callback(struct notifier_block * self,unsigned long action,void * arg)424 static int __meminit page_ext_callback(struct notifier_block *self,
425 unsigned long action, void *arg)
426 {
427 struct memory_notify *mn = arg;
428 int ret = 0;
429
430 switch (action) {
431 case MEM_GOING_ONLINE:
432 ret = online_page_ext(mn->start_pfn, mn->nr_pages);
433 break;
434 case MEM_OFFLINE:
435 offline_page_ext(mn->start_pfn,
436 mn->nr_pages);
437 break;
438 case MEM_CANCEL_ONLINE:
439 offline_page_ext(mn->start_pfn,
440 mn->nr_pages);
441 break;
442 case MEM_GOING_OFFLINE:
443 break;
444 case MEM_ONLINE:
445 case MEM_CANCEL_OFFLINE:
446 break;
447 }
448
449 return notifier_from_errno(ret);
450 }
451
page_ext_init(void)452 void __init page_ext_init(void)
453 {
454 unsigned long pfn;
455 int nid;
456
457 if (!invoke_need_callbacks())
458 return;
459
460 for_each_node_state(nid, N_MEMORY) {
461 unsigned long start_pfn, end_pfn;
462
463 start_pfn = node_start_pfn(nid);
464 end_pfn = node_end_pfn(nid);
465 /*
466 * start_pfn and end_pfn may not be aligned to SECTION and the
467 * page->flags of out of node pages are not initialized. So we
468 * scan [start_pfn, the biggest section's pfn < end_pfn) here.
469 */
470 for (pfn = start_pfn; pfn < end_pfn;
471 pfn = ALIGN(pfn + 1, PAGES_PER_SECTION)) {
472
473 if (!pfn_valid(pfn))
474 continue;
475 /*
476 * Nodes's pfns can be overlapping.
477 * We know some arch can have a nodes layout such as
478 * -------------pfn-------------->
479 * N0 | N1 | N2 | N0 | N1 | N2|....
480 */
481 if (pfn_to_nid(pfn) != nid)
482 continue;
483 if (init_section_page_ext(pfn, nid))
484 goto oom;
485 cond_resched();
486 }
487 }
488 hotplug_memory_notifier(page_ext_callback, DEFAULT_CALLBACK_PRI);
489 pr_info("allocated %ld bytes of page_ext\n", total_usage);
490 invoke_init_callbacks();
491 return;
492
493 oom:
494 panic("Out of memory");
495 }
496
pgdat_page_ext_init(struct pglist_data * pgdat)497 void __meminit pgdat_page_ext_init(struct pglist_data *pgdat)
498 {
499 }
500
501 #endif
502
503 /**
504 * page_ext_lookup() - Lookup a page extension for a PFN.
505 * @pfn: PFN of the page we're interested in.
506 *
507 * Must be called with RCU read lock taken and @pfn must be valid.
508 *
509 * Return: NULL if no page_ext exists for this page.
510 */
page_ext_lookup(unsigned long pfn)511 struct page_ext *page_ext_lookup(unsigned long pfn)
512 {
513 return lookup_page_ext(pfn_to_page(pfn));
514 }
515
516 /**
517 * page_ext_get() - Get the extended information for a page.
518 * @page: The page we're interested in.
519 *
520 * Ensures that the page_ext will remain valid until page_ext_put()
521 * is called.
522 *
523 * Return: NULL if no page_ext exists for this page.
524 * Context: Any context. Caller may not sleep until they have called
525 * page_ext_put().
526 */
page_ext_get(const struct page * page)527 struct page_ext *page_ext_get(const struct page *page)
528 {
529 struct page_ext *page_ext;
530
531 rcu_read_lock();
532 page_ext = lookup_page_ext(page);
533 if (!page_ext) {
534 rcu_read_unlock();
535 return NULL;
536 }
537
538 return page_ext;
539 }
540
541 /**
542 * page_ext_from_phys() - Get the page_ext structure for a physical address.
543 * @phys: The physical address to query.
544 *
545 * This function safely gets the `struct page_ext` associated with a given
546 * physical address. It performs validation to ensure the address corresponds
547 * to a valid, online struct page before attempting to access it.
548 * It returns NULL for MMIO, ZONE_DEVICE, holes and offline memory.
549 *
550 * Return: NULL if no page_ext exists for this physical address.
551 * Context: Any context. Caller may not sleep until they have called
552 * page_ext_put().
553 */
page_ext_from_phys(phys_addr_t phys)554 struct page_ext *page_ext_from_phys(phys_addr_t phys)
555 {
556 struct page *page = pfn_to_online_page(__phys_to_pfn(phys));
557
558 if (!page)
559 return NULL;
560
561 return page_ext_get(page);
562 }
563
564 /**
565 * page_ext_put() - Working with page extended information is done.
566 * @page_ext: Page extended information received from page_ext_get().
567 *
568 * The page extended information of the page may not be valid after this
569 * function is called.
570 *
571 * Return: None.
572 * Context: Any context with corresponding page_ext_get() is called.
573 */
page_ext_put(struct page_ext * page_ext)574 void page_ext_put(struct page_ext *page_ext)
575 {
576 if (unlikely(!page_ext))
577 return;
578
579 rcu_read_unlock();
580 }
581