powerpc/pseries/cmm: Implement balloon compaction
[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 <linux/mount.h>
23 #include <linux/pseudo_fs.h>
24 #include <linux/magic.h>
25 #include <linux/balloon_compaction.h>
26 #include <asm/firmware.h>
27 #include <asm/hvcall.h>
28 #include <asm/mmu.h>
29 #include <asm/pgalloc.h>
30 #include <linux/uaccess.h>
31 #include <linux/memory.h>
32 #include <asm/plpar_wrappers.h>
33
34 #include "pseries.h"
35
36 #define CMM_DRIVER_VERSION      "1.0.0"
37 #define CMM_DEFAULT_DELAY       1
38 #define CMM_HOTPLUG_DELAY       5
39 #define CMM_DEBUG                       0
40 #define CMM_DISABLE             0
41 #define CMM_OOM_KB              1024
42 #define CMM_MIN_MEM_MB          256
43 #define KB2PAGES(_p)            ((_p)>>(PAGE_SHIFT-10))
44 #define PAGES2KB(_p)            ((_p)<<(PAGE_SHIFT-10))
45
46 #define CMM_MEM_HOTPLUG_PRI     1
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 atomic_long_t loaned_pages;
81 static unsigned long loaned_pages_target;
82 static unsigned long oom_freed_pages;
83
84 static DEFINE_MUTEX(hotplug_mutex);
85 static int hotplug_occurred; /* protected by the hotplug mutex */
86
87 static struct task_struct *cmm_thread_ptr;
88 static struct balloon_dev_info b_dev_info;
89
90 static long plpar_page_set_loaned(struct page *page)
91 {
92         const unsigned long vpa = page_to_phys(page);
93         unsigned long cmo_page_sz = cmo_get_page_size();
94         long rc = 0;
95         int i;
96
97         for (i = 0; !rc && i < PAGE_SIZE; i += cmo_page_sz)
98                 rc = plpar_hcall_norets(H_PAGE_INIT, H_PAGE_SET_LOANED, vpa + i, 0);
99
100         for (i -= cmo_page_sz; rc && i != 0; i -= cmo_page_sz)
101                 plpar_hcall_norets(H_PAGE_INIT, H_PAGE_SET_ACTIVE,
102                                    vpa + i - cmo_page_sz, 0);
103
104         return rc;
105 }
106
107 static long plpar_page_set_active(struct page *page)
108 {
109         const unsigned long vpa = page_to_phys(page);
110         unsigned long cmo_page_sz = cmo_get_page_size();
111         long rc = 0;
112         int i;
113
114         for (i = 0; !rc && i < PAGE_SIZE; i += cmo_page_sz)
115                 rc = plpar_hcall_norets(H_PAGE_INIT, H_PAGE_SET_ACTIVE, vpa + i, 0);
116
117         for (i -= cmo_page_sz; rc && i != 0; i -= cmo_page_sz)
118                 plpar_hcall_norets(H_PAGE_INIT, H_PAGE_SET_LOANED,
119                                    vpa + i - cmo_page_sz, 0);
120
121         return rc;
122 }
123
124 /**
125  * cmm_alloc_pages - Allocate pages and mark them as loaned
126  * @nr: number of pages to allocate
127  *
128  * Return value:
129  *      number of pages requested to be allocated which were not
130  **/
131 static long cmm_alloc_pages(long nr)
132 {
133         struct page *page;
134         long rc;
135
136         cmm_dbg("Begin request for %ld pages\n", nr);
137
138         while (nr) {
139                 /* Exit if a hotplug operation is in progress or occurred */
140                 if (mutex_trylock(&hotplug_mutex)) {
141                         if (hotplug_occurred) {
142                                 mutex_unlock(&hotplug_mutex);
143                                 break;
144                         }
145                         mutex_unlock(&hotplug_mutex);
146                 } else {
147                         break;
148                 }
149
150                 page = alloc_page(GFP_NOIO | __GFP_NOWARN | __GFP_NORETRY |
151                                   __GFP_NOMEMALLOC);
152                 if (!page)
153                         break;
154                 rc = plpar_page_set_loaned(page);
155                 if (rc) {
156                         pr_err("%s: Can not set page to loaned. rc=%ld\n", __func__, rc);
157                         __free_page(page);
158                         break;
159                 }
160
161                 balloon_page_enqueue(&b_dev_info, page);
162                 atomic_long_inc(&loaned_pages);
163                 adjust_managed_page_count(page, -1);
164                 nr--;
165         }
166
167         cmm_dbg("End request with %ld pages unfulfilled\n", nr);
168         return nr;
169 }
170
171 /**
172  * cmm_free_pages - Free pages and mark them as active
173  * @nr: number of pages to free
174  *
175  * Return value:
176  *      number of pages requested to be freed which were not
177  **/
178 static long cmm_free_pages(long nr)
179 {
180         struct page *page;
181
182         cmm_dbg("Begin free of %ld pages.\n", nr);
183         while (nr) {
184                 page = balloon_page_dequeue(&b_dev_info);
185                 if (!page)
186                         break;
187                 plpar_page_set_active(page);
188                 adjust_managed_page_count(page, 1);
189                 __free_page(page);
190                 atomic_long_dec(&loaned_pages);
191                 nr--;
192         }
193         cmm_dbg("End request with %ld pages unfulfilled\n", nr);
194         return nr;
195 }
196
197 /**
198  * cmm_oom_notify - OOM notifier
199  * @self:       notifier block struct
200  * @dummy:      not used
201  * @parm:       returned - number of pages freed
202  *
203  * Return value:
204  *      NOTIFY_OK
205  **/
206 static int cmm_oom_notify(struct notifier_block *self,
207                           unsigned long dummy, void *parm)
208 {
209         unsigned long *freed = parm;
210         long nr = KB2PAGES(oom_kb);
211
212         cmm_dbg("OOM processing started\n");
213         nr = cmm_free_pages(nr);
214         loaned_pages_target = atomic_long_read(&loaned_pages);
215         *freed += KB2PAGES(oom_kb) - nr;
216         oom_freed_pages += KB2PAGES(oom_kb) - nr;
217         cmm_dbg("OOM processing complete\n");
218         return NOTIFY_OK;
219 }
220
221 /**
222  * cmm_get_mpp - Read memory performance parameters
223  *
224  * Makes hcall to query the current page loan request from the hypervisor.
225  *
226  * Return value:
227  *      nothing
228  **/
229 static void cmm_get_mpp(void)
230 {
231         const long __loaned_pages = atomic_long_read(&loaned_pages);
232         const long total_pages = totalram_pages() + __loaned_pages;
233         int rc;
234         struct hvcall_mpp_data mpp_data;
235         signed long active_pages_target, page_loan_request, target;
236         signed long min_mem_pages = (min_mem_mb * 1024 * 1024) / PAGE_SIZE;
237
238         rc = h_get_mpp(&mpp_data);
239
240         if (rc != H_SUCCESS)
241                 return;
242
243         page_loan_request = div_s64((s64)mpp_data.loan_request, PAGE_SIZE);
244         target = page_loan_request + __loaned_pages;
245
246         if (target < 0 || total_pages < min_mem_pages)
247                 target = 0;
248
249         if (target > oom_freed_pages)
250                 target -= oom_freed_pages;
251         else
252                 target = 0;
253
254         active_pages_target = total_pages - target;
255
256         if (min_mem_pages > active_pages_target)
257                 target = total_pages - min_mem_pages;
258
259         if (target < 0)
260                 target = 0;
261
262         loaned_pages_target = target;
263
264         cmm_dbg("delta = %ld, loaned = %lu, target = %lu, oom = %lu, totalram = %lu\n",
265                 page_loan_request, __loaned_pages, loaned_pages_target,
266                 oom_freed_pages, totalram_pages());
267 }
268
269 static struct notifier_block cmm_oom_nb = {
270         .notifier_call = cmm_oom_notify
271 };
272
273 /**
274  * cmm_thread - CMM task thread
275  * @dummy:      not used
276  *
277  * Return value:
278  *      0
279  **/
280 static int cmm_thread(void *dummy)
281 {
282         unsigned long timeleft;
283         long __loaned_pages;
284
285         while (1) {
286                 timeleft = msleep_interruptible(delay * 1000);
287
288                 if (kthread_should_stop() || timeleft)
289                         break;
290
291                 if (mutex_trylock(&hotplug_mutex)) {
292                         if (hotplug_occurred) {
293                                 hotplug_occurred = 0;
294                                 mutex_unlock(&hotplug_mutex);
295                                 cmm_dbg("Hotplug operation has occurred, "
296                                                 "loaning activity suspended "
297                                                 "for %d seconds.\n",
298                                                 hotplug_delay);
299                                 timeleft = msleep_interruptible(hotplug_delay *
300                                                 1000);
301                                 if (kthread_should_stop() || timeleft)
302                                         break;
303                                 continue;
304                         }
305                         mutex_unlock(&hotplug_mutex);
306                 } else {
307                         cmm_dbg("Hotplug operation in progress, activity "
308                                         "suspended\n");
309                         continue;
310                 }
311
312                 cmm_get_mpp();
313
314                 __loaned_pages = atomic_long_read(&loaned_pages);
315                 if (loaned_pages_target > __loaned_pages) {
316                         if (cmm_alloc_pages(loaned_pages_target - __loaned_pages))
317                                 loaned_pages_target = __loaned_pages;
318                 } else if (loaned_pages_target < __loaned_pages)
319                         cmm_free_pages(__loaned_pages - loaned_pages_target);
320         }
321         return 0;
322 }
323
324 #define CMM_SHOW(name, format, args...)                 \
325         static ssize_t show_##name(struct device *dev,  \
326                                    struct device_attribute *attr,       \
327                                    char *buf)                   \
328         {                                                       \
329                 return sprintf(buf, format, ##args);            \
330         }                                                       \
331         static DEVICE_ATTR(name, 0444, show_##name, NULL)
332
333 CMM_SHOW(loaned_kb, "%lu\n", PAGES2KB(atomic_long_read(&loaned_pages)));
334 CMM_SHOW(loaned_target_kb, "%lu\n", PAGES2KB(loaned_pages_target));
335
336 static ssize_t show_oom_pages(struct device *dev,
337                               struct device_attribute *attr, char *buf)
338 {
339         return sprintf(buf, "%lu\n", PAGES2KB(oom_freed_pages));
340 }
341
342 static ssize_t store_oom_pages(struct device *dev,
343                                struct device_attribute *attr,
344                                const char *buf, size_t count)
345 {
346         unsigned long val = simple_strtoul (buf, NULL, 10);
347
348         if (!capable(CAP_SYS_ADMIN))
349                 return -EPERM;
350         if (val != 0)
351                 return -EBADMSG;
352
353         oom_freed_pages = 0;
354         return count;
355 }
356
357 static DEVICE_ATTR(oom_freed_kb, 0644,
358                    show_oom_pages, store_oom_pages);
359
360 static struct device_attribute *cmm_attrs[] = {
361         &dev_attr_loaned_kb,
362         &dev_attr_loaned_target_kb,
363         &dev_attr_oom_freed_kb,
364 };
365
366 static struct bus_type cmm_subsys = {
367         .name = "cmm",
368         .dev_name = "cmm",
369 };
370
371 static void cmm_release_device(struct device *dev)
372 {
373 }
374
375 /**
376  * cmm_sysfs_register - Register with sysfs
377  *
378  * Return value:
379  *      0 on success / other on failure
380  **/
381 static int cmm_sysfs_register(struct device *dev)
382 {
383         int i, rc;
384
385         if ((rc = subsys_system_register(&cmm_subsys, NULL)))
386                 return rc;
387
388         dev->id = 0;
389         dev->bus = &cmm_subsys;
390         dev->release = cmm_release_device;
391
392         if ((rc = device_register(dev)))
393                 goto subsys_unregister;
394
395         for (i = 0; i < ARRAY_SIZE(cmm_attrs); i++) {
396                 if ((rc = device_create_file(dev, cmm_attrs[i])))
397                         goto fail;
398         }
399
400         return 0;
401
402 fail:
403         while (--i >= 0)
404                 device_remove_file(dev, cmm_attrs[i]);
405         device_unregister(dev);
406 subsys_unregister:
407         bus_unregister(&cmm_subsys);
408         return rc;
409 }
410
411 /**
412  * cmm_unregister_sysfs - Unregister from sysfs
413  *
414  **/
415 static void cmm_unregister_sysfs(struct device *dev)
416 {
417         int i;
418
419         for (i = 0; i < ARRAY_SIZE(cmm_attrs); i++)
420                 device_remove_file(dev, cmm_attrs[i]);
421         device_unregister(dev);
422         bus_unregister(&cmm_subsys);
423 }
424
425 /**
426  * cmm_reboot_notifier - Make sure pages are not still marked as "loaned"
427  *
428  **/
429 static int cmm_reboot_notifier(struct notifier_block *nb,
430                                unsigned long action, void *unused)
431 {
432         if (action == SYS_RESTART) {
433                 if (cmm_thread_ptr)
434                         kthread_stop(cmm_thread_ptr);
435                 cmm_thread_ptr = NULL;
436                 cmm_free_pages(atomic_long_read(&loaned_pages));
437         }
438         return NOTIFY_DONE;
439 }
440
441 static struct notifier_block cmm_reboot_nb = {
442         .notifier_call = cmm_reboot_notifier,
443 };
444
445 /**
446  * cmm_memory_cb - Handle memory hotplug notifier calls
447  * @self:       notifier block struct
448  * @action:     action to take
449  * @arg:        struct memory_notify data for handler
450  *
451  * Return value:
452  *      NOTIFY_OK or notifier error based on subfunction return value
453  *
454  **/
455 static int cmm_memory_cb(struct notifier_block *self,
456                         unsigned long action, void *arg)
457 {
458         int ret = 0;
459
460         switch (action) {
461         case MEM_GOING_OFFLINE:
462                 mutex_lock(&hotplug_mutex);
463                 hotplug_occurred = 1;
464                 break;
465         case MEM_OFFLINE:
466         case MEM_CANCEL_OFFLINE:
467                 mutex_unlock(&hotplug_mutex);
468                 cmm_dbg("Memory offline operation complete.\n");
469                 break;
470         case MEM_GOING_ONLINE:
471         case MEM_ONLINE:
472         case MEM_CANCEL_ONLINE:
473                 break;
474         }
475
476         return notifier_from_errno(ret);
477 }
478
479 static struct notifier_block cmm_mem_nb = {
480         .notifier_call = cmm_memory_cb,
481         .priority = CMM_MEM_HOTPLUG_PRI
482 };
483
484 #ifdef CONFIG_BALLOON_COMPACTION
485 static struct vfsmount *balloon_mnt;
486
487 static int cmm_init_fs_context(struct fs_context *fc)
488 {
489         return init_pseudo(fc, PPC_CMM_MAGIC) ? 0 : -ENOMEM;
490 }
491
492 static struct file_system_type balloon_fs = {
493         .name = "ppc-cmm",
494         .init_fs_context = cmm_init_fs_context,
495         .kill_sb = kill_anon_super,
496 };
497
498 static int cmm_migratepage(struct balloon_dev_info *b_dev_info,
499                            struct page *newpage, struct page *page,
500                            enum migrate_mode mode)
501 {
502         unsigned long flags;
503
504         /*
505          * loan/"inflate" the newpage first.
506          *
507          * We might race against the cmm_thread who might discover after our
508          * loan request that another page is to be unloaned. However, once
509          * the cmm_thread runs again later, this error will automatically
510          * be corrected.
511          */
512         if (plpar_page_set_loaned(newpage)) {
513                 /* Unlikely, but possible. Tell the caller not to retry now. */
514                 pr_err_ratelimited("%s: Cannot set page to loaned.", __func__);
515                 return -EBUSY;
516         }
517
518         /* balloon page list reference */
519         get_page(newpage);
520
521         spin_lock_irqsave(&b_dev_info->pages_lock, flags);
522         balloon_page_insert(b_dev_info, newpage);
523         balloon_page_delete(page);
524         b_dev_info->isolated_pages--;
525         spin_unlock_irqrestore(&b_dev_info->pages_lock, flags);
526
527         /*
528          * activate/"deflate" the old page. We ignore any errors just like the
529          * other callers.
530          */
531         plpar_page_set_active(page);
532
533         /* balloon page list reference */
534         put_page(page);
535
536         return MIGRATEPAGE_SUCCESS;
537 }
538
539 static int cmm_balloon_compaction_init(void)
540 {
541         int rc;
542
543         balloon_devinfo_init(&b_dev_info);
544         b_dev_info.migratepage = cmm_migratepage;
545
546         balloon_mnt = kern_mount(&balloon_fs);
547         if (IS_ERR(balloon_mnt)) {
548                 rc = PTR_ERR(balloon_mnt);
549                 balloon_mnt = NULL;
550                 return rc;
551         }
552
553         b_dev_info.inode = alloc_anon_inode(balloon_mnt->mnt_sb);
554         if (IS_ERR(b_dev_info.inode)) {
555                 rc = PTR_ERR(b_dev_info.inode);
556                 b_dev_info.inode = NULL;
557                 kern_unmount(balloon_mnt);
558                 balloon_mnt = NULL;
559                 return rc;
560         }
561
562         b_dev_info.inode->i_mapping->a_ops = &balloon_aops;
563         return 0;
564 }
565 static void cmm_balloon_compaction_deinit(void)
566 {
567         if (b_dev_info.inode)
568                 iput(b_dev_info.inode);
569         b_dev_info.inode = NULL;
570         kern_unmount(balloon_mnt);
571         balloon_mnt = NULL;
572 }
573 #else /* CONFIG_BALLOON_COMPACTION */
574 static int cmm_balloon_compaction_init(void)
575 {
576         return 0;
577 }
578
579 static void cmm_balloon_compaction_deinit(void)
580 {
581 }
582 #endif /* CONFIG_BALLOON_COMPACTION */
583
584 /**
585  * cmm_init - Module initialization
586  *
587  * Return value:
588  *      0 on success / other on failure
589  **/
590 static int cmm_init(void)
591 {
592         int rc;
593
594         if (!firmware_has_feature(FW_FEATURE_CMO))
595                 return -EOPNOTSUPP;
596
597         rc = cmm_balloon_compaction_init();
598         if (rc)
599                 return rc;
600
601         rc = register_oom_notifier(&cmm_oom_nb);
602         if (rc < 0)
603                 goto out_balloon_compaction;
604
605         if ((rc = register_reboot_notifier(&cmm_reboot_nb)))
606                 goto out_oom_notifier;
607
608         if ((rc = cmm_sysfs_register(&cmm_dev)))
609                 goto out_reboot_notifier;
610
611         rc = register_memory_notifier(&cmm_mem_nb);
612         if (rc)
613                 goto out_unregister_notifier;
614
615         if (cmm_disabled)
616                 return 0;
617
618         cmm_thread_ptr = kthread_run(cmm_thread, NULL, "cmmthread");
619         if (IS_ERR(cmm_thread_ptr)) {
620                 rc = PTR_ERR(cmm_thread_ptr);
621                 goto out_unregister_notifier;
622         }
623
624         return 0;
625 out_unregister_notifier:
626         unregister_memory_notifier(&cmm_mem_nb);
627         cmm_unregister_sysfs(&cmm_dev);
628 out_reboot_notifier:
629         unregister_reboot_notifier(&cmm_reboot_nb);
630 out_oom_notifier:
631         unregister_oom_notifier(&cmm_oom_nb);
632 out_balloon_compaction:
633         cmm_balloon_compaction_deinit();
634         return rc;
635 }
636
637 /**
638  * cmm_exit - Module exit
639  *
640  * Return value:
641  *      nothing
642  **/
643 static void cmm_exit(void)
644 {
645         if (cmm_thread_ptr)
646                 kthread_stop(cmm_thread_ptr);
647         unregister_oom_notifier(&cmm_oom_nb);
648         unregister_reboot_notifier(&cmm_reboot_nb);
649         unregister_memory_notifier(&cmm_mem_nb);
650         cmm_free_pages(atomic_long_read(&loaned_pages));
651         cmm_unregister_sysfs(&cmm_dev);
652         cmm_balloon_compaction_deinit();
653 }
654
655 /**
656  * cmm_set_disable - Disable/Enable CMM
657  *
658  * Return value:
659  *      0 on success / other on failure
660  **/
661 static int cmm_set_disable(const char *val, const struct kernel_param *kp)
662 {
663         int disable = simple_strtoul(val, NULL, 10);
664
665         if (disable != 0 && disable != 1)
666                 return -EINVAL;
667
668         if (disable && !cmm_disabled) {
669                 if (cmm_thread_ptr)
670                         kthread_stop(cmm_thread_ptr);
671                 cmm_thread_ptr = NULL;
672                 cmm_free_pages(atomic_long_read(&loaned_pages));
673         } else if (!disable && cmm_disabled) {
674                 cmm_thread_ptr = kthread_run(cmm_thread, NULL, "cmmthread");
675                 if (IS_ERR(cmm_thread_ptr))
676                         return PTR_ERR(cmm_thread_ptr);
677         }
678
679         cmm_disabled = disable;
680         return 0;
681 }
682
683 module_param_call(disable, cmm_set_disable, param_get_uint,
684                   &cmm_disabled, 0644);
685 MODULE_PARM_DESC(disable, "Disable CMM. Set to 1 to disable. "
686                  "[Default=" __stringify(CMM_DISABLE) "]");
687
688 module_init(cmm_init);
689 module_exit(cmm_exit);