xref: /linux/drivers/dax/kmem.c (revision 570f7e331f5febb30f1384817463c7e42b65ca7d)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2016-2019 Intel Corporation. All rights reserved. */
3 #include <linux/memremap.h>
4 #include <linux/pagemap.h>
5 #include <linux/memory.h>
6 #include <linux/module.h>
7 #include <linux/device.h>
8 #include <linux/slab.h>
9 #include <linux/dax.h>
10 #include <linux/fs.h>
11 #include <linux/mm.h>
12 #include <linux/mman.h>
13 #include <linux/memory-tiers.h>
14 #include <linux/memory_hotplug.h>
15 #include <linux/string_helpers.h>
16 #include "dax-private.h"
17 #include "bus.h"
18 
19 /*
20  * Default abstract distance assigned to the NUMA node onlined
21  * by DAX/kmem if the low level platform driver didn't initialize
22  * one for this NUMA node.
23  */
24 #define MEMTIER_DEFAULT_DAX_ADISTANCE	(MEMTIER_ADISTANCE_DRAM * 5)
25 
26 /* Memory resource name used for add_memory_driver_managed(). */
27 static const char *kmem_name;
28 /* Set if any memory will remain added when the driver will be unloaded. */
29 static bool any_hotremove_failed;
30 
31 static int dax_kmem_range(struct dev_dax *dev_dax, int i, struct range *r)
32 {
33 	struct dev_dax_range *dax_range = &dev_dax->ranges[i];
34 	struct range *range = &dax_range->range;
35 
36 	*r = memory_block_aligned_range(range);
37 	if (r->start >= r->end) {
38 		r->start = range->start;
39 		r->end = range->end;
40 		return -ENOSPC;
41 	}
42 	return 0;
43 }
44 
45 struct dax_kmem_data {
46 	const char *res_name;
47 	int mgid;
48 	int state;
49 	struct mutex lock; /* protects hotplug state transitions */
50 	struct resource *res[];
51 };
52 
53 static DEFINE_MUTEX(kmem_memory_type_lock);
54 static LIST_HEAD(kmem_memory_types);
55 
56 static struct memory_dev_type *kmem_find_alloc_memory_type(int adist)
57 {
58 	guard(mutex)(&kmem_memory_type_lock);
59 	return mt_find_alloc_memory_type(adist, &kmem_memory_types);
60 }
61 
62 static void kmem_put_memory_types(void)
63 {
64 	guard(mutex)(&kmem_memory_type_lock);
65 	mt_put_memory_types(&kmem_memory_types);
66 }
67 
68 /* True for the online states a kmem dax device can hold. */
69 static bool dax_kmem_state_is_online(int state)
70 {
71 	return state == MMOP_ONLINE ||
72 	       state == MMOP_ONLINE_KERNEL ||
73 	       state == MMOP_ONLINE_MOVABLE;
74 }
75 
76 /**
77  * dax_kmem_do_hotplug - hotplug memory for dax kmem device
78  * @dev_dax: the dev_dax instance
79  * @data: the dax_kmem_data structure with resource tracking
80  * @online_type: the online policy to use for the memory blocks
81  *
82  * Hotplugs all ranges in the dev_dax region as system memory with the
83  * provided online policy (offline, online, online_movable, online_kernel).
84  *
85  * Returns the number of successfully mapped ranges, or negative error.
86  */
87 static int dax_kmem_do_hotplug(struct dev_dax *dev_dax,
88 			       struct dax_kmem_data *data,
89 			       int online_type)
90 {
91 	struct device *dev = &dev_dax->dev;
92 	int i, rc, added = 0;
93 	mhp_t mhp_flags;
94 
95 	if (dax_kmem_state_is_online(data->state))
96 		return -EINVAL;
97 
98 	if (online_type < MMOP_OFFLINE || online_type > MMOP_ONLINE_MOVABLE)
99 		return -EINVAL;
100 
101 	for (i = 0; i < dev_dax->nr_range; i++) {
102 		struct range range;
103 
104 		rc = dax_kmem_range(dev_dax, i, &range);
105 		if (rc)
106 			continue;
107 
108 		/*
109 		 * init_resources() is best-effort: if a reservation conflict
110 		 * occurs it keeps the range but leaves res[i]=NULL. For hotplug
111 		 * on probe systems, this means kmem will partially online.
112 		 *
113 		 * We have to keep this behavior not to break those systems.
114 		 * For those systems - atomicity only applies to valid ranges.
115 		 */
116 		if (!data->res[i])
117 			continue;
118 
119 		mhp_flags = MHP_NID_IS_MGID;
120 		if (dev_dax->memmap_on_memory)
121 			mhp_flags |= MHP_MEMMAP_ON_MEMORY;
122 
123 		/*
124 		 * Ensure that future kexec'd kernels will not treat
125 		 * this as RAM automatically.
126 		 */
127 		rc = __add_memory_driver_managed(data->mgid, range.start,
128 				range_len(&range), kmem_name, mhp_flags,
129 				online_type);
130 
131 		if (rc) {
132 			dev_warn(dev, "mapping%d: %#llx-%#llx memory add failed\n",
133 				 i, range.start, range.end);
134 			/*
135 			 * Release the reservation for the range that failed to
136 			 * add so a later hotremove does not try to remove memory
137 			 * that was never added.
138 			 */
139 			if (data->res[i]) {
140 				remove_resource(data->res[i]);
141 				kfree(data->res[i]);
142 				data->res[i] = NULL;
143 			}
144 			if (added)
145 				continue;
146 			return rc;
147 		}
148 		added++;
149 	}
150 
151 	return added;
152 }
153 
154 /**
155  * dax_kmem_init_resources - create memory regions for dax kmem
156  * @dev_dax: the dev_dax instance
157  * @data: the dax_kmem_data structure with resource tracking
158  *
159  * Initializes all the resources for the DAX
160  *
161  * Returns the number of successfully mapped ranges, or negative error.
162  */
163 static int dax_kmem_init_resources(struct dev_dax *dev_dax,
164 				   struct dax_kmem_data *data)
165 {
166 	struct device *dev = &dev_dax->dev;
167 	int i, rc, mapped = 0;
168 
169 	for (i = 0; i < dev_dax->nr_range; i++) {
170 		struct resource *res;
171 		struct range range;
172 
173 		rc = dax_kmem_range(dev_dax, i, &range);
174 		if (rc)
175 			continue;
176 
177 		/* Skip ranges already added */
178 		if (data->res[i])
179 			continue;
180 
181 		/* Region is permanently reserved if hotremove fails. */
182 		res = request_mem_region(range.start, range_len(&range),
183 					 data->res_name);
184 		if (!res) {
185 			dev_warn(dev, "mapping%d: %#llx-%#llx could not reserve region\n",
186 				 i, range.start, range.end);
187 			/*
188 			 * Once some memory has been onlined we can't
189 			 * assume that it can be un-onlined safely.
190 			 */
191 			if (mapped)
192 				continue;
193 			return -EBUSY;
194 		}
195 		data->res[i] = res;
196 		/*
197 		 * Set flags appropriate for System RAM.  Leave ..._BUSY clear
198 		 * so that add_memory() can add a child resource.  Do not
199 		 * inherit flags from the parent since it may set new flags
200 		 * unknown to us that will break add_memory() later.
201 		 */
202 		res->flags = IORESOURCE_SYSTEM_RAM;
203 		mapped++;
204 	}
205 	return mapped;
206 }
207 
208 #ifdef CONFIG_MEMORY_HOTREMOVE
209 /**
210  * dax_kmem_do_hotremove - hot-remove memory for dax kmem device
211  * @dev_dax: the dev_dax instance
212  * @data: the dax_kmem_data structure with resource tracking
213  *
214  * Offlines and removes every currently-added range in the dev_dax region
215  * atomically: either all ranges are offlined and removed, or none are and
216  * the device is returned to its prior state.
217  *
218  * Returns 0 on success, or a negative errno on failure.
219  */
220 static int dax_kmem_do_hotremove(struct dev_dax *dev_dax,
221 				 struct dax_kmem_data *data)
222 {
223 	struct device *dev = &dev_dax->dev;
224 	struct range *ranges;
225 	int i, nr_ranges = 0, rc;
226 
227 	ranges = kmalloc_objs(*ranges, dev_dax->nr_range);
228 	if (!ranges)
229 		return -ENOMEM;
230 
231 	/* Collect the ranges that were actually added during probe. */
232 	for (i = 0; i < dev_dax->nr_range; i++) {
233 		struct range range;
234 
235 		if (!data->res[i])
236 			continue;
237 		if (dax_kmem_range(dev_dax, i, &range))
238 			continue;
239 		ranges[nr_ranges++] = range;
240 	}
241 
242 	/* Nothing added means nothing to remove. */
243 	if (!nr_ranges) {
244 		kfree(ranges);
245 		return 0;
246 	}
247 
248 	rc = offline_and_remove_memory_ranges(ranges, nr_ranges);
249 	kfree(ranges);
250 	if (rc) {
251 		/* Recoverable: the ranges rolled back, nothing is leaked yet. */
252 		dev_err(dev, "hotremove failed, device left online: %d\n", rc);
253 		return rc;
254 	}
255 
256 	/* All ranges removed; release the reserved resources. */
257 	for (i = 0; i < dev_dax->nr_range; i++) {
258 		if (!data->res[i])
259 			continue;
260 		remove_resource(data->res[i]);
261 		kfree(data->res[i]);
262 		data->res[i] = NULL;
263 	}
264 
265 	return 0;
266 }
267 #else
268 static int dax_kmem_do_hotremove(struct dev_dax *dev_dax,
269 				 struct dax_kmem_data *data)
270 {
271 	return -EBUSY;
272 }
273 #endif /* CONFIG_MEMORY_HOTREMOVE */
274 
275 /**
276  * dax_kmem_cleanup_resources - remove the dax memory resources
277  * @dev_dax: the dev_dax instance
278  * @data: the dax_kmem_data structure with resource tracking
279  *
280  * Removes all resources in the dev_dax region.
281  */
282 static void dax_kmem_cleanup_resources(struct dev_dax *dev_dax,
283 				       struct dax_kmem_data *data)
284 {
285 	int i;
286 
287 	/*
288 	 * If the device unbind occurs before memory is hotremoved, we can never
289 	 * remove the memory (requires reboot).  Attempting an offline operation
290 	 * here may cause deadlock and a failure to finish the unbind.
291 	 *
292 	 * Note: This leaks the resources.
293 	 */
294 	if (WARN(((data->state != DAX_KMEM_UNPLUGGED) &&
295 		  (data->state != MMOP_OFFLINE)),
296 		 "Hotplug memory regions stuck online until reboot"))
297 		return;
298 
299 	for (i = 0; i < dev_dax->nr_range; i++) {
300 		if (!data->res[i])
301 			continue;
302 		remove_resource(data->res[i]);
303 		kfree(data->res[i]);
304 		data->res[i] = NULL;
305 	}
306 }
307 
308 static int dax_kmem_parse_state(const char *buf)
309 {
310 	int online_type;
311 
312 	/* "unplugged" is kmem-specific - the rest map to MMOP_ */
313 	if (sysfs_streq(buf, "unplugged"))
314 		return DAX_KMEM_UNPLUGGED;
315 
316 	online_type = mhp_online_type_from_str(buf);
317 	/* Disallow "offline": it's not useful and creates race conditions */
318 	if (online_type == MMOP_OFFLINE)
319 		return -EINVAL;
320 	return online_type;
321 }
322 
323 static ssize_t state_show(struct device *dev,
324 			    struct device_attribute *attr, char *buf)
325 {
326 	struct dax_kmem_data *data = dev_get_drvdata(dev);
327 	const char *state_str;
328 
329 	if (data->state == DAX_KMEM_UNPLUGGED)
330 		state_str = "unplugged";
331 	else
332 		state_str = mhp_online_type_to_str(data->state);
333 
334 	return sysfs_emit(buf, "%s\n", state_str ?: "unknown");
335 }
336 
337 static ssize_t state_store(struct device *dev, struct device_attribute *attr,
338 			     const char *buf, size_t len)
339 {
340 	struct dev_dax *dev_dax = to_dev_dax(dev);
341 	struct dax_kmem_data *data = dev_get_drvdata(dev);
342 	int online_type;
343 	int rc;
344 
345 	online_type = dax_kmem_parse_state(buf);
346 	if (online_type < DAX_KMEM_UNPLUGGED)
347 		return online_type;
348 
349 	guard(mutex)(&data->lock);
350 
351 	/* Already in requested state */
352 	if (data->state == online_type)
353 		return len;
354 
355 	if (online_type == DAX_KMEM_UNPLUGGED) {
356 		rc = dax_kmem_do_hotremove(dev_dax, data);
357 		if (rc)
358 			return rc;
359 		data->state = DAX_KMEM_UNPLUGGED;
360 		return len;
361 	}
362 
363 	/* Onlining is only allowed from the unplugged state. */
364 	if (data->state != DAX_KMEM_UNPLUGGED)
365 		return -EBUSY;
366 
367 	/* Re-acquire resources if previously unplugged, otherwise no-op */
368 	rc = dax_kmem_init_resources(dev_dax, data);
369 	if (rc < 0)
370 		return rc;
371 
372 	rc = dax_kmem_do_hotplug(dev_dax, data, online_type);
373 	if (rc < 0) {
374 		/* Total failure, drop the reservations we took. */
375 		dax_kmem_cleanup_resources(dev_dax, data);
376 		return rc;
377 	}
378 
379 	data->state = online_type;
380 	return len;
381 }
382 
383 static int dev_dax_kmem_probe(struct dev_dax *dev_dax)
384 {
385 	struct device *dev = &dev_dax->dev;
386 	unsigned long total_len = 0, orig_len = 0;
387 	struct dax_kmem_data *data;
388 	struct memory_dev_type *mtype;
389 	int i, rc;
390 	int numa_node;
391 	int adist = MEMTIER_DEFAULT_DAX_ADISTANCE;
392 	int online_type = mhp_get_default_online_type();
393 
394 	/*
395 	 * Ensure good NUMA information for the persistent memory.
396 	 * Without this check, there is a risk that slow memory
397 	 * could be mixed in a node with faster memory, causing
398 	 * unavoidable performance issues.
399 	 */
400 	numa_node = dev_dax->target_node;
401 	if (numa_node < 0) {
402 		dev_warn(dev, "rejecting DAX region with invalid node: %d\n",
403 				numa_node);
404 		return -EINVAL;
405 	}
406 
407 	mt_calc_adistance(numa_node, &adist);
408 	mtype = kmem_find_alloc_memory_type(adist);
409 	if (IS_ERR(mtype))
410 		return PTR_ERR(mtype);
411 
412 	for (i = 0; i < dev_dax->nr_range; i++) {
413 		struct range range;
414 
415 		orig_len += range_len(&dev_dax->ranges[i].range);
416 		rc = dax_kmem_range(dev_dax, i, &range);
417 		if (rc) {
418 			dev_info(dev, "mapping%d: %#llx-%#llx too small after alignment\n",
419 					i, range.start, range.end);
420 			continue;
421 		}
422 		total_len += range_len(&range);
423 	}
424 
425 	if (!total_len) {
426 		dev_warn(dev, "rejecting DAX region without any memory after alignment\n");
427 		return -EINVAL;
428 	} else if (total_len != orig_len) {
429 		char buf[16];
430 
431 		string_get_size(orig_len - total_len, 1, STRING_UNITS_2,
432 				buf, sizeof(buf));
433 		dev_warn(dev, "DAX region truncated by %s due to alignment\n", buf);
434 	}
435 
436 	init_node_memory_type(numa_node, mtype);
437 
438 	rc = -ENOMEM;
439 	data = kzalloc_flex(*data, res, dev_dax->nr_range);
440 	if (!data)
441 		goto err_dax_kmem_data;
442 
443 	data->res_name = kstrdup(dev_name(dev), GFP_KERNEL);
444 	if (!data->res_name)
445 		goto err_res_name;
446 
447 	rc = memory_group_register_static(numa_node, PFN_UP(total_len));
448 	if (rc < 0)
449 		goto err_reg_mgid;
450 	data->mgid = rc;
451 	data->state = DAX_KMEM_UNPLUGGED;
452 	mutex_init(&data->lock);
453 
454 	dev_set_drvdata(dev, data);
455 
456 	rc = dax_kmem_init_resources(dev_dax, data);
457 	if (rc < 0)
458 		goto err_resources;
459 
460 	rc = dax_kmem_do_hotplug(dev_dax, data, online_type);
461 	if (rc < 0)
462 		goto err_hotplug;
463 	data->state = online_type;
464 
465 	return 0;
466 
467 err_hotplug:
468 	dax_kmem_cleanup_resources(dev_dax, data);
469 err_resources:
470 	dev_set_drvdata(dev, NULL);
471 	memory_group_unregister(data->mgid);
472 err_reg_mgid:
473 	kfree(data->res_name);
474 err_res_name:
475 	kfree(data);
476 err_dax_kmem_data:
477 	clear_node_memory_type(numa_node, mtype);
478 	return rc;
479 }
480 
481 #ifdef CONFIG_MEMORY_HOTREMOVE
482 /*
483  * Remove the device's added ranges with remove_memory().
484  * Unlike the sysfs unplug path it never offlines and fails if the blocks are
485  * online (-EBUSY), so it is safe from unbind. Failures leak until reboot.
486  *
487  * Returns 0 only if every added range was removed.
488  */
489 static int dax_kmem_remove_ranges(struct dev_dax *dev_dax,
490 				  struct dax_kmem_data *data)
491 {
492 	struct device *dev = &dev_dax->dev;
493 	int i, rc = 0;
494 
495 	for (i = 0; i < dev_dax->nr_range; i++) {
496 		struct range range;
497 
498 		if (!data->res[i] || dax_kmem_range(dev_dax, i, &range))
499 			continue;
500 		if (remove_memory(range.start, range_len(&range))) {
501 			dev_warn(dev, "mapping%d: %#llx-%#llx stuck online until reboot\n",
502 				 i, range.start, range.end);
503 			rc = -EBUSY;
504 			continue;
505 		}
506 		remove_resource(data->res[i]);
507 		kfree(data->res[i]);
508 		data->res[i] = NULL;
509 	}
510 	return rc;
511 }
512 
513 static void dev_dax_kmem_remove(struct dev_dax *dev_dax)
514 {
515 	int node = dev_dax->target_node;
516 	struct device *dev = &dev_dax->dev;
517 	struct dax_kmem_data *data = dev_get_drvdata(dev);
518 
519 	/*
520 	 * Remove every range that is still added.  dax_kmem_remove_ranges()
521 	 * uses remove_memory(), which never offlines: an online block fails
522 	 * with -EBUSY rather than deadlocking an uninterruptible unbind.
523 	 *
524 	 * data->state only tracks daxX.Y/state writes, so it can be stale if
525 	 * blocks were toggled via memoryX/state. Do not trust it here and
526 	 * attempt simply remove_memory() - which reports the true state of
527 	 * each range anyway. Anything left online is leaked until reboot.
528 	 */
529 	if (dax_kmem_remove_ranges(dev_dax, data)) {
530 		dev_err(dev, "Hotplug regions stuck online until reboot\n");
531 		any_hotremove_failed = true;
532 		return;
533 	}
534 
535 	memory_group_unregister(data->mgid);
536 	kfree(data->res_name);
537 	kfree(data);
538 	dev_set_drvdata(dev, NULL);
539 	/*
540 	 * Clear the memtype association on successful unplug.
541 	 * If not, we have memory blocks left which can be
542 	 * offlined/onlined later. We need to keep memory_dev_type
543 	 * for that. This implies this reference will be around
544 	 * till next reboot.
545 	 */
546 	clear_node_memory_type(node, NULL);
547 }
548 #else
549 static void dev_dax_kmem_remove(struct dev_dax *dev_dax)
550 {
551 	/*
552 	 * Without hotremove purposely leak the request_mem_region() for the
553 	 * device-dax range and return '0' to ->remove() attempts. The removal
554 	 * of the device from the driver always succeeds, but the region is
555 	 * permanently pinned as reserved by the unreleased
556 	 * request_mem_region().
557 	 */
558 	any_hotremove_failed = true;
559 }
560 #endif /* CONFIG_MEMORY_HOTREMOVE */
561 
562 static DEVICE_ATTR_RW(state);
563 
564 static struct attribute *dev_dax_kmem_attrs[] = {
565 	&dev_attr_state.attr,
566 	NULL,
567 };
568 ATTRIBUTE_GROUPS(dev_dax_kmem);
569 
570 static struct dax_device_driver device_dax_kmem_driver = {
571 	.probe = dev_dax_kmem_probe,
572 	.remove = dev_dax_kmem_remove,
573 	.type = DAXDRV_KMEM_TYPE,
574 	.drv = {
575 		.dev_groups = dev_dax_kmem_groups,
576 	},
577 };
578 
579 static int __init dax_kmem_init(void)
580 {
581 	int rc;
582 
583 	/* Resource name is permanently allocated if any hotremove fails. */
584 	kmem_name = kstrdup_const("System RAM (kmem)", GFP_KERNEL);
585 	if (!kmem_name)
586 		return -ENOMEM;
587 
588 	rc = dax_driver_register(&device_dax_kmem_driver);
589 	if (rc)
590 		goto error_dax_driver;
591 
592 	return rc;
593 
594 error_dax_driver:
595 	kmem_put_memory_types();
596 	kfree_const(kmem_name);
597 	return rc;
598 }
599 
600 static void __exit dax_kmem_exit(void)
601 {
602 	dax_driver_unregister(&device_dax_kmem_driver);
603 	if (!any_hotremove_failed)
604 		kfree_const(kmem_name);
605 	kmem_put_memory_types();
606 }
607 
608 MODULE_AUTHOR("Intel Corporation");
609 MODULE_DESCRIPTION("KMEM DAX: map dax-devices as System-RAM");
610 MODULE_LICENSE("GPL v2");
611 module_init(dax_kmem_init);
612 module_exit(dax_kmem_exit);
613 MODULE_ALIAS_DAX_DEVICE(0);
614