1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2015 Intel Corporation. All rights reserved. */
3 #include <linux/device.h>
4 #include <linux/io.h>
5 #include <linux/kasan.h>
6 #include <linux/memory_hotplug.h>
7 #include <linux/memremap.h>
8 #include <linux/pfn_t.h>
9 #include <linux/swap.h>
10 #include <linux/mm.h>
11 #include <linux/mmzone.h>
12 #include <linux/swapops.h>
13 #include <linux/types.h>
14 #include <linux/wait_bit.h>
15 #include <linux/xarray.h>
16 #include "internal.h"
17 
18 static DEFINE_XARRAY(pgmap_array);
19 
20 /*
21  * The memremap() and memremap_pages() interfaces are alternately used
22  * to map persistent memory namespaces. These interfaces place different
23  * constraints on the alignment and size of the mapping (namespace).
24  * memremap() can map individual PAGE_SIZE pages. memremap_pages() can
25  * only map subsections (2MB), and at least one architecture (PowerPC)
26  * the minimum mapping granularity of memremap_pages() is 16MB.
27  *
28  * The role of memremap_compat_align() is to communicate the minimum
29  * arch supported alignment of a namespace such that it can freely
30  * switch modes without violating the arch constraint. Namely, do not
31  * allow a namespace to be PAGE_SIZE aligned since that namespace may be
32  * reconfigured into a mode that requires SUBSECTION_SIZE alignment.
33  */
34 #ifndef CONFIG_ARCH_HAS_MEMREMAP_COMPAT_ALIGN
memremap_compat_align(void)35 unsigned long memremap_compat_align(void)
36 {
37 	return SUBSECTION_SIZE;
38 }
39 EXPORT_SYMBOL_GPL(memremap_compat_align);
40 #endif
41 
42 #ifdef CONFIG_FS_DAX
43 DEFINE_STATIC_KEY_FALSE(devmap_managed_key);
44 EXPORT_SYMBOL(devmap_managed_key);
45 
devmap_managed_enable_put(struct dev_pagemap * pgmap)46 static void devmap_managed_enable_put(struct dev_pagemap *pgmap)
47 {
48 	if (pgmap->type == MEMORY_DEVICE_FS_DAX)
49 		static_branch_dec(&devmap_managed_key);
50 }
51 
devmap_managed_enable_get(struct dev_pagemap * pgmap)52 static void devmap_managed_enable_get(struct dev_pagemap *pgmap)
53 {
54 	if (pgmap->type == MEMORY_DEVICE_FS_DAX)
55 		static_branch_inc(&devmap_managed_key);
56 }
57 #else
devmap_managed_enable_get(struct dev_pagemap * pgmap)58 static void devmap_managed_enable_get(struct dev_pagemap *pgmap)
59 {
60 }
devmap_managed_enable_put(struct dev_pagemap * pgmap)61 static void devmap_managed_enable_put(struct dev_pagemap *pgmap)
62 {
63 }
64 #endif /* CONFIG_FS_DAX */
65 
pgmap_array_delete(struct range * range)66 static void pgmap_array_delete(struct range *range)
67 {
68 	xa_store_range(&pgmap_array, PHYS_PFN(range->start), PHYS_PFN(range->end),
69 			NULL, GFP_KERNEL);
70 	synchronize_rcu();
71 }
72 
pfn_first(struct dev_pagemap * pgmap,int range_id)73 static unsigned long pfn_first(struct dev_pagemap *pgmap, int range_id)
74 {
75 	struct range *range = &pgmap->ranges[range_id];
76 	unsigned long pfn = PHYS_PFN(range->start);
77 
78 	if (range_id)
79 		return pfn;
80 	return pfn + vmem_altmap_offset(pgmap_altmap(pgmap));
81 }
82 
pgmap_pfn_valid(struct dev_pagemap * pgmap,unsigned long pfn)83 bool pgmap_pfn_valid(struct dev_pagemap *pgmap, unsigned long pfn)
84 {
85 	int i;
86 
87 	for (i = 0; i < pgmap->nr_range; i++) {
88 		struct range *range = &pgmap->ranges[i];
89 
90 		if (pfn >= PHYS_PFN(range->start) &&
91 		    pfn <= PHYS_PFN(range->end))
92 			return pfn >= pfn_first(pgmap, i);
93 	}
94 
95 	return false;
96 }
97 
pfn_end(struct dev_pagemap * pgmap,int range_id)98 static unsigned long pfn_end(struct dev_pagemap *pgmap, int range_id)
99 {
100 	const struct range *range = &pgmap->ranges[range_id];
101 
102 	return (range->start + range_len(range)) >> PAGE_SHIFT;
103 }
104 
pfn_len(struct dev_pagemap * pgmap,unsigned long range_id)105 static unsigned long pfn_len(struct dev_pagemap *pgmap, unsigned long range_id)
106 {
107 	return (pfn_end(pgmap, range_id) -
108 		pfn_first(pgmap, range_id)) >> pgmap->vmemmap_shift;
109 }
110 
pageunmap_range(struct dev_pagemap * pgmap,int range_id)111 static void pageunmap_range(struct dev_pagemap *pgmap, int range_id)
112 {
113 	struct range *range = &pgmap->ranges[range_id];
114 	struct page *first_page;
115 
116 	/* make sure to access a memmap that was actually initialized */
117 	first_page = pfn_to_page(pfn_first(pgmap, range_id));
118 
119 	/* pages are dead and unused, undo the arch mapping */
120 	mem_hotplug_begin();
121 	remove_pfn_range_from_zone(page_zone(first_page), PHYS_PFN(range->start),
122 				   PHYS_PFN(range_len(range)));
123 	if (pgmap->type == MEMORY_DEVICE_PRIVATE) {
124 		__remove_pages(PHYS_PFN(range->start),
125 			       PHYS_PFN(range_len(range)), NULL);
126 	} else {
127 		arch_remove_memory(range->start, range_len(range),
128 				pgmap_altmap(pgmap));
129 		kasan_remove_zero_shadow(__va(range->start), range_len(range));
130 	}
131 	mem_hotplug_done();
132 
133 	untrack_pfn(NULL, PHYS_PFN(range->start), range_len(range), true);
134 	pgmap_array_delete(range);
135 }
136 
memunmap_pages(struct dev_pagemap * pgmap)137 void memunmap_pages(struct dev_pagemap *pgmap)
138 {
139 	int i;
140 
141 	percpu_ref_kill(&pgmap->ref);
142 	if (pgmap->type != MEMORY_DEVICE_PRIVATE &&
143 	    pgmap->type != MEMORY_DEVICE_COHERENT)
144 		for (i = 0; i < pgmap->nr_range; i++)
145 			percpu_ref_put_many(&pgmap->ref, pfn_len(pgmap, i));
146 
147 	wait_for_completion(&pgmap->done);
148 
149 	for (i = 0; i < pgmap->nr_range; i++)
150 		pageunmap_range(pgmap, i);
151 	percpu_ref_exit(&pgmap->ref);
152 
153 	WARN_ONCE(pgmap->altmap.alloc, "failed to free all reserved pages\n");
154 	devmap_managed_enable_put(pgmap);
155 }
156 EXPORT_SYMBOL_GPL(memunmap_pages);
157 
devm_memremap_pages_release(void * data)158 static void devm_memremap_pages_release(void *data)
159 {
160 	memunmap_pages(data);
161 }
162 
dev_pagemap_percpu_release(struct percpu_ref * ref)163 static void dev_pagemap_percpu_release(struct percpu_ref *ref)
164 {
165 	struct dev_pagemap *pgmap = container_of(ref, struct dev_pagemap, ref);
166 
167 	complete(&pgmap->done);
168 }
169 
pagemap_range(struct dev_pagemap * pgmap,struct mhp_params * params,int range_id,int nid)170 static int pagemap_range(struct dev_pagemap *pgmap, struct mhp_params *params,
171 		int range_id, int nid)
172 {
173 	const bool is_private = pgmap->type == MEMORY_DEVICE_PRIVATE;
174 	struct range *range = &pgmap->ranges[range_id];
175 	struct dev_pagemap *conflict_pgmap;
176 	int error, is_ram;
177 
178 	if (WARN_ONCE(pgmap_altmap(pgmap) && range_id > 0,
179 				"altmap not supported for multiple ranges\n"))
180 		return -EINVAL;
181 
182 	conflict_pgmap = get_dev_pagemap(PHYS_PFN(range->start), NULL);
183 	if (conflict_pgmap) {
184 		WARN(1, "Conflicting mapping in same section\n");
185 		put_dev_pagemap(conflict_pgmap);
186 		return -ENOMEM;
187 	}
188 
189 	conflict_pgmap = get_dev_pagemap(PHYS_PFN(range->end), NULL);
190 	if (conflict_pgmap) {
191 		WARN(1, "Conflicting mapping in same section\n");
192 		put_dev_pagemap(conflict_pgmap);
193 		return -ENOMEM;
194 	}
195 
196 	is_ram = region_intersects(range->start, range_len(range),
197 		IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE);
198 
199 	if (is_ram != REGION_DISJOINT) {
200 		WARN_ONCE(1, "attempted on %s region %#llx-%#llx\n",
201 				is_ram == REGION_MIXED ? "mixed" : "ram",
202 				range->start, range->end);
203 		return -ENXIO;
204 	}
205 
206 	error = xa_err(xa_store_range(&pgmap_array, PHYS_PFN(range->start),
207 				PHYS_PFN(range->end), pgmap, GFP_KERNEL));
208 	if (error)
209 		return error;
210 
211 	if (nid < 0)
212 		nid = numa_mem_id();
213 
214 	error = track_pfn_remap(NULL, &params->pgprot, PHYS_PFN(range->start), 0,
215 			range_len(range));
216 	if (error)
217 		goto err_pfn_remap;
218 
219 	if (!mhp_range_allowed(range->start, range_len(range), !is_private)) {
220 		error = -EINVAL;
221 		goto err_kasan;
222 	}
223 
224 	mem_hotplug_begin();
225 
226 	/*
227 	 * For device private memory we call add_pages() as we only need to
228 	 * allocate and initialize struct page for the device memory. More-
229 	 * over the device memory is un-accessible thus we do not want to
230 	 * create a linear mapping for the memory like arch_add_memory()
231 	 * would do.
232 	 *
233 	 * For all other device memory types, which are accessible by
234 	 * the CPU, we do want the linear mapping and thus use
235 	 * arch_add_memory().
236 	 */
237 	if (is_private) {
238 		error = add_pages(nid, PHYS_PFN(range->start),
239 				PHYS_PFN(range_len(range)), params);
240 	} else {
241 		error = kasan_add_zero_shadow(__va(range->start), range_len(range));
242 		if (error) {
243 			mem_hotplug_done();
244 			goto err_kasan;
245 		}
246 
247 		error = arch_add_memory(nid, range->start, range_len(range),
248 					params);
249 	}
250 
251 	if (!error) {
252 		struct zone *zone;
253 
254 		zone = &NODE_DATA(nid)->node_zones[ZONE_DEVICE];
255 		move_pfn_range_to_zone(zone, PHYS_PFN(range->start),
256 				PHYS_PFN(range_len(range)), params->altmap,
257 				MIGRATE_MOVABLE);
258 	}
259 
260 	mem_hotplug_done();
261 	if (error)
262 		goto err_add_memory;
263 
264 	/*
265 	 * Initialization of the pages has been deferred until now in order
266 	 * to allow us to do the work while not holding the hotplug lock.
267 	 */
268 	memmap_init_zone_device(&NODE_DATA(nid)->node_zones[ZONE_DEVICE],
269 				PHYS_PFN(range->start),
270 				PHYS_PFN(range_len(range)), pgmap);
271 	if (pgmap->type != MEMORY_DEVICE_PRIVATE &&
272 	    pgmap->type != MEMORY_DEVICE_COHERENT)
273 		percpu_ref_get_many(&pgmap->ref, pfn_len(pgmap, range_id));
274 	return 0;
275 
276 err_add_memory:
277 	if (!is_private)
278 		kasan_remove_zero_shadow(__va(range->start), range_len(range));
279 err_kasan:
280 	untrack_pfn(NULL, PHYS_PFN(range->start), range_len(range), true);
281 err_pfn_remap:
282 	pgmap_array_delete(range);
283 	return error;
284 }
285 
286 
287 /*
288  * Not device managed version of devm_memremap_pages, undone by
289  * memunmap_pages().  Please use devm_memremap_pages if you have a struct
290  * device available.
291  */
memremap_pages(struct dev_pagemap * pgmap,int nid)292 void *memremap_pages(struct dev_pagemap *pgmap, int nid)
293 {
294 	struct mhp_params params = {
295 		.altmap = pgmap_altmap(pgmap),
296 		.pgmap = pgmap,
297 		.pgprot = PAGE_KERNEL,
298 	};
299 	const int nr_range = pgmap->nr_range;
300 	int error, i;
301 
302 	if (WARN_ONCE(!nr_range, "nr_range must be specified\n"))
303 		return ERR_PTR(-EINVAL);
304 
305 	switch (pgmap->type) {
306 	case MEMORY_DEVICE_PRIVATE:
307 		if (!IS_ENABLED(CONFIG_DEVICE_PRIVATE)) {
308 			WARN(1, "Device private memory not supported\n");
309 			return ERR_PTR(-EINVAL);
310 		}
311 		if (!pgmap->ops || !pgmap->ops->migrate_to_ram) {
312 			WARN(1, "Missing migrate_to_ram method\n");
313 			return ERR_PTR(-EINVAL);
314 		}
315 		if (!pgmap->ops->page_free) {
316 			WARN(1, "Missing page_free method\n");
317 			return ERR_PTR(-EINVAL);
318 		}
319 		if (!pgmap->owner) {
320 			WARN(1, "Missing owner\n");
321 			return ERR_PTR(-EINVAL);
322 		}
323 		break;
324 	case MEMORY_DEVICE_COHERENT:
325 		if (!pgmap->ops->page_free) {
326 			WARN(1, "Missing page_free method\n");
327 			return ERR_PTR(-EINVAL);
328 		}
329 		if (!pgmap->owner) {
330 			WARN(1, "Missing owner\n");
331 			return ERR_PTR(-EINVAL);
332 		}
333 		break;
334 	case MEMORY_DEVICE_FS_DAX:
335 		if (IS_ENABLED(CONFIG_FS_DAX_LIMITED)) {
336 			WARN(1, "File system DAX not supported\n");
337 			return ERR_PTR(-EINVAL);
338 		}
339 		params.pgprot = pgprot_decrypted(params.pgprot);
340 		break;
341 	case MEMORY_DEVICE_GENERIC:
342 		break;
343 	case MEMORY_DEVICE_PCI_P2PDMA:
344 		params.pgprot = pgprot_noncached(params.pgprot);
345 		break;
346 	default:
347 		WARN(1, "Invalid pgmap type %d\n", pgmap->type);
348 		break;
349 	}
350 
351 	init_completion(&pgmap->done);
352 	error = percpu_ref_init(&pgmap->ref, dev_pagemap_percpu_release, 0,
353 				GFP_KERNEL);
354 	if (error)
355 		return ERR_PTR(error);
356 
357 	devmap_managed_enable_get(pgmap);
358 
359 	/*
360 	 * Clear the pgmap nr_range as it will be incremented for each
361 	 * successfully processed range. This communicates how many
362 	 * regions to unwind in the abort case.
363 	 */
364 	pgmap->nr_range = 0;
365 	error = 0;
366 	for (i = 0; i < nr_range; i++) {
367 		error = pagemap_range(pgmap, &params, i, nid);
368 		if (error)
369 			break;
370 		pgmap->nr_range++;
371 	}
372 
373 	if (i < nr_range) {
374 		memunmap_pages(pgmap);
375 		pgmap->nr_range = nr_range;
376 		return ERR_PTR(error);
377 	}
378 
379 	return __va(pgmap->ranges[0].start);
380 }
381 EXPORT_SYMBOL_GPL(memremap_pages);
382 
383 /**
384  * devm_memremap_pages - remap and provide memmap backing for the given resource
385  * @dev: hosting device for @res
386  * @pgmap: pointer to a struct dev_pagemap
387  *
388  * Notes:
389  * 1/ At a minimum the range and type members of @pgmap must be initialized
390  *    by the caller before passing it to this function
391  *
392  * 2/ The altmap field may optionally be initialized, in which case
393  *    PGMAP_ALTMAP_VALID must be set in pgmap->flags.
394  *
395  * 3/ The ref field may optionally be provided, in which pgmap->ref must be
396  *    'live' on entry and will be killed and reaped at
397  *    devm_memremap_pages_release() time, or if this routine fails.
398  *
399  * 4/ range is expected to be a host memory range that could feasibly be
400  *    treated as a "System RAM" range, i.e. not a device mmio range, but
401  *    this is not enforced.
402  */
devm_memremap_pages(struct device * dev,struct dev_pagemap * pgmap)403 void *devm_memremap_pages(struct device *dev, struct dev_pagemap *pgmap)
404 {
405 	int error;
406 	void *ret;
407 
408 	ret = memremap_pages(pgmap, dev_to_node(dev));
409 	if (IS_ERR(ret))
410 		return ret;
411 
412 	error = devm_add_action_or_reset(dev, devm_memremap_pages_release,
413 			pgmap);
414 	if (error)
415 		return ERR_PTR(error);
416 	return ret;
417 }
418 EXPORT_SYMBOL_GPL(devm_memremap_pages);
419 
devm_memunmap_pages(struct device * dev,struct dev_pagemap * pgmap)420 void devm_memunmap_pages(struct device *dev, struct dev_pagemap *pgmap)
421 {
422 	devm_release_action(dev, devm_memremap_pages_release, pgmap);
423 }
424 EXPORT_SYMBOL_GPL(devm_memunmap_pages);
425 
426 /**
427  * get_dev_pagemap() - take a new live reference on the dev_pagemap for @pfn
428  * @pfn: page frame number to lookup page_map
429  * @pgmap: optional known pgmap that already has a reference
430  *
431  * If @pgmap is non-NULL and covers @pfn it will be returned as-is.  If @pgmap
432  * is non-NULL but does not cover @pfn the reference to it will be released.
433  */
get_dev_pagemap(unsigned long pfn,struct dev_pagemap * pgmap)434 struct dev_pagemap *get_dev_pagemap(unsigned long pfn,
435 		struct dev_pagemap *pgmap)
436 {
437 	resource_size_t phys = PFN_PHYS(pfn);
438 
439 	/*
440 	 * In the cached case we're already holding a live reference.
441 	 */
442 	if (pgmap) {
443 		if (phys >= pgmap->range.start && phys <= pgmap->range.end)
444 			return pgmap;
445 		put_dev_pagemap(pgmap);
446 	}
447 
448 	/* fall back to slow path lookup */
449 	rcu_read_lock();
450 	pgmap = xa_load(&pgmap_array, PHYS_PFN(phys));
451 	if (pgmap && !percpu_ref_tryget_live_rcu(&pgmap->ref))
452 		pgmap = NULL;
453 	rcu_read_unlock();
454 
455 	return pgmap;
456 }
457 EXPORT_SYMBOL_GPL(get_dev_pagemap);
458 
free_zone_device_folio(struct folio * folio)459 void free_zone_device_folio(struct folio *folio)
460 {
461 	if (WARN_ON_ONCE(!folio->page.pgmap->ops ||
462 			!folio->page.pgmap->ops->page_free))
463 		return;
464 
465 	mem_cgroup_uncharge(folio);
466 
467 	/*
468 	 * Note: we don't expect anonymous compound pages yet. Once supported
469 	 * and we could PTE-map them similar to THP, we'd have to clear
470 	 * PG_anon_exclusive on all tail pages.
471 	 */
472 	if (folio_test_anon(folio)) {
473 		VM_BUG_ON_FOLIO(folio_test_large(folio), folio);
474 		__ClearPageAnonExclusive(folio_page(folio, 0));
475 	}
476 
477 	/*
478 	 * When a device managed page is freed, the folio->mapping field
479 	 * may still contain a (stale) mapping value. For example, the
480 	 * lower bits of folio->mapping may still identify the folio as an
481 	 * anonymous folio. Ultimately, this entire field is just stale
482 	 * and wrong, and it will cause errors if not cleared.
483 	 *
484 	 * For other types of ZONE_DEVICE pages, migration is either
485 	 * handled differently or not done at all, so there is no need
486 	 * to clear folio->mapping.
487 	 */
488 	folio->mapping = NULL;
489 	folio->page.pgmap->ops->page_free(folio_page(folio, 0));
490 
491 	if (folio->page.pgmap->type != MEMORY_DEVICE_PRIVATE &&
492 	    folio->page.pgmap->type != MEMORY_DEVICE_COHERENT)
493 		/*
494 		 * Reset the refcount to 1 to prepare for handing out the page
495 		 * again.
496 		 */
497 		folio_set_count(folio, 1);
498 	else
499 		put_dev_pagemap(folio->page.pgmap);
500 }
501 
zone_device_page_init(struct page * page)502 void zone_device_page_init(struct page *page)
503 {
504 	/*
505 	 * Drivers shouldn't be allocating pages after calling
506 	 * memunmap_pages().
507 	 */
508 	WARN_ON_ONCE(!percpu_ref_tryget_live(&page->pgmap->ref));
509 	set_page_count(page, 1);
510 	lock_page(page);
511 }
512 EXPORT_SYMBOL_GPL(zone_device_page_init);
513 
514 #ifdef CONFIG_FS_DAX
__put_devmap_managed_folio_refs(struct folio * folio,int refs)515 bool __put_devmap_managed_folio_refs(struct folio *folio, int refs)
516 {
517 	if (folio->page.pgmap->type != MEMORY_DEVICE_FS_DAX)
518 		return false;
519 
520 	/*
521 	 * fsdax page refcounts are 1-based, rather than 0-based: if
522 	 * refcount is 1, then the page is free and the refcount is
523 	 * stable because nobody holds a reference on the page.
524 	 */
525 	if (folio_ref_sub_return(folio, refs) == 1)
526 		wake_up_var(&folio->_refcount);
527 	return true;
528 }
529 EXPORT_SYMBOL(__put_devmap_managed_folio_refs);
530 #endif /* CONFIG_FS_DAX */
531