33d31e48ec158819489af3eff8362cf226a9c73c
[linux-2.6-microblaze.git] / arch / powerpc / platforms / pseries / cmm.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Collaborative memory management interface.
4  *
5  * Copyright (C) 2008 IBM Corporation
6  * Author(s): Brian King (brking@linux.vnet.ibm.com),
7  */
8
9 #include <linux/ctype.h>
10 #include <linux/delay.h>
11 #include <linux/errno.h>
12 #include <linux/fs.h>
13 #include <linux/gfp.h>
14 #include <linux/kthread.h>
15 #include <linux/module.h>
16 #include <linux/oom.h>
17 #include <linux/reboot.h>
18 #include <linux/sched.h>
19 #include <linux/stringify.h>
20 #include <linux/swap.h>
21 #include <linux/device.h>
22 #include <asm/firmware.h>
23 #include <asm/hvcall.h>
24 #include <asm/mmu.h>
25 #include <asm/pgalloc.h>
26 #include <linux/uaccess.h>
27 #include <linux/memory.h>
28 #include <asm/plpar_wrappers.h>
29
30 #include "pseries.h"
31
32 #define CMM_DRIVER_VERSION      "1.0.0"
33 #define CMM_DEFAULT_DELAY       1
34 #define CMM_HOTPLUG_DELAY       5
35 #define CMM_DEBUG                       0
36 #define CMM_DISABLE             0
37 #define CMM_OOM_KB              1024
38 #define CMM_MIN_MEM_MB          256
39 #define KB2PAGES(_p)            ((_p)>>(PAGE_SHIFT-10))
40 #define PAGES2KB(_p)            ((_p)<<(PAGE_SHIFT-10))
41 /*
42  * The priority level tries to ensure that this notifier is called as
43  * late as possible to reduce thrashing in the shared memory pool.
44  */
45 #define CMM_MEM_HOTPLUG_PRI     1
46 #define CMM_MEM_ISOLATE_PRI     15
47
48 static unsigned int delay = CMM_DEFAULT_DELAY;
49 static unsigned int hotplug_delay = CMM_HOTPLUG_DELAY;
50 static unsigned int oom_kb = CMM_OOM_KB;
51 static unsigned int cmm_debug = CMM_DEBUG;
52 static unsigned int cmm_disabled = CMM_DISABLE;
53 static unsigned long min_mem_mb = CMM_MIN_MEM_MB;
54 static struct device cmm_dev;
55
56 MODULE_AUTHOR("Brian King <brking@linux.vnet.ibm.com>");
57 MODULE_DESCRIPTION("IBM System p Collaborative Memory Manager");
58 MODULE_LICENSE("GPL");
59 MODULE_VERSION(CMM_DRIVER_VERSION);
60
61 module_param_named(delay, delay, uint, 0644);
62 MODULE_PARM_DESC(delay, "Delay (in seconds) between polls to query hypervisor paging requests. "
63                  "[Default=" __stringify(CMM_DEFAULT_DELAY) "]");
64 module_param_named(hotplug_delay, hotplug_delay, uint, 0644);
65 MODULE_PARM_DESC(hotplug_delay, "Delay (in seconds) after memory hotplug remove "
66                  "before loaning resumes. "
67                  "[Default=" __stringify(CMM_HOTPLUG_DELAY) "]");
68 module_param_named(oom_kb, oom_kb, uint, 0644);
69 MODULE_PARM_DESC(oom_kb, "Amount of memory in kb to free on OOM. "
70                  "[Default=" __stringify(CMM_OOM_KB) "]");
71 module_param_named(min_mem_mb, min_mem_mb, ulong, 0644);
72 MODULE_PARM_DESC(min_mem_mb, "Minimum amount of memory (in MB) to not balloon. "
73                  "[Default=" __stringify(CMM_MIN_MEM_MB) "]");
74 module_param_named(debug, cmm_debug, uint, 0644);
75 MODULE_PARM_DESC(debug, "Enable module debugging logging. Set to 1 to enable. "
76                  "[Default=" __stringify(CMM_DEBUG) "]");
77
78 #define cmm_dbg(...) if (cmm_debug) { printk(KERN_INFO "cmm: "__VA_ARGS__); }
79
80 static unsigned long loaned_pages;
81 static unsigned long loaned_pages_target;
82 static unsigned long oom_freed_pages;
83
84 static LIST_HEAD(cmm_page_list);
85 static DEFINE_SPINLOCK(cmm_lock);
86
87 static DEFINE_MUTEX(hotplug_mutex);
88 static int hotplug_occurred; /* protected by the hotplug mutex */
89
90 static struct task_struct *cmm_thread_ptr;
91
92 static long plpar_page_set_loaned(struct page *page)
93 {
94         const unsigned long vpa = page_to_phys(page);
95         unsigned long cmo_page_sz = cmo_get_page_size();
96         long rc = 0;
97         int i;
98
99         for (i = 0; !rc && i < PAGE_SIZE; i += cmo_page_sz)
100                 rc = plpar_hcall_norets(H_PAGE_INIT, H_PAGE_SET_LOANED, vpa + i, 0);
101
102         for (i -= cmo_page_sz; rc && i != 0; i -= cmo_page_sz)
103                 plpar_hcall_norets(H_PAGE_INIT, H_PAGE_SET_ACTIVE,
104                                    vpa + i - cmo_page_sz, 0);
105
106         return rc;
107 }
108
109 static long plpar_page_set_active(struct page *page)
110 {
111         const unsigned long vpa = page_to_phys(page);
112         unsigned long cmo_page_sz = cmo_get_page_size();
113         long rc = 0;
114         int i;
115
116         for (i = 0; !rc && i < PAGE_SIZE; i += cmo_page_sz)
117                 rc = plpar_hcall_norets(H_PAGE_INIT, H_PAGE_SET_ACTIVE, vpa + i, 0);
118
119         for (i -= cmo_page_sz; rc && i != 0; i -= cmo_page_sz)
120                 plpar_hcall_norets(H_PAGE_INIT, H_PAGE_SET_LOANED,
121                                    vpa + i - cmo_page_sz, 0);
122
123         return rc;
124 }
125
126 /**
127  * cmm_alloc_pages - Allocate pages and mark them as loaned
128  * @nr: number of pages to allocate
129  *
130  * Return value:
131  *      number of pages requested to be allocated which were not
132  **/
133 static long cmm_alloc_pages(long nr)
134 {
135         struct page *page;
136         long rc;
137
138         cmm_dbg("Begin request for %ld pages\n", nr);
139
140         while (nr) {
141                 /* Exit if a hotplug operation is in progress or occurred */
142                 if (mutex_trylock(&hotplug_mutex)) {
143                         if (hotplug_occurred) {
144                                 mutex_unlock(&hotplug_mutex);
145                                 break;
146                         }
147                         mutex_unlock(&hotplug_mutex);
148                 } else {
149                         break;
150                 }
151
152                 page = alloc_page(GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY |
153                                   __GFP_NOMEMALLOC);
154                 if (!page)
155                         break;
156                 spin_lock(&cmm_lock);
157                 rc = plpar_page_set_loaned(page);
158                 if (rc) {
159                         pr_err("%s: Can not set page to loaned. rc=%ld\n", __func__, rc);
160                         spin_unlock(&cmm_lock);
161                         __free_page(page);
162                         break;
163                 }
164
165                 list_add(&page->lru, &cmm_page_list);
166                 loaned_pages++;
167                 totalram_pages_dec();
168                 spin_unlock(&cmm_lock);
169                 nr--;
170         }
171
172         cmm_dbg("End request with %ld pages unfulfilled\n", nr);
173         return nr;
174 }
175
176 /**
177  * cmm_free_pages - Free pages and mark them as active
178  * @nr: number of pages to free
179  *
180  * Return value:
181  *      number of pages requested to be freed which were not
182  **/
183 static long cmm_free_pages(long nr)
184 {
185         struct page *page, *tmp;
186
187         cmm_dbg("Begin free of %ld pages.\n", nr);
188         spin_lock(&cmm_lock);
189         list_for_each_entry_safe(page, tmp, &cmm_page_list, lru) {
190                 if (!nr)
191                         break;
192                 plpar_page_set_active(page);
193                 list_del(&page->lru);
194                 __free_page(page);
195                 loaned_pages--;
196                 nr--;
197                 totalram_pages_inc();
198         }
199         spin_unlock(&cmm_lock);
200         cmm_dbg("End request with %ld pages unfulfilled\n", nr);
201         return nr;
202 }
203
204 /**
205  * cmm_oom_notify - OOM notifier
206  * @self:       notifier block struct
207  * @dummy:      not used
208  * @parm:       returned - number of pages freed
209  *
210  * Return value:
211  *      NOTIFY_OK
212  **/
213 static int cmm_oom_notify(struct notifier_block *self,
214                           unsigned long dummy, void *parm)
215 {
216         unsigned long *freed = parm;
217         long nr = KB2PAGES(oom_kb);
218
219         cmm_dbg("OOM processing started\n");
220         nr = cmm_free_pages(nr);
221         loaned_pages_target = loaned_pages;
222         *freed += KB2PAGES(oom_kb) - nr;
223         oom_freed_pages += KB2PAGES(oom_kb) - nr;
224         cmm_dbg("OOM processing complete\n");
225         return NOTIFY_OK;
226 }
227
228 /**
229  * cmm_get_mpp - Read memory performance parameters
230  *
231  * Makes hcall to query the current page loan request from the hypervisor.
232  *
233  * Return value:
234  *      nothing
235  **/
236 static void cmm_get_mpp(void)
237 {
238         int rc;
239         struct hvcall_mpp_data mpp_data;
240         signed long active_pages_target, page_loan_request, target;
241         signed long total_pages = totalram_pages() + loaned_pages;
242         signed long min_mem_pages = (min_mem_mb * 1024 * 1024) / PAGE_SIZE;
243
244         rc = h_get_mpp(&mpp_data);
245
246         if (rc != H_SUCCESS)
247                 return;
248
249         page_loan_request = div_s64((s64)mpp_data.loan_request, PAGE_SIZE);
250         target = page_loan_request + (signed long)loaned_pages;
251
252         if (target < 0 || total_pages < min_mem_pages)
253                 target = 0;
254
255         if (target > oom_freed_pages)
256                 target -= oom_freed_pages;
257         else
258                 target = 0;
259
260         active_pages_target = total_pages - target;
261
262         if (min_mem_pages > active_pages_target)
263                 target = total_pages - min_mem_pages;
264
265         if (target < 0)
266                 target = 0;
267
268         loaned_pages_target = target;
269
270         cmm_dbg("delta = %ld, loaned = %lu, target = %lu, oom = %lu, totalram = %lu\n",
271                 page_loan_request, loaned_pages, loaned_pages_target,
272                 oom_freed_pages, totalram_pages());
273 }
274
275 static struct notifier_block cmm_oom_nb = {
276         .notifier_call = cmm_oom_notify
277 };
278
279 /**
280  * cmm_thread - CMM task thread
281  * @dummy:      not used
282  *
283  * Return value:
284  *      0
285  **/
286 static int cmm_thread(void *dummy)
287 {
288         unsigned long timeleft;
289
290         while (1) {
291                 timeleft = msleep_interruptible(delay * 1000);
292
293                 if (kthread_should_stop() || timeleft)
294                         break;
295
296                 if (mutex_trylock(&hotplug_mutex)) {
297                         if (hotplug_occurred) {
298                                 hotplug_occurred = 0;
299                                 mutex_unlock(&hotplug_mutex);
300                                 cmm_dbg("Hotplug operation has occurred, "
301                                                 "loaning activity suspended "
302                                                 "for %d seconds.\n",
303                                                 hotplug_delay);
304                                 timeleft = msleep_interruptible(hotplug_delay *
305                                                 1000);
306                                 if (kthread_should_stop() || timeleft)
307                                         break;
308                                 continue;
309                         }
310                         mutex_unlock(&hotplug_mutex);
311                 } else {
312                         cmm_dbg("Hotplug operation in progress, activity "
313                                         "suspended\n");
314                         continue;
315                 }
316
317                 cmm_get_mpp();
318
319                 if (loaned_pages_target > loaned_pages) {
320                         if (cmm_alloc_pages(loaned_pages_target - loaned_pages))
321                                 loaned_pages_target = loaned_pages;
322                 } else if (loaned_pages_target < loaned_pages)
323                         cmm_free_pages(loaned_pages - loaned_pages_target);
324         }
325         return 0;
326 }
327
328 #define CMM_SHOW(name, format, args...)                 \
329         static ssize_t show_##name(struct device *dev,  \
330                                    struct device_attribute *attr,       \
331                                    char *buf)                   \
332         {                                                       \
333                 return sprintf(buf, format, ##args);            \
334         }                                                       \
335         static DEVICE_ATTR(name, 0444, show_##name, NULL)
336
337 CMM_SHOW(loaned_kb, "%lu\n", PAGES2KB(loaned_pages));
338 CMM_SHOW(loaned_target_kb, "%lu\n", PAGES2KB(loaned_pages_target));
339
340 static ssize_t show_oom_pages(struct device *dev,
341                               struct device_attribute *attr, char *buf)
342 {
343         return sprintf(buf, "%lu\n", PAGES2KB(oom_freed_pages));
344 }
345
346 static ssize_t store_oom_pages(struct device *dev,
347                                struct device_attribute *attr,
348                                const char *buf, size_t count)
349 {
350         unsigned long val = simple_strtoul (buf, NULL, 10);
351
352         if (!capable(CAP_SYS_ADMIN))
353                 return -EPERM;
354         if (val != 0)
355                 return -EBADMSG;
356
357         oom_freed_pages = 0;
358         return count;
359 }
360
361 static DEVICE_ATTR(oom_freed_kb, 0644,
362                    show_oom_pages, store_oom_pages);
363
364 static struct device_attribute *cmm_attrs[] = {
365         &dev_attr_loaned_kb,
366         &dev_attr_loaned_target_kb,
367         &dev_attr_oom_freed_kb,
368 };
369
370 static struct bus_type cmm_subsys = {
371         .name = "cmm",
372         .dev_name = "cmm",
373 };
374
375 static void cmm_release_device(struct device *dev)
376 {
377 }
378
379 /**
380  * cmm_sysfs_register - Register with sysfs
381  *
382  * Return value:
383  *      0 on success / other on failure
384  **/
385 static int cmm_sysfs_register(struct device *dev)
386 {
387         int i, rc;
388
389         if ((rc = subsys_system_register(&cmm_subsys, NULL)))
390                 return rc;
391
392         dev->id = 0;
393         dev->bus = &cmm_subsys;
394         dev->release = cmm_release_device;
395
396         if ((rc = device_register(dev)))
397                 goto subsys_unregister;
398
399         for (i = 0; i < ARRAY_SIZE(cmm_attrs); i++) {
400                 if ((rc = device_create_file(dev, cmm_attrs[i])))
401                         goto fail;
402         }
403
404         return 0;
405
406 fail:
407         while (--i >= 0)
408                 device_remove_file(dev, cmm_attrs[i]);
409         device_unregister(dev);
410 subsys_unregister:
411         bus_unregister(&cmm_subsys);
412         return rc;
413 }
414
415 /**
416  * cmm_unregister_sysfs - Unregister from sysfs
417  *
418  **/
419 static void cmm_unregister_sysfs(struct device *dev)
420 {
421         int i;
422
423         for (i = 0; i < ARRAY_SIZE(cmm_attrs); i++)
424                 device_remove_file(dev, cmm_attrs[i]);
425         device_unregister(dev);
426         bus_unregister(&cmm_subsys);
427 }
428
429 /**
430  * cmm_reboot_notifier - Make sure pages are not still marked as "loaned"
431  *
432  **/
433 static int cmm_reboot_notifier(struct notifier_block *nb,
434                                unsigned long action, void *unused)
435 {
436         if (action == SYS_RESTART) {
437                 if (cmm_thread_ptr)
438                         kthread_stop(cmm_thread_ptr);
439                 cmm_thread_ptr = NULL;
440                 cmm_free_pages(loaned_pages);
441         }
442         return NOTIFY_DONE;
443 }
444
445 static struct notifier_block cmm_reboot_nb = {
446         .notifier_call = cmm_reboot_notifier,
447 };
448
449 /**
450  * cmm_count_pages - Count the number of pages loaned in a particular range.
451  *
452  * @arg: memory_isolate_notify structure with address range and count
453  *
454  * Return value:
455  *      0 on success
456  **/
457 static unsigned long cmm_count_pages(void *arg)
458 {
459         struct memory_isolate_notify *marg = arg;
460         struct page *page;
461
462         spin_lock(&cmm_lock);
463         list_for_each_entry(page, &cmm_page_list, lru) {
464                 if (page_to_pfn(page) >= marg->start_pfn &&
465                     page_to_pfn(page) < marg->start_pfn + marg->nr_pages)
466                         marg->pages_found++;
467         }
468         spin_unlock(&cmm_lock);
469         return 0;
470 }
471
472 /**
473  * cmm_memory_isolate_cb - Handle memory isolation notifier calls
474  * @self:       notifier block struct
475  * @action:     action to take
476  * @arg:        struct memory_isolate_notify data for handler
477  *
478  * Return value:
479  *      NOTIFY_OK or notifier error based on subfunction return value
480  **/
481 static int cmm_memory_isolate_cb(struct notifier_block *self,
482                                  unsigned long action, void *arg)
483 {
484         int ret = 0;
485
486         if (action == MEM_ISOLATE_COUNT)
487                 ret = cmm_count_pages(arg);
488
489         return notifier_from_errno(ret);
490 }
491
492 static struct notifier_block cmm_mem_isolate_nb = {
493         .notifier_call = cmm_memory_isolate_cb,
494         .priority = CMM_MEM_ISOLATE_PRI
495 };
496
497 /**
498  * cmm_mem_going_offline - Unloan pages where memory is to be removed
499  * @arg: memory_notify structure with page range to be offlined
500  *
501  * Return value:
502  *      0 on success
503  **/
504 static int cmm_mem_going_offline(void *arg)
505 {
506         struct memory_notify *marg = arg;
507         struct page *page, *tmp;
508         unsigned long freed = 0;
509
510         cmm_dbg("Memory going offline, searching PFN 0x%lx (%ld pages).\n",
511                 marg->start_pfn, marg->nr_pages);
512         spin_lock(&cmm_lock);
513
514         /* Search the page list for pages in the range to be offlined */
515         list_for_each_entry_safe(page, tmp, &cmm_page_list, lru) {
516                 if (page_to_pfn(page) < marg->start_pfn ||
517                     page_to_pfn(page) >= marg->start_pfn + marg->nr_pages)
518                         continue;
519                 plpar_page_set_active(page);
520                 list_del(&page->lru);
521                 __free_page(page);
522                 freed++;
523                 loaned_pages--;
524                 totalram_pages_inc();
525         }
526
527         spin_unlock(&cmm_lock);
528         cmm_dbg("Released %ld pages in the search range.\n", freed);
529
530         return 0;
531 }
532
533 /**
534  * cmm_memory_cb - Handle memory hotplug notifier calls
535  * @self:       notifier block struct
536  * @action:     action to take
537  * @arg:        struct memory_notify data for handler
538  *
539  * Return value:
540  *      NOTIFY_OK or notifier error based on subfunction return value
541  *
542  **/
543 static int cmm_memory_cb(struct notifier_block *self,
544                         unsigned long action, void *arg)
545 {
546         int ret = 0;
547
548         switch (action) {
549         case MEM_GOING_OFFLINE:
550                 mutex_lock(&hotplug_mutex);
551                 hotplug_occurred = 1;
552                 ret = cmm_mem_going_offline(arg);
553                 break;
554         case MEM_OFFLINE:
555         case MEM_CANCEL_OFFLINE:
556                 mutex_unlock(&hotplug_mutex);
557                 cmm_dbg("Memory offline operation complete.\n");
558                 break;
559         case MEM_GOING_ONLINE:
560         case MEM_ONLINE:
561         case MEM_CANCEL_ONLINE:
562                 break;
563         }
564
565         return notifier_from_errno(ret);
566 }
567
568 static struct notifier_block cmm_mem_nb = {
569         .notifier_call = cmm_memory_cb,
570         .priority = CMM_MEM_HOTPLUG_PRI
571 };
572
573 /**
574  * cmm_init - Module initialization
575  *
576  * Return value:
577  *      0 on success / other on failure
578  **/
579 static int cmm_init(void)
580 {
581         int rc;
582
583         if (!firmware_has_feature(FW_FEATURE_CMO))
584                 return -EOPNOTSUPP;
585
586         if ((rc = register_oom_notifier(&cmm_oom_nb)) < 0)
587                 return rc;
588
589         if ((rc = register_reboot_notifier(&cmm_reboot_nb)))
590                 goto out_oom_notifier;
591
592         if ((rc = cmm_sysfs_register(&cmm_dev)))
593                 goto out_reboot_notifier;
594
595         rc = register_memory_notifier(&cmm_mem_nb);
596         if (rc)
597                 goto out_unregister_notifier;
598
599         rc = register_memory_isolate_notifier(&cmm_mem_isolate_nb);
600         if (rc)
601                 goto out_unregister_notifier;
602
603         if (cmm_disabled)
604                 return 0;
605
606         cmm_thread_ptr = kthread_run(cmm_thread, NULL, "cmmthread");
607         if (IS_ERR(cmm_thread_ptr)) {
608                 rc = PTR_ERR(cmm_thread_ptr);
609                 goto out_unregister_notifier;
610         }
611
612         return 0;
613 out_unregister_notifier:
614         unregister_memory_notifier(&cmm_mem_nb);
615         unregister_memory_isolate_notifier(&cmm_mem_isolate_nb);
616         cmm_unregister_sysfs(&cmm_dev);
617 out_reboot_notifier:
618         unregister_reboot_notifier(&cmm_reboot_nb);
619 out_oom_notifier:
620         unregister_oom_notifier(&cmm_oom_nb);
621         return rc;
622 }
623
624 /**
625  * cmm_exit - Module exit
626  *
627  * Return value:
628  *      nothing
629  **/
630 static void cmm_exit(void)
631 {
632         if (cmm_thread_ptr)
633                 kthread_stop(cmm_thread_ptr);
634         unregister_oom_notifier(&cmm_oom_nb);
635         unregister_reboot_notifier(&cmm_reboot_nb);
636         unregister_memory_notifier(&cmm_mem_nb);
637         unregister_memory_isolate_notifier(&cmm_mem_isolate_nb);
638         cmm_free_pages(loaned_pages);
639         cmm_unregister_sysfs(&cmm_dev);
640 }
641
642 /**
643  * cmm_set_disable - Disable/Enable CMM
644  *
645  * Return value:
646  *      0 on success / other on failure
647  **/
648 static int cmm_set_disable(const char *val, const struct kernel_param *kp)
649 {
650         int disable = simple_strtoul(val, NULL, 10);
651
652         if (disable != 0 && disable != 1)
653                 return -EINVAL;
654
655         if (disable && !cmm_disabled) {
656                 if (cmm_thread_ptr)
657                         kthread_stop(cmm_thread_ptr);
658                 cmm_thread_ptr = NULL;
659                 cmm_free_pages(loaned_pages);
660         } else if (!disable && cmm_disabled) {
661                 cmm_thread_ptr = kthread_run(cmm_thread, NULL, "cmmthread");
662                 if (IS_ERR(cmm_thread_ptr))
663                         return PTR_ERR(cmm_thread_ptr);
664         }
665
666         cmm_disabled = disable;
667         return 0;
668 }
669
670 module_param_call(disable, cmm_set_disable, param_get_uint,
671                   &cmm_disabled, 0644);
672 MODULE_PARM_DESC(disable, "Disable CMM. Set to 1 to disable. "
673                  "[Default=" __stringify(CMM_DISABLE) "]");
674
675 module_init(cmm_init);
676 module_exit(cmm_exit);