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