cd23c081924deed7774f98407748becf817c21b0
[sfrench/cifs-2.6.git] / mm / memory_hotplug.c
1 /*
2  *  linux/mm/memory_hotplug.c
3  *
4  *  Copyright (C)
5  */
6
7 #include <linux/stddef.h>
8 #include <linux/mm.h>
9 #include <linux/sched/signal.h>
10 #include <linux/swap.h>
11 #include <linux/interrupt.h>
12 #include <linux/pagemap.h>
13 #include <linux/compiler.h>
14 #include <linux/export.h>
15 #include <linux/pagevec.h>
16 #include <linux/writeback.h>
17 #include <linux/slab.h>
18 #include <linux/sysctl.h>
19 #include <linux/cpu.h>
20 #include <linux/memory.h>
21 #include <linux/memremap.h>
22 #include <linux/memory_hotplug.h>
23 #include <linux/highmem.h>
24 #include <linux/vmalloc.h>
25 #include <linux/ioport.h>
26 #include <linux/delay.h>
27 #include <linux/migrate.h>
28 #include <linux/page-isolation.h>
29 #include <linux/pfn.h>
30 #include <linux/suspend.h>
31 #include <linux/mm_inline.h>
32 #include <linux/firmware-map.h>
33 #include <linux/stop_machine.h>
34 #include <linux/hugetlb.h>
35 #include <linux/memblock.h>
36 #include <linux/compaction.h>
37 #include <linux/rmap.h>
38
39 #include <asm/tlbflush.h>
40
41 #include "internal.h"
42
43 /*
44  * online_page_callback contains pointer to current page onlining function.
45  * Initially it is generic_online_page(). If it is required it could be
46  * changed by calling set_online_page_callback() for callback registration
47  * and restore_online_page_callback() for generic callback restore.
48  */
49
50 static void generic_online_page(struct page *page, unsigned int order);
51
52 static online_page_callback_t online_page_callback = generic_online_page;
53 static DEFINE_MUTEX(online_page_callback_lock);
54
55 DEFINE_STATIC_PERCPU_RWSEM(mem_hotplug_lock);
56
57 void get_online_mems(void)
58 {
59         percpu_down_read(&mem_hotplug_lock);
60 }
61
62 void put_online_mems(void)
63 {
64         percpu_up_read(&mem_hotplug_lock);
65 }
66
67 bool movable_node_enabled = false;
68
69 #ifndef CONFIG_MEMORY_HOTPLUG_DEFAULT_ONLINE
70 bool memhp_auto_online;
71 #else
72 bool memhp_auto_online = true;
73 #endif
74 EXPORT_SYMBOL_GPL(memhp_auto_online);
75
76 static int __init setup_memhp_default_state(char *str)
77 {
78         if (!strcmp(str, "online"))
79                 memhp_auto_online = true;
80         else if (!strcmp(str, "offline"))
81                 memhp_auto_online = false;
82
83         return 1;
84 }
85 __setup("memhp_default_state=", setup_memhp_default_state);
86
87 void mem_hotplug_begin(void)
88 {
89         cpus_read_lock();
90         percpu_down_write(&mem_hotplug_lock);
91 }
92
93 void mem_hotplug_done(void)
94 {
95         percpu_up_write(&mem_hotplug_lock);
96         cpus_read_unlock();
97 }
98
99 u64 max_mem_size = U64_MAX;
100
101 /* add this memory to iomem resource */
102 static struct resource *register_memory_resource(u64 start, u64 size)
103 {
104         struct resource *res, *conflict;
105
106         if (start + size > max_mem_size)
107                 return ERR_PTR(-E2BIG);
108
109         res = kzalloc(sizeof(struct resource), GFP_KERNEL);
110         if (!res)
111                 return ERR_PTR(-ENOMEM);
112
113         res->name = "System RAM";
114         res->start = start;
115         res->end = start + size - 1;
116         res->flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
117         conflict =  request_resource_conflict(&iomem_resource, res);
118         if (conflict) {
119                 if (conflict->desc == IORES_DESC_DEVICE_PRIVATE_MEMORY) {
120                         pr_debug("Device unaddressable memory block "
121                                  "memory hotplug at %#010llx !\n",
122                                  (unsigned long long)start);
123                 }
124                 pr_debug("System RAM resource %pR cannot be added\n", res);
125                 kfree(res);
126                 return ERR_PTR(-EEXIST);
127         }
128         return res;
129 }
130
131 static void release_memory_resource(struct resource *res)
132 {
133         if (!res)
134                 return;
135         release_resource(res);
136         kfree(res);
137         return;
138 }
139
140 #ifdef CONFIG_MEMORY_HOTPLUG_SPARSE
141 void get_page_bootmem(unsigned long info,  struct page *page,
142                       unsigned long type)
143 {
144         page->freelist = (void *)type;
145         SetPagePrivate(page);
146         set_page_private(page, info);
147         page_ref_inc(page);
148 }
149
150 void put_page_bootmem(struct page *page)
151 {
152         unsigned long type;
153
154         type = (unsigned long) page->freelist;
155         BUG_ON(type < MEMORY_HOTPLUG_MIN_BOOTMEM_TYPE ||
156                type > MEMORY_HOTPLUG_MAX_BOOTMEM_TYPE);
157
158         if (page_ref_dec_return(page) == 1) {
159                 page->freelist = NULL;
160                 ClearPagePrivate(page);
161                 set_page_private(page, 0);
162                 INIT_LIST_HEAD(&page->lru);
163                 free_reserved_page(page);
164         }
165 }
166
167 #ifdef CONFIG_HAVE_BOOTMEM_INFO_NODE
168 #ifndef CONFIG_SPARSEMEM_VMEMMAP
169 static void register_page_bootmem_info_section(unsigned long start_pfn)
170 {
171         unsigned long *usemap, mapsize, section_nr, i;
172         struct mem_section *ms;
173         struct page *page, *memmap;
174
175         section_nr = pfn_to_section_nr(start_pfn);
176         ms = __nr_to_section(section_nr);
177
178         /* Get section's memmap address */
179         memmap = sparse_decode_mem_map(ms->section_mem_map, section_nr);
180
181         /*
182          * Get page for the memmap's phys address
183          * XXX: need more consideration for sparse_vmemmap...
184          */
185         page = virt_to_page(memmap);
186         mapsize = sizeof(struct page) * PAGES_PER_SECTION;
187         mapsize = PAGE_ALIGN(mapsize) >> PAGE_SHIFT;
188
189         /* remember memmap's page */
190         for (i = 0; i < mapsize; i++, page++)
191                 get_page_bootmem(section_nr, page, SECTION_INFO);
192
193         usemap = ms->pageblock_flags;
194         page = virt_to_page(usemap);
195
196         mapsize = PAGE_ALIGN(usemap_size()) >> PAGE_SHIFT;
197
198         for (i = 0; i < mapsize; i++, page++)
199                 get_page_bootmem(section_nr, page, MIX_SECTION_INFO);
200
201 }
202 #else /* CONFIG_SPARSEMEM_VMEMMAP */
203 static void register_page_bootmem_info_section(unsigned long start_pfn)
204 {
205         unsigned long *usemap, mapsize, section_nr, i;
206         struct mem_section *ms;
207         struct page *page, *memmap;
208
209         section_nr = pfn_to_section_nr(start_pfn);
210         ms = __nr_to_section(section_nr);
211
212         memmap = sparse_decode_mem_map(ms->section_mem_map, section_nr);
213
214         register_page_bootmem_memmap(section_nr, memmap, PAGES_PER_SECTION);
215
216         usemap = ms->pageblock_flags;
217         page = virt_to_page(usemap);
218
219         mapsize = PAGE_ALIGN(usemap_size()) >> PAGE_SHIFT;
220
221         for (i = 0; i < mapsize; i++, page++)
222                 get_page_bootmem(section_nr, page, MIX_SECTION_INFO);
223 }
224 #endif /* !CONFIG_SPARSEMEM_VMEMMAP */
225
226 void __init register_page_bootmem_info_node(struct pglist_data *pgdat)
227 {
228         unsigned long i, pfn, end_pfn, nr_pages;
229         int node = pgdat->node_id;
230         struct page *page;
231
232         nr_pages = PAGE_ALIGN(sizeof(struct pglist_data)) >> PAGE_SHIFT;
233         page = virt_to_page(pgdat);
234
235         for (i = 0; i < nr_pages; i++, page++)
236                 get_page_bootmem(node, page, NODE_INFO);
237
238         pfn = pgdat->node_start_pfn;
239         end_pfn = pgdat_end_pfn(pgdat);
240
241         /* register section info */
242         for (; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
243                 /*
244                  * Some platforms can assign the same pfn to multiple nodes - on
245                  * node0 as well as nodeN.  To avoid registering a pfn against
246                  * multiple nodes we check that this pfn does not already
247                  * reside in some other nodes.
248                  */
249                 if (pfn_valid(pfn) && (early_pfn_to_nid(pfn) == node))
250                         register_page_bootmem_info_section(pfn);
251         }
252 }
253 #endif /* CONFIG_HAVE_BOOTMEM_INFO_NODE */
254
255 static int __meminit __add_section(int nid, unsigned long phys_start_pfn,
256                 struct vmem_altmap *altmap, bool want_memblock)
257 {
258         int ret;
259
260         if (pfn_valid(phys_start_pfn))
261                 return -EEXIST;
262
263         ret = sparse_add_one_section(nid, phys_start_pfn, altmap);
264         if (ret < 0)
265                 return ret;
266
267         if (!want_memblock)
268                 return 0;
269
270         return hotplug_memory_register(nid, __pfn_to_section(phys_start_pfn));
271 }
272
273 /*
274  * Reasonably generic function for adding memory.  It is
275  * expected that archs that support memory hotplug will
276  * call this function after deciding the zone to which to
277  * add the new pages.
278  */
279 int __ref __add_pages(int nid, unsigned long phys_start_pfn,
280                 unsigned long nr_pages, struct vmem_altmap *altmap,
281                 bool want_memblock)
282 {
283         unsigned long i;
284         int err = 0;
285         int start_sec, end_sec;
286
287         /* during initialize mem_map, align hot-added range to section */
288         start_sec = pfn_to_section_nr(phys_start_pfn);
289         end_sec = pfn_to_section_nr(phys_start_pfn + nr_pages - 1);
290
291         if (altmap) {
292                 /*
293                  * Validate altmap is within bounds of the total request
294                  */
295                 if (altmap->base_pfn != phys_start_pfn
296                                 || vmem_altmap_offset(altmap) > nr_pages) {
297                         pr_warn_once("memory add fail, invalid altmap\n");
298                         err = -EINVAL;
299                         goto out;
300                 }
301                 altmap->alloc = 0;
302         }
303
304         for (i = start_sec; i <= end_sec; i++) {
305                 err = __add_section(nid, section_nr_to_pfn(i), altmap,
306                                 want_memblock);
307
308                 /*
309                  * EEXIST is finally dealt with by ioresource collision
310                  * check. see add_memory() => register_memory_resource()
311                  * Warning will be printed if there is collision.
312                  */
313                 if (err && (err != -EEXIST))
314                         break;
315                 err = 0;
316                 cond_resched();
317         }
318         vmemmap_populate_print_last();
319 out:
320         return err;
321 }
322
323 #ifdef CONFIG_MEMORY_HOTREMOVE
324 /* find the smallest valid pfn in the range [start_pfn, end_pfn) */
325 static unsigned long find_smallest_section_pfn(int nid, struct zone *zone,
326                                      unsigned long start_pfn,
327                                      unsigned long end_pfn)
328 {
329         struct mem_section *ms;
330
331         for (; start_pfn < end_pfn; start_pfn += PAGES_PER_SECTION) {
332                 ms = __pfn_to_section(start_pfn);
333
334                 if (unlikely(!valid_section(ms)))
335                         continue;
336
337                 if (unlikely(pfn_to_nid(start_pfn) != nid))
338                         continue;
339
340                 if (zone && zone != page_zone(pfn_to_page(start_pfn)))
341                         continue;
342
343                 return start_pfn;
344         }
345
346         return 0;
347 }
348
349 /* find the biggest valid pfn in the range [start_pfn, end_pfn). */
350 static unsigned long find_biggest_section_pfn(int nid, struct zone *zone,
351                                     unsigned long start_pfn,
352                                     unsigned long end_pfn)
353 {
354         struct mem_section *ms;
355         unsigned long pfn;
356
357         /* pfn is the end pfn of a memory section. */
358         pfn = end_pfn - 1;
359         for (; pfn >= start_pfn; pfn -= PAGES_PER_SECTION) {
360                 ms = __pfn_to_section(pfn);
361
362                 if (unlikely(!valid_section(ms)))
363                         continue;
364
365                 if (unlikely(pfn_to_nid(pfn) != nid))
366                         continue;
367
368                 if (zone && zone != page_zone(pfn_to_page(pfn)))
369                         continue;
370
371                 return pfn;
372         }
373
374         return 0;
375 }
376
377 static void shrink_zone_span(struct zone *zone, unsigned long start_pfn,
378                              unsigned long end_pfn)
379 {
380         unsigned long zone_start_pfn = zone->zone_start_pfn;
381         unsigned long z = zone_end_pfn(zone); /* zone_end_pfn namespace clash */
382         unsigned long zone_end_pfn = z;
383         unsigned long pfn;
384         struct mem_section *ms;
385         int nid = zone_to_nid(zone);
386
387         zone_span_writelock(zone);
388         if (zone_start_pfn == start_pfn) {
389                 /*
390                  * If the section is smallest section in the zone, it need
391                  * shrink zone->zone_start_pfn and zone->zone_spanned_pages.
392                  * In this case, we find second smallest valid mem_section
393                  * for shrinking zone.
394                  */
395                 pfn = find_smallest_section_pfn(nid, zone, end_pfn,
396                                                 zone_end_pfn);
397                 if (pfn) {
398                         zone->zone_start_pfn = pfn;
399                         zone->spanned_pages = zone_end_pfn - pfn;
400                 }
401         } else if (zone_end_pfn == end_pfn) {
402                 /*
403                  * If the section is biggest section in the zone, it need
404                  * shrink zone->spanned_pages.
405                  * In this case, we find second biggest valid mem_section for
406                  * shrinking zone.
407                  */
408                 pfn = find_biggest_section_pfn(nid, zone, zone_start_pfn,
409                                                start_pfn);
410                 if (pfn)
411                         zone->spanned_pages = pfn - zone_start_pfn + 1;
412         }
413
414         /*
415          * The section is not biggest or smallest mem_section in the zone, it
416          * only creates a hole in the zone. So in this case, we need not
417          * change the zone. But perhaps, the zone has only hole data. Thus
418          * it check the zone has only hole or not.
419          */
420         pfn = zone_start_pfn;
421         for (; pfn < zone_end_pfn; pfn += PAGES_PER_SECTION) {
422                 ms = __pfn_to_section(pfn);
423
424                 if (unlikely(!valid_section(ms)))
425                         continue;
426
427                 if (page_zone(pfn_to_page(pfn)) != zone)
428                         continue;
429
430                  /* If the section is current section, it continues the loop */
431                 if (start_pfn == pfn)
432                         continue;
433
434                 /* If we find valid section, we have nothing to do */
435                 zone_span_writeunlock(zone);
436                 return;
437         }
438
439         /* The zone has no valid section */
440         zone->zone_start_pfn = 0;
441         zone->spanned_pages = 0;
442         zone_span_writeunlock(zone);
443 }
444
445 static void shrink_pgdat_span(struct pglist_data *pgdat,
446                               unsigned long start_pfn, unsigned long end_pfn)
447 {
448         unsigned long pgdat_start_pfn = pgdat->node_start_pfn;
449         unsigned long p = pgdat_end_pfn(pgdat); /* pgdat_end_pfn namespace clash */
450         unsigned long pgdat_end_pfn = p;
451         unsigned long pfn;
452         struct mem_section *ms;
453         int nid = pgdat->node_id;
454
455         if (pgdat_start_pfn == start_pfn) {
456                 /*
457                  * If the section is smallest section in the pgdat, it need
458                  * shrink pgdat->node_start_pfn and pgdat->node_spanned_pages.
459                  * In this case, we find second smallest valid mem_section
460                  * for shrinking zone.
461                  */
462                 pfn = find_smallest_section_pfn(nid, NULL, end_pfn,
463                                                 pgdat_end_pfn);
464                 if (pfn) {
465                         pgdat->node_start_pfn = pfn;
466                         pgdat->node_spanned_pages = pgdat_end_pfn - pfn;
467                 }
468         } else if (pgdat_end_pfn == end_pfn) {
469                 /*
470                  * If the section is biggest section in the pgdat, it need
471                  * shrink pgdat->node_spanned_pages.
472                  * In this case, we find second biggest valid mem_section for
473                  * shrinking zone.
474                  */
475                 pfn = find_biggest_section_pfn(nid, NULL, pgdat_start_pfn,
476                                                start_pfn);
477                 if (pfn)
478                         pgdat->node_spanned_pages = pfn - pgdat_start_pfn + 1;
479         }
480
481         /*
482          * If the section is not biggest or smallest mem_section in the pgdat,
483          * it only creates a hole in the pgdat. So in this case, we need not
484          * change the pgdat.
485          * But perhaps, the pgdat has only hole data. Thus it check the pgdat
486          * has only hole or not.
487          */
488         pfn = pgdat_start_pfn;
489         for (; pfn < pgdat_end_pfn; pfn += PAGES_PER_SECTION) {
490                 ms = __pfn_to_section(pfn);
491
492                 if (unlikely(!valid_section(ms)))
493                         continue;
494
495                 if (pfn_to_nid(pfn) != nid)
496                         continue;
497
498                  /* If the section is current section, it continues the loop */
499                 if (start_pfn == pfn)
500                         continue;
501
502                 /* If we find valid section, we have nothing to do */
503                 return;
504         }
505
506         /* The pgdat has no valid section */
507         pgdat->node_start_pfn = 0;
508         pgdat->node_spanned_pages = 0;
509 }
510
511 static void __remove_zone(struct zone *zone, unsigned long start_pfn)
512 {
513         struct pglist_data *pgdat = zone->zone_pgdat;
514         int nr_pages = PAGES_PER_SECTION;
515         unsigned long flags;
516
517         pgdat_resize_lock(zone->zone_pgdat, &flags);
518         shrink_zone_span(zone, start_pfn, start_pfn + nr_pages);
519         shrink_pgdat_span(pgdat, start_pfn, start_pfn + nr_pages);
520         pgdat_resize_unlock(zone->zone_pgdat, &flags);
521 }
522
523 static int __remove_section(struct zone *zone, struct mem_section *ms,
524                 unsigned long map_offset, struct vmem_altmap *altmap)
525 {
526         unsigned long start_pfn;
527         int scn_nr;
528         int ret = -EINVAL;
529
530         if (!valid_section(ms))
531                 return ret;
532
533         ret = unregister_memory_section(ms);
534         if (ret)
535                 return ret;
536
537         scn_nr = __section_nr(ms);
538         start_pfn = section_nr_to_pfn((unsigned long)scn_nr);
539         __remove_zone(zone, start_pfn);
540
541         sparse_remove_one_section(zone, ms, map_offset, altmap);
542         return 0;
543 }
544
545 /**
546  * __remove_pages() - remove sections of pages from a zone
547  * @zone: zone from which pages need to be removed
548  * @phys_start_pfn: starting pageframe (must be aligned to start of a section)
549  * @nr_pages: number of pages to remove (must be multiple of section size)
550  * @altmap: alternative device page map or %NULL if default memmap is used
551  *
552  * Generic helper function to remove section mappings and sysfs entries
553  * for the section of the memory we are removing. Caller needs to make
554  * sure that pages are marked reserved and zones are adjust properly by
555  * calling offline_pages().
556  */
557 int __remove_pages(struct zone *zone, unsigned long phys_start_pfn,
558                  unsigned long nr_pages, struct vmem_altmap *altmap)
559 {
560         unsigned long i;
561         unsigned long map_offset = 0;
562         int sections_to_remove, ret = 0;
563
564         /* In the ZONE_DEVICE case device driver owns the memory region */
565         if (is_dev_zone(zone)) {
566                 if (altmap)
567                         map_offset = vmem_altmap_offset(altmap);
568         } else {
569                 resource_size_t start, size;
570
571                 start = phys_start_pfn << PAGE_SHIFT;
572                 size = nr_pages * PAGE_SIZE;
573
574                 ret = release_mem_region_adjustable(&iomem_resource, start,
575                                         size);
576                 if (ret) {
577                         resource_size_t endres = start + size - 1;
578
579                         pr_warn("Unable to release resource <%pa-%pa> (%d)\n",
580                                         &start, &endres, ret);
581                 }
582         }
583
584         clear_zone_contiguous(zone);
585
586         /*
587          * We can only remove entire sections
588          */
589         BUG_ON(phys_start_pfn & ~PAGE_SECTION_MASK);
590         BUG_ON(nr_pages % PAGES_PER_SECTION);
591
592         sections_to_remove = nr_pages / PAGES_PER_SECTION;
593         for (i = 0; i < sections_to_remove; i++) {
594                 unsigned long pfn = phys_start_pfn + i*PAGES_PER_SECTION;
595
596                 cond_resched();
597                 ret = __remove_section(zone, __pfn_to_section(pfn), map_offset,
598                                 altmap);
599                 map_offset = 0;
600                 if (ret)
601                         break;
602         }
603
604         set_zone_contiguous(zone);
605
606         return ret;
607 }
608 #endif /* CONFIG_MEMORY_HOTREMOVE */
609
610 int set_online_page_callback(online_page_callback_t callback)
611 {
612         int rc = -EINVAL;
613
614         get_online_mems();
615         mutex_lock(&online_page_callback_lock);
616
617         if (online_page_callback == generic_online_page) {
618                 online_page_callback = callback;
619                 rc = 0;
620         }
621
622         mutex_unlock(&online_page_callback_lock);
623         put_online_mems();
624
625         return rc;
626 }
627 EXPORT_SYMBOL_GPL(set_online_page_callback);
628
629 int restore_online_page_callback(online_page_callback_t callback)
630 {
631         int rc = -EINVAL;
632
633         get_online_mems();
634         mutex_lock(&online_page_callback_lock);
635
636         if (online_page_callback == callback) {
637                 online_page_callback = generic_online_page;
638                 rc = 0;
639         }
640
641         mutex_unlock(&online_page_callback_lock);
642         put_online_mems();
643
644         return rc;
645 }
646 EXPORT_SYMBOL_GPL(restore_online_page_callback);
647
648 void __online_page_set_limits(struct page *page)
649 {
650 }
651 EXPORT_SYMBOL_GPL(__online_page_set_limits);
652
653 void __online_page_increment_counters(struct page *page)
654 {
655         adjust_managed_page_count(page, 1);
656 }
657 EXPORT_SYMBOL_GPL(__online_page_increment_counters);
658
659 void __online_page_free(struct page *page)
660 {
661         __free_reserved_page(page);
662 }
663 EXPORT_SYMBOL_GPL(__online_page_free);
664
665 static void generic_online_page(struct page *page, unsigned int order)
666 {
667         kernel_map_pages(page, 1 << order, 1);
668         __free_pages_core(page, order);
669         totalram_pages_add(1UL << order);
670 #ifdef CONFIG_HIGHMEM
671         if (PageHighMem(page))
672                 totalhigh_pages_add(1UL << order);
673 #endif
674 }
675
676 static int online_pages_blocks(unsigned long start, unsigned long nr_pages)
677 {
678         unsigned long end = start + nr_pages;
679         int order, onlined_pages = 0;
680
681         while (start < end) {
682                 order = min(MAX_ORDER - 1,
683                         get_order(PFN_PHYS(end) - PFN_PHYS(start)));
684                 (*online_page_callback)(pfn_to_page(start), order);
685
686                 onlined_pages += (1UL << order);
687                 start += (1UL << order);
688         }
689         return onlined_pages;
690 }
691
692 static int online_pages_range(unsigned long start_pfn, unsigned long nr_pages,
693                         void *arg)
694 {
695         unsigned long onlined_pages = *(unsigned long *)arg;
696
697         if (PageReserved(pfn_to_page(start_pfn)))
698                 onlined_pages += online_pages_blocks(start_pfn, nr_pages);
699
700         online_mem_sections(start_pfn, start_pfn + nr_pages);
701
702         *(unsigned long *)arg = onlined_pages;
703         return 0;
704 }
705
706 /* check which state of node_states will be changed when online memory */
707 static void node_states_check_changes_online(unsigned long nr_pages,
708         struct zone *zone, struct memory_notify *arg)
709 {
710         int nid = zone_to_nid(zone);
711
712         arg->status_change_nid = NUMA_NO_NODE;
713         arg->status_change_nid_normal = NUMA_NO_NODE;
714         arg->status_change_nid_high = NUMA_NO_NODE;
715
716         if (!node_state(nid, N_MEMORY))
717                 arg->status_change_nid = nid;
718         if (zone_idx(zone) <= ZONE_NORMAL && !node_state(nid, N_NORMAL_MEMORY))
719                 arg->status_change_nid_normal = nid;
720 #ifdef CONFIG_HIGHMEM
721         if (zone_idx(zone) <= N_HIGH_MEMORY && !node_state(nid, N_HIGH_MEMORY))
722                 arg->status_change_nid_high = nid;
723 #endif
724 }
725
726 static void node_states_set_node(int node, struct memory_notify *arg)
727 {
728         if (arg->status_change_nid_normal >= 0)
729                 node_set_state(node, N_NORMAL_MEMORY);
730
731         if (arg->status_change_nid_high >= 0)
732                 node_set_state(node, N_HIGH_MEMORY);
733
734         if (arg->status_change_nid >= 0)
735                 node_set_state(node, N_MEMORY);
736 }
737
738 static void __meminit resize_zone_range(struct zone *zone, unsigned long start_pfn,
739                 unsigned long nr_pages)
740 {
741         unsigned long old_end_pfn = zone_end_pfn(zone);
742
743         if (zone_is_empty(zone) || start_pfn < zone->zone_start_pfn)
744                 zone->zone_start_pfn = start_pfn;
745
746         zone->spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - zone->zone_start_pfn;
747 }
748
749 static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned long start_pfn,
750                                      unsigned long nr_pages)
751 {
752         unsigned long old_end_pfn = pgdat_end_pfn(pgdat);
753
754         if (!pgdat->node_spanned_pages || start_pfn < pgdat->node_start_pfn)
755                 pgdat->node_start_pfn = start_pfn;
756
757         pgdat->node_spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - pgdat->node_start_pfn;
758 }
759
760 void __ref move_pfn_range_to_zone(struct zone *zone, unsigned long start_pfn,
761                 unsigned long nr_pages, struct vmem_altmap *altmap)
762 {
763         struct pglist_data *pgdat = zone->zone_pgdat;
764         int nid = pgdat->node_id;
765         unsigned long flags;
766
767         clear_zone_contiguous(zone);
768
769         /* TODO Huh pgdat is irqsave while zone is not. It used to be like that before */
770         pgdat_resize_lock(pgdat, &flags);
771         zone_span_writelock(zone);
772         if (zone_is_empty(zone))
773                 init_currently_empty_zone(zone, start_pfn, nr_pages);
774         resize_zone_range(zone, start_pfn, nr_pages);
775         zone_span_writeunlock(zone);
776         resize_pgdat_range(pgdat, start_pfn, nr_pages);
777         pgdat_resize_unlock(pgdat, &flags);
778
779         /*
780          * TODO now we have a visible range of pages which are not associated
781          * with their zone properly. Not nice but set_pfnblock_flags_mask
782          * expects the zone spans the pfn range. All the pages in the range
783          * are reserved so nobody should be touching them so we should be safe
784          */
785         memmap_init_zone(nr_pages, nid, zone_idx(zone), start_pfn,
786                         MEMMAP_HOTPLUG, altmap);
787
788         set_zone_contiguous(zone);
789 }
790
791 /*
792  * Returns a default kernel memory zone for the given pfn range.
793  * If no kernel zone covers this pfn range it will automatically go
794  * to the ZONE_NORMAL.
795  */
796 static struct zone *default_kernel_zone_for_pfn(int nid, unsigned long start_pfn,
797                 unsigned long nr_pages)
798 {
799         struct pglist_data *pgdat = NODE_DATA(nid);
800         int zid;
801
802         for (zid = 0; zid <= ZONE_NORMAL; zid++) {
803                 struct zone *zone = &pgdat->node_zones[zid];
804
805                 if (zone_intersects(zone, start_pfn, nr_pages))
806                         return zone;
807         }
808
809         return &pgdat->node_zones[ZONE_NORMAL];
810 }
811
812 static inline struct zone *default_zone_for_pfn(int nid, unsigned long start_pfn,
813                 unsigned long nr_pages)
814 {
815         struct zone *kernel_zone = default_kernel_zone_for_pfn(nid, start_pfn,
816                         nr_pages);
817         struct zone *movable_zone = &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
818         bool in_kernel = zone_intersects(kernel_zone, start_pfn, nr_pages);
819         bool in_movable = zone_intersects(movable_zone, start_pfn, nr_pages);
820
821         /*
822          * We inherit the existing zone in a simple case where zones do not
823          * overlap in the given range
824          */
825         if (in_kernel ^ in_movable)
826                 return (in_kernel) ? kernel_zone : movable_zone;
827
828         /*
829          * If the range doesn't belong to any zone or two zones overlap in the
830          * given range then we use movable zone only if movable_node is
831          * enabled because we always online to a kernel zone by default.
832          */
833         return movable_node_enabled ? movable_zone : kernel_zone;
834 }
835
836 struct zone * zone_for_pfn_range(int online_type, int nid, unsigned start_pfn,
837                 unsigned long nr_pages)
838 {
839         if (online_type == MMOP_ONLINE_KERNEL)
840                 return default_kernel_zone_for_pfn(nid, start_pfn, nr_pages);
841
842         if (online_type == MMOP_ONLINE_MOVABLE)
843                 return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
844
845         return default_zone_for_pfn(nid, start_pfn, nr_pages);
846 }
847
848 /*
849  * Associates the given pfn range with the given node and the zone appropriate
850  * for the given online type.
851  */
852 static struct zone * __meminit move_pfn_range(int online_type, int nid,
853                 unsigned long start_pfn, unsigned long nr_pages)
854 {
855         struct zone *zone;
856
857         zone = zone_for_pfn_range(online_type, nid, start_pfn, nr_pages);
858         move_pfn_range_to_zone(zone, start_pfn, nr_pages, NULL);
859         return zone;
860 }
861
862 int __ref online_pages(unsigned long pfn, unsigned long nr_pages, int online_type)
863 {
864         unsigned long flags;
865         unsigned long onlined_pages = 0;
866         struct zone *zone;
867         int need_zonelists_rebuild = 0;
868         int nid;
869         int ret;
870         struct memory_notify arg;
871         struct memory_block *mem;
872
873         mem_hotplug_begin();
874
875         /*
876          * We can't use pfn_to_nid() because nid might be stored in struct page
877          * which is not yet initialized. Instead, we find nid from memory block.
878          */
879         mem = find_memory_block(__pfn_to_section(pfn));
880         nid = mem->nid;
881
882         /* associate pfn range with the zone */
883         zone = move_pfn_range(online_type, nid, pfn, nr_pages);
884
885         arg.start_pfn = pfn;
886         arg.nr_pages = nr_pages;
887         node_states_check_changes_online(nr_pages, zone, &arg);
888
889         ret = memory_notify(MEM_GOING_ONLINE, &arg);
890         ret = notifier_to_errno(ret);
891         if (ret)
892                 goto failed_addition;
893
894         /*
895          * If this zone is not populated, then it is not in zonelist.
896          * This means the page allocator ignores this zone.
897          * So, zonelist must be updated after online.
898          */
899         if (!populated_zone(zone)) {
900                 need_zonelists_rebuild = 1;
901                 setup_zone_pageset(zone);
902         }
903
904         ret = walk_system_ram_range(pfn, nr_pages, &onlined_pages,
905                 online_pages_range);
906         if (ret) {
907                 if (need_zonelists_rebuild)
908                         zone_pcp_reset(zone);
909                 goto failed_addition;
910         }
911
912         zone->present_pages += onlined_pages;
913
914         pgdat_resize_lock(zone->zone_pgdat, &flags);
915         zone->zone_pgdat->node_present_pages += onlined_pages;
916         pgdat_resize_unlock(zone->zone_pgdat, &flags);
917
918         if (onlined_pages) {
919                 node_states_set_node(nid, &arg);
920                 if (need_zonelists_rebuild)
921                         build_all_zonelists(NULL);
922                 else
923                         zone_pcp_update(zone);
924         }
925
926         init_per_zone_wmark_min();
927
928         if (onlined_pages) {
929                 kswapd_run(nid);
930                 kcompactd_run(nid);
931         }
932
933         vm_total_pages = nr_free_pagecache_pages();
934
935         writeback_set_ratelimit();
936
937         if (onlined_pages)
938                 memory_notify(MEM_ONLINE, &arg);
939         mem_hotplug_done();
940         return 0;
941
942 failed_addition:
943         pr_debug("online_pages [mem %#010llx-%#010llx] failed\n",
944                  (unsigned long long) pfn << PAGE_SHIFT,
945                  (((unsigned long long) pfn + nr_pages) << PAGE_SHIFT) - 1);
946         memory_notify(MEM_CANCEL_ONLINE, &arg);
947         mem_hotplug_done();
948         return ret;
949 }
950 #endif /* CONFIG_MEMORY_HOTPLUG_SPARSE */
951
952 static void reset_node_present_pages(pg_data_t *pgdat)
953 {
954         struct zone *z;
955
956         for (z = pgdat->node_zones; z < pgdat->node_zones + MAX_NR_ZONES; z++)
957                 z->present_pages = 0;
958
959         pgdat->node_present_pages = 0;
960 }
961
962 /* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
963 static pg_data_t __ref *hotadd_new_pgdat(int nid, u64 start)
964 {
965         struct pglist_data *pgdat;
966         unsigned long start_pfn = PFN_DOWN(start);
967
968         pgdat = NODE_DATA(nid);
969         if (!pgdat) {
970                 pgdat = arch_alloc_nodedata(nid);
971                 if (!pgdat)
972                         return NULL;
973
974                 arch_refresh_nodedata(nid, pgdat);
975         } else {
976                 /*
977                  * Reset the nr_zones, order and classzone_idx before reuse.
978                  * Note that kswapd will init kswapd_classzone_idx properly
979                  * when it starts in the near future.
980                  */
981                 pgdat->nr_zones = 0;
982                 pgdat->kswapd_order = 0;
983                 pgdat->kswapd_classzone_idx = 0;
984         }
985
986         /* we can use NODE_DATA(nid) from here */
987
988         pgdat->node_id = nid;
989         pgdat->node_start_pfn = start_pfn;
990
991         /* init node's zones as empty zones, we don't have any present pages.*/
992         free_area_init_core_hotplug(nid);
993         pgdat->per_cpu_nodestats = alloc_percpu(struct per_cpu_nodestat);
994
995         /*
996          * The node we allocated has no zone fallback lists. For avoiding
997          * to access not-initialized zonelist, build here.
998          */
999         build_all_zonelists(pgdat);
1000
1001         /*
1002          * When memory is hot-added, all the memory is in offline state. So
1003          * clear all zones' present_pages because they will be updated in
1004          * online_pages() and offline_pages().
1005          */
1006         reset_node_managed_pages(pgdat);
1007         reset_node_present_pages(pgdat);
1008
1009         return pgdat;
1010 }
1011
1012 static void rollback_node_hotadd(int nid)
1013 {
1014         pg_data_t *pgdat = NODE_DATA(nid);
1015
1016         arch_refresh_nodedata(nid, NULL);
1017         free_percpu(pgdat->per_cpu_nodestats);
1018         arch_free_nodedata(pgdat);
1019         return;
1020 }
1021
1022
1023 /**
1024  * try_online_node - online a node if offlined
1025  * @nid: the node ID
1026  * @start: start addr of the node
1027  * @set_node_online: Whether we want to online the node
1028  * called by cpu_up() to online a node without onlined memory.
1029  *
1030  * Returns:
1031  * 1 -> a new node has been allocated
1032  * 0 -> the node is already online
1033  * -ENOMEM -> the node could not be allocated
1034  */
1035 static int __try_online_node(int nid, u64 start, bool set_node_online)
1036 {
1037         pg_data_t *pgdat;
1038         int ret = 1;
1039
1040         if (node_online(nid))
1041                 return 0;
1042
1043         pgdat = hotadd_new_pgdat(nid, start);
1044         if (!pgdat) {
1045                 pr_err("Cannot online node %d due to NULL pgdat\n", nid);
1046                 ret = -ENOMEM;
1047                 goto out;
1048         }
1049
1050         if (set_node_online) {
1051                 node_set_online(nid);
1052                 ret = register_one_node(nid);
1053                 BUG_ON(ret);
1054         }
1055 out:
1056         return ret;
1057 }
1058
1059 /*
1060  * Users of this function always want to online/register the node
1061  */
1062 int try_online_node(int nid)
1063 {
1064         int ret;
1065
1066         mem_hotplug_begin();
1067         ret =  __try_online_node(nid, 0, true);
1068         mem_hotplug_done();
1069         return ret;
1070 }
1071
1072 static int check_hotplug_memory_range(u64 start, u64 size)
1073 {
1074         unsigned long block_sz = memory_block_size_bytes();
1075         u64 block_nr_pages = block_sz >> PAGE_SHIFT;
1076         u64 nr_pages = size >> PAGE_SHIFT;
1077         u64 start_pfn = PFN_DOWN(start);
1078
1079         /* memory range must be block size aligned */
1080         if (!nr_pages || !IS_ALIGNED(start_pfn, block_nr_pages) ||
1081             !IS_ALIGNED(nr_pages, block_nr_pages)) {
1082                 pr_err("Block size [%#lx] unaligned hotplug range: start %#llx, size %#llx",
1083                        block_sz, start, size);
1084                 return -EINVAL;
1085         }
1086
1087         return 0;
1088 }
1089
1090 static int online_memory_block(struct memory_block *mem, void *arg)
1091 {
1092         return device_online(&mem->dev);
1093 }
1094
1095 /*
1096  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
1097  * and online/offline operations (triggered e.g. by sysfs).
1098  *
1099  * we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG
1100  */
1101 int __ref add_memory_resource(int nid, struct resource *res)
1102 {
1103         u64 start, size;
1104         bool new_node = false;
1105         int ret;
1106
1107         start = res->start;
1108         size = resource_size(res);
1109
1110         ret = check_hotplug_memory_range(start, size);
1111         if (ret)
1112                 return ret;
1113
1114         mem_hotplug_begin();
1115
1116         /*
1117          * Add new range to memblock so that when hotadd_new_pgdat() is called
1118          * to allocate new pgdat, get_pfn_range_for_nid() will be able to find
1119          * this new range and calculate total pages correctly.  The range will
1120          * be removed at hot-remove time.
1121          */
1122         memblock_add_node(start, size, nid);
1123
1124         ret = __try_online_node(nid, start, false);
1125         if (ret < 0)
1126                 goto error;
1127         new_node = ret;
1128
1129         /* call arch's memory hotadd */
1130         ret = arch_add_memory(nid, start, size, NULL, true);
1131         if (ret < 0)
1132                 goto error;
1133
1134         if (new_node) {
1135                 /* If sysfs file of new node can't be created, cpu on the node
1136                  * can't be hot-added. There is no rollback way now.
1137                  * So, check by BUG_ON() to catch it reluctantly..
1138                  * We online node here. We can't roll back from here.
1139                  */
1140                 node_set_online(nid);
1141                 ret = __register_one_node(nid);
1142                 BUG_ON(ret);
1143         }
1144
1145         /* link memory sections under this node.*/
1146         ret = link_mem_sections(nid, PFN_DOWN(start), PFN_UP(start + size - 1));
1147         BUG_ON(ret);
1148
1149         /* create new memmap entry */
1150         firmware_map_add_hotplug(start, start + size, "System RAM");
1151
1152         /* device_online() will take the lock when calling online_pages() */
1153         mem_hotplug_done();
1154
1155         /* online pages if requested */
1156         if (memhp_auto_online)
1157                 walk_memory_range(PFN_DOWN(start), PFN_UP(start + size - 1),
1158                                   NULL, online_memory_block);
1159
1160         return ret;
1161 error:
1162         /* rollback pgdat allocation and others */
1163         if (new_node)
1164                 rollback_node_hotadd(nid);
1165         memblock_remove(start, size);
1166         mem_hotplug_done();
1167         return ret;
1168 }
1169
1170 /* requires device_hotplug_lock, see add_memory_resource() */
1171 int __ref __add_memory(int nid, u64 start, u64 size)
1172 {
1173         struct resource *res;
1174         int ret;
1175
1176         res = register_memory_resource(start, size);
1177         if (IS_ERR(res))
1178                 return PTR_ERR(res);
1179
1180         ret = add_memory_resource(nid, res);
1181         if (ret < 0)
1182                 release_memory_resource(res);
1183         return ret;
1184 }
1185
1186 int add_memory(int nid, u64 start, u64 size)
1187 {
1188         int rc;
1189
1190         lock_device_hotplug();
1191         rc = __add_memory(nid, start, size);
1192         unlock_device_hotplug();
1193
1194         return rc;
1195 }
1196 EXPORT_SYMBOL_GPL(add_memory);
1197
1198 #ifdef CONFIG_MEMORY_HOTREMOVE
1199 /*
1200  * A free page on the buddy free lists (not the per-cpu lists) has PageBuddy
1201  * set and the size of the free page is given by page_order(). Using this,
1202  * the function determines if the pageblock contains only free pages.
1203  * Due to buddy contraints, a free page at least the size of a pageblock will
1204  * be located at the start of the pageblock
1205  */
1206 static inline int pageblock_free(struct page *page)
1207 {
1208         return PageBuddy(page) && page_order(page) >= pageblock_order;
1209 }
1210
1211 /* Return the pfn of the start of the next active pageblock after a given pfn */
1212 static unsigned long next_active_pageblock(unsigned long pfn)
1213 {
1214         struct page *page = pfn_to_page(pfn);
1215
1216         /* Ensure the starting page is pageblock-aligned */
1217         BUG_ON(pfn & (pageblock_nr_pages - 1));
1218
1219         /* If the entire pageblock is free, move to the end of free page */
1220         if (pageblock_free(page)) {
1221                 int order;
1222                 /* be careful. we don't have locks, page_order can be changed.*/
1223                 order = page_order(page);
1224                 if ((order < MAX_ORDER) && (order >= pageblock_order))
1225                         return pfn + (1 << order);
1226         }
1227
1228         return pfn + pageblock_nr_pages;
1229 }
1230
1231 static bool is_pageblock_removable_nolock(unsigned long pfn)
1232 {
1233         struct page *page = pfn_to_page(pfn);
1234         struct zone *zone;
1235
1236         /*
1237          * We have to be careful here because we are iterating over memory
1238          * sections which are not zone aware so we might end up outside of
1239          * the zone but still within the section.
1240          * We have to take care about the node as well. If the node is offline
1241          * its NODE_DATA will be NULL - see page_zone.
1242          */
1243         if (!node_online(page_to_nid(page)))
1244                 return false;
1245
1246         zone = page_zone(page);
1247         pfn = page_to_pfn(page);
1248         if (!zone_spans_pfn(zone, pfn))
1249                 return false;
1250
1251         return !has_unmovable_pages(zone, page, 0, MIGRATE_MOVABLE, SKIP_HWPOISON);
1252 }
1253
1254 /* Checks if this range of memory is likely to be hot-removable. */
1255 bool is_mem_section_removable(unsigned long start_pfn, unsigned long nr_pages)
1256 {
1257         unsigned long end_pfn, pfn;
1258
1259         end_pfn = min(start_pfn + nr_pages,
1260                         zone_end_pfn(page_zone(pfn_to_page(start_pfn))));
1261
1262         /* Check the starting page of each pageblock within the range */
1263         for (pfn = start_pfn; pfn < end_pfn; pfn = next_active_pageblock(pfn)) {
1264                 if (!is_pageblock_removable_nolock(pfn))
1265                         return false;
1266                 cond_resched();
1267         }
1268
1269         /* All pageblocks in the memory block are likely to be hot-removable */
1270         return true;
1271 }
1272
1273 /*
1274  * Confirm all pages in a range [start, end) belong to the same zone.
1275  * When true, return its valid [start, end).
1276  */
1277 int test_pages_in_a_zone(unsigned long start_pfn, unsigned long end_pfn,
1278                          unsigned long *valid_start, unsigned long *valid_end)
1279 {
1280         unsigned long pfn, sec_end_pfn;
1281         unsigned long start, end;
1282         struct zone *zone = NULL;
1283         struct page *page;
1284         int i;
1285         for (pfn = start_pfn, sec_end_pfn = SECTION_ALIGN_UP(start_pfn + 1);
1286              pfn < end_pfn;
1287              pfn = sec_end_pfn, sec_end_pfn += PAGES_PER_SECTION) {
1288                 /* Make sure the memory section is present first */
1289                 if (!present_section_nr(pfn_to_section_nr(pfn)))
1290                         continue;
1291                 for (; pfn < sec_end_pfn && pfn < end_pfn;
1292                      pfn += MAX_ORDER_NR_PAGES) {
1293                         i = 0;
1294                         /* This is just a CONFIG_HOLES_IN_ZONE check.*/
1295                         while ((i < MAX_ORDER_NR_PAGES) &&
1296                                 !pfn_valid_within(pfn + i))
1297                                 i++;
1298                         if (i == MAX_ORDER_NR_PAGES || pfn + i >= end_pfn)
1299                                 continue;
1300                         /* Check if we got outside of the zone */
1301                         if (zone && !zone_spans_pfn(zone, pfn + i))
1302                                 return 0;
1303                         page = pfn_to_page(pfn + i);
1304                         if (zone && page_zone(page) != zone)
1305                                 return 0;
1306                         if (!zone)
1307                                 start = pfn + i;
1308                         zone = page_zone(page);
1309                         end = pfn + MAX_ORDER_NR_PAGES;
1310                 }
1311         }
1312
1313         if (zone) {
1314                 *valid_start = start;
1315                 *valid_end = min(end, end_pfn);
1316                 return 1;
1317         } else {
1318                 return 0;
1319         }
1320 }
1321
1322 /*
1323  * Scan pfn range [start,end) to find movable/migratable pages (LRU pages,
1324  * non-lru movable pages and hugepages). We scan pfn because it's much
1325  * easier than scanning over linked list. This function returns the pfn
1326  * of the first found movable page if it's found, otherwise 0.
1327  */
1328 static unsigned long scan_movable_pages(unsigned long start, unsigned long end)
1329 {
1330         unsigned long pfn;
1331
1332         for (pfn = start; pfn < end; pfn++) {
1333                 struct page *page, *head;
1334                 unsigned long skip;
1335
1336                 if (!pfn_valid(pfn))
1337                         continue;
1338                 page = pfn_to_page(pfn);
1339                 if (PageLRU(page))
1340                         return pfn;
1341                 if (__PageMovable(page))
1342                         return pfn;
1343
1344                 if (!PageHuge(page))
1345                         continue;
1346                 head = compound_head(page);
1347                 if (hugepage_migration_supported(page_hstate(head)) &&
1348                     page_huge_active(head))
1349                         return pfn;
1350                 skip = (1 << compound_order(head)) - (page - head);
1351                 pfn += skip - 1;
1352         }
1353         return 0;
1354 }
1355
1356 static struct page *new_node_page(struct page *page, unsigned long private)
1357 {
1358         int nid = page_to_nid(page);
1359         nodemask_t nmask = node_states[N_MEMORY];
1360
1361         /*
1362          * try to allocate from a different node but reuse this node if there
1363          * are no other online nodes to be used (e.g. we are offlining a part
1364          * of the only existing node)
1365          */
1366         node_clear(nid, nmask);
1367         if (nodes_empty(nmask))
1368                 node_set(nid, nmask);
1369
1370         return new_page_nodemask(page, nid, &nmask);
1371 }
1372
1373 static int
1374 do_migrate_range(unsigned long start_pfn, unsigned long end_pfn)
1375 {
1376         unsigned long pfn;
1377         struct page *page;
1378         int ret = 0;
1379         LIST_HEAD(source);
1380
1381         for (pfn = start_pfn; pfn < end_pfn; pfn++) {
1382                 if (!pfn_valid(pfn))
1383                         continue;
1384                 page = pfn_to_page(pfn);
1385
1386                 if (PageHuge(page)) {
1387                         struct page *head = compound_head(page);
1388                         if (compound_order(head) > PFN_SECTION_SHIFT) {
1389                                 ret = -EBUSY;
1390                                 break;
1391                         }
1392                         pfn = page_to_pfn(head) + (1<<compound_order(head)) - 1;
1393                         isolate_huge_page(head, &source);
1394                         continue;
1395                 } else if (PageTransHuge(page))
1396                         pfn = page_to_pfn(compound_head(page))
1397                                 + hpage_nr_pages(page) - 1;
1398
1399                 /*
1400                  * HWPoison pages have elevated reference counts so the migration would
1401                  * fail on them. It also doesn't make any sense to migrate them in the
1402                  * first place. Still try to unmap such a page in case it is still mapped
1403                  * (e.g. current hwpoison implementation doesn't unmap KSM pages but keep
1404                  * the unmap as the catch all safety net).
1405                  */
1406                 if (PageHWPoison(page)) {
1407                         if (WARN_ON(PageLRU(page)))
1408                                 isolate_lru_page(page);
1409                         if (page_mapped(page))
1410                                 try_to_unmap(page, TTU_IGNORE_MLOCK | TTU_IGNORE_ACCESS);
1411                         continue;
1412                 }
1413
1414                 if (!get_page_unless_zero(page))
1415                         continue;
1416                 /*
1417                  * We can skip free pages. And we can deal with pages on
1418                  * LRU and non-lru movable pages.
1419                  */
1420                 if (PageLRU(page))
1421                         ret = isolate_lru_page(page);
1422                 else
1423                         ret = isolate_movable_page(page, ISOLATE_UNEVICTABLE);
1424                 if (!ret) { /* Success */
1425                         list_add_tail(&page->lru, &source);
1426                         if (!__PageMovable(page))
1427                                 inc_node_page_state(page, NR_ISOLATED_ANON +
1428                                                     page_is_file_cache(page));
1429
1430                 } else {
1431                         pr_warn("failed to isolate pfn %lx\n", pfn);
1432                         dump_page(page, "isolation failed");
1433                 }
1434                 put_page(page);
1435         }
1436         if (!list_empty(&source)) {
1437                 /* Allocate a new page from the nearest neighbor node */
1438                 ret = migrate_pages(&source, new_node_page, NULL, 0,
1439                                         MIGRATE_SYNC, MR_MEMORY_HOTPLUG);
1440                 if (ret) {
1441                         list_for_each_entry(page, &source, lru) {
1442                                 pr_warn("migrating pfn %lx failed ret:%d ",
1443                                        page_to_pfn(page), ret);
1444                                 dump_page(page, "migration failure");
1445                         }
1446                         putback_movable_pages(&source);
1447                 }
1448         }
1449
1450         return ret;
1451 }
1452
1453 /*
1454  * remove from free_area[] and mark all as Reserved.
1455  */
1456 static int
1457 offline_isolated_pages_cb(unsigned long start, unsigned long nr_pages,
1458                         void *data)
1459 {
1460         __offline_isolated_pages(start, start + nr_pages);
1461         return 0;
1462 }
1463
1464 static void
1465 offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
1466 {
1467         walk_system_ram_range(start_pfn, end_pfn - start_pfn, NULL,
1468                                 offline_isolated_pages_cb);
1469 }
1470
1471 /*
1472  * Check all pages in range, recoreded as memory resource, are isolated.
1473  */
1474 static int
1475 check_pages_isolated_cb(unsigned long start_pfn, unsigned long nr_pages,
1476                         void *data)
1477 {
1478         int ret;
1479         long offlined = *(long *)data;
1480         ret = test_pages_isolated(start_pfn, start_pfn + nr_pages, true);
1481         offlined = nr_pages;
1482         if (!ret)
1483                 *(long *)data += offlined;
1484         return ret;
1485 }
1486
1487 static long
1488 check_pages_isolated(unsigned long start_pfn, unsigned long end_pfn)
1489 {
1490         long offlined = 0;
1491         int ret;
1492
1493         ret = walk_system_ram_range(start_pfn, end_pfn - start_pfn, &offlined,
1494                         check_pages_isolated_cb);
1495         if (ret < 0)
1496                 offlined = (long)ret;
1497         return offlined;
1498 }
1499
1500 static int __init cmdline_parse_movable_node(char *p)
1501 {
1502 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
1503         movable_node_enabled = true;
1504 #else
1505         pr_warn("movable_node parameter depends on CONFIG_HAVE_MEMBLOCK_NODE_MAP to work properly\n");
1506 #endif
1507         return 0;
1508 }
1509 early_param("movable_node", cmdline_parse_movable_node);
1510
1511 /* check which state of node_states will be changed when offline memory */
1512 static void node_states_check_changes_offline(unsigned long nr_pages,
1513                 struct zone *zone, struct memory_notify *arg)
1514 {
1515         struct pglist_data *pgdat = zone->zone_pgdat;
1516         unsigned long present_pages = 0;
1517         enum zone_type zt;
1518
1519         arg->status_change_nid = NUMA_NO_NODE;
1520         arg->status_change_nid_normal = NUMA_NO_NODE;
1521         arg->status_change_nid_high = NUMA_NO_NODE;
1522
1523         /*
1524          * Check whether node_states[N_NORMAL_MEMORY] will be changed.
1525          * If the memory to be offline is within the range
1526          * [0..ZONE_NORMAL], and it is the last present memory there,
1527          * the zones in that range will become empty after the offlining,
1528          * thus we can determine that we need to clear the node from
1529          * node_states[N_NORMAL_MEMORY].
1530          */
1531         for (zt = 0; zt <= ZONE_NORMAL; zt++)
1532                 present_pages += pgdat->node_zones[zt].present_pages;
1533         if (zone_idx(zone) <= ZONE_NORMAL && nr_pages >= present_pages)
1534                 arg->status_change_nid_normal = zone_to_nid(zone);
1535
1536 #ifdef CONFIG_HIGHMEM
1537         /*
1538          * node_states[N_HIGH_MEMORY] contains nodes which
1539          * have normal memory or high memory.
1540          * Here we add the present_pages belonging to ZONE_HIGHMEM.
1541          * If the zone is within the range of [0..ZONE_HIGHMEM), and
1542          * we determine that the zones in that range become empty,
1543          * we need to clear the node for N_HIGH_MEMORY.
1544          */
1545         present_pages += pgdat->node_zones[ZONE_HIGHMEM].present_pages;
1546         if (zone_idx(zone) <= ZONE_HIGHMEM && nr_pages >= present_pages)
1547                 arg->status_change_nid_high = zone_to_nid(zone);
1548 #endif
1549
1550         /*
1551          * We have accounted the pages from [0..ZONE_NORMAL), and
1552          * in case of CONFIG_HIGHMEM the pages from ZONE_HIGHMEM
1553          * as well.
1554          * Here we count the possible pages from ZONE_MOVABLE.
1555          * If after having accounted all the pages, we see that the nr_pages
1556          * to be offlined is over or equal to the accounted pages,
1557          * we know that the node will become empty, and so, we can clear
1558          * it for N_MEMORY as well.
1559          */
1560         present_pages += pgdat->node_zones[ZONE_MOVABLE].present_pages;
1561
1562         if (nr_pages >= present_pages)
1563                 arg->status_change_nid = zone_to_nid(zone);
1564 }
1565
1566 static void node_states_clear_node(int node, struct memory_notify *arg)
1567 {
1568         if (arg->status_change_nid_normal >= 0)
1569                 node_clear_state(node, N_NORMAL_MEMORY);
1570
1571         if (arg->status_change_nid_high >= 0)
1572                 node_clear_state(node, N_HIGH_MEMORY);
1573
1574         if (arg->status_change_nid >= 0)
1575                 node_clear_state(node, N_MEMORY);
1576 }
1577
1578 static int __ref __offline_pages(unsigned long start_pfn,
1579                   unsigned long end_pfn)
1580 {
1581         unsigned long pfn, nr_pages;
1582         long offlined_pages;
1583         int ret, node;
1584         unsigned long flags;
1585         unsigned long valid_start, valid_end;
1586         struct zone *zone;
1587         struct memory_notify arg;
1588         char *reason;
1589
1590         mem_hotplug_begin();
1591
1592         /* This makes hotplug much easier...and readable.
1593            we assume this for now. .*/
1594         if (!test_pages_in_a_zone(start_pfn, end_pfn, &valid_start,
1595                                   &valid_end)) {
1596                 ret = -EINVAL;
1597                 reason = "multizone range";
1598                 goto failed_removal;
1599         }
1600
1601         zone = page_zone(pfn_to_page(valid_start));
1602         node = zone_to_nid(zone);
1603         nr_pages = end_pfn - start_pfn;
1604
1605         /* set above range as isolated */
1606         ret = start_isolate_page_range(start_pfn, end_pfn,
1607                                        MIGRATE_MOVABLE,
1608                                        SKIP_HWPOISON | REPORT_FAILURE);
1609         if (ret) {
1610                 reason = "failure to isolate range";
1611                 goto failed_removal;
1612         }
1613
1614         arg.start_pfn = start_pfn;
1615         arg.nr_pages = nr_pages;
1616         node_states_check_changes_offline(nr_pages, zone, &arg);
1617
1618         ret = memory_notify(MEM_GOING_OFFLINE, &arg);
1619         ret = notifier_to_errno(ret);
1620         if (ret) {
1621                 reason = "notifier failure";
1622                 goto failed_removal_isolated;
1623         }
1624
1625         do {
1626                 for (pfn = start_pfn; pfn;) {
1627                         if (signal_pending(current)) {
1628                                 ret = -EINTR;
1629                                 reason = "signal backoff";
1630                                 goto failed_removal_isolated;
1631                         }
1632
1633                         cond_resched();
1634                         lru_add_drain_all();
1635
1636                         pfn = scan_movable_pages(pfn, end_pfn);
1637                         if (pfn) {
1638                                 /*
1639                                  * TODO: fatal migration failures should bail
1640                                  * out
1641                                  */
1642                                 do_migrate_range(pfn, end_pfn);
1643                         }
1644                 }
1645
1646                 /*
1647                  * Dissolve free hugepages in the memory block before doing
1648                  * offlining actually in order to make hugetlbfs's object
1649                  * counting consistent.
1650                  */
1651                 ret = dissolve_free_huge_pages(start_pfn, end_pfn);
1652                 if (ret) {
1653                         reason = "failure to dissolve huge pages";
1654                         goto failed_removal_isolated;
1655                 }
1656                 /* check again */
1657                 offlined_pages = check_pages_isolated(start_pfn, end_pfn);
1658         } while (offlined_pages < 0);
1659
1660         pr_info("Offlined Pages %ld\n", offlined_pages);
1661         /* Ok, all of our target is isolated.
1662            We cannot do rollback at this point. */
1663         offline_isolated_pages(start_pfn, end_pfn);
1664         /* reset pagetype flags and makes migrate type to be MOVABLE */
1665         undo_isolate_page_range(start_pfn, end_pfn, MIGRATE_MOVABLE);
1666         /* removal success */
1667         adjust_managed_page_count(pfn_to_page(start_pfn), -offlined_pages);
1668         zone->present_pages -= offlined_pages;
1669
1670         pgdat_resize_lock(zone->zone_pgdat, &flags);
1671         zone->zone_pgdat->node_present_pages -= offlined_pages;
1672         pgdat_resize_unlock(zone->zone_pgdat, &flags);
1673
1674         init_per_zone_wmark_min();
1675
1676         if (!populated_zone(zone)) {
1677                 zone_pcp_reset(zone);
1678                 build_all_zonelists(NULL);
1679         } else
1680                 zone_pcp_update(zone);
1681
1682         node_states_clear_node(node, &arg);
1683         if (arg.status_change_nid >= 0) {
1684                 kswapd_stop(node);
1685                 kcompactd_stop(node);
1686         }
1687
1688         vm_total_pages = nr_free_pagecache_pages();
1689         writeback_set_ratelimit();
1690
1691         memory_notify(MEM_OFFLINE, &arg);
1692         mem_hotplug_done();
1693         return 0;
1694
1695 failed_removal_isolated:
1696         undo_isolate_page_range(start_pfn, end_pfn, MIGRATE_MOVABLE);
1697 failed_removal:
1698         pr_debug("memory offlining [mem %#010llx-%#010llx] failed due to %s\n",
1699                  (unsigned long long) start_pfn << PAGE_SHIFT,
1700                  ((unsigned long long) end_pfn << PAGE_SHIFT) - 1,
1701                  reason);
1702         memory_notify(MEM_CANCEL_OFFLINE, &arg);
1703         /* pushback to free area */
1704         mem_hotplug_done();
1705         return ret;
1706 }
1707
1708 int offline_pages(unsigned long start_pfn, unsigned long nr_pages)
1709 {
1710         return __offline_pages(start_pfn, start_pfn + nr_pages);
1711 }
1712 #endif /* CONFIG_MEMORY_HOTREMOVE */
1713
1714 /**
1715  * walk_memory_range - walks through all mem sections in [start_pfn, end_pfn)
1716  * @start_pfn: start pfn of the memory range
1717  * @end_pfn: end pfn of the memory range
1718  * @arg: argument passed to func
1719  * @func: callback for each memory section walked
1720  *
1721  * This function walks through all present mem sections in range
1722  * [start_pfn, end_pfn) and call func on each mem section.
1723  *
1724  * Returns the return value of func.
1725  */
1726 int walk_memory_range(unsigned long start_pfn, unsigned long end_pfn,
1727                 void *arg, int (*func)(struct memory_block *, void *))
1728 {
1729         struct memory_block *mem = NULL;
1730         struct mem_section *section;
1731         unsigned long pfn, section_nr;
1732         int ret;
1733
1734         for (pfn = start_pfn; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
1735                 section_nr = pfn_to_section_nr(pfn);
1736                 if (!present_section_nr(section_nr))
1737                         continue;
1738
1739                 section = __nr_to_section(section_nr);
1740                 /* same memblock? */
1741                 if (mem)
1742                         if ((section_nr >= mem->start_section_nr) &&
1743                             (section_nr <= mem->end_section_nr))
1744                                 continue;
1745
1746                 mem = find_memory_block_hinted(section, mem);
1747                 if (!mem)
1748                         continue;
1749
1750                 ret = func(mem, arg);
1751                 if (ret) {
1752                         kobject_put(&mem->dev.kobj);
1753                         return ret;
1754                 }
1755         }
1756
1757         if (mem)
1758                 kobject_put(&mem->dev.kobj);
1759
1760         return 0;
1761 }
1762
1763 #ifdef CONFIG_MEMORY_HOTREMOVE
1764 static int check_memblock_offlined_cb(struct memory_block *mem, void *arg)
1765 {
1766         int ret = !is_memblock_offlined(mem);
1767
1768         if (unlikely(ret)) {
1769                 phys_addr_t beginpa, endpa;
1770
1771                 beginpa = PFN_PHYS(section_nr_to_pfn(mem->start_section_nr));
1772                 endpa = PFN_PHYS(section_nr_to_pfn(mem->end_section_nr + 1))-1;
1773                 pr_warn("removing memory fails, because memory [%pa-%pa] is onlined\n",
1774                         &beginpa, &endpa);
1775         }
1776
1777         return ret;
1778 }
1779
1780 static int check_cpu_on_node(pg_data_t *pgdat)
1781 {
1782         int cpu;
1783
1784         for_each_present_cpu(cpu) {
1785                 if (cpu_to_node(cpu) == pgdat->node_id)
1786                         /*
1787                          * the cpu on this node isn't removed, and we can't
1788                          * offline this node.
1789                          */
1790                         return -EBUSY;
1791         }
1792
1793         return 0;
1794 }
1795
1796 /**
1797  * try_offline_node
1798  * @nid: the node ID
1799  *
1800  * Offline a node if all memory sections and cpus of the node are removed.
1801  *
1802  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
1803  * and online/offline operations before this call.
1804  */
1805 void try_offline_node(int nid)
1806 {
1807         pg_data_t *pgdat = NODE_DATA(nid);
1808         unsigned long start_pfn = pgdat->node_start_pfn;
1809         unsigned long end_pfn = start_pfn + pgdat->node_spanned_pages;
1810         unsigned long pfn;
1811
1812         for (pfn = start_pfn; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
1813                 unsigned long section_nr = pfn_to_section_nr(pfn);
1814
1815                 if (!present_section_nr(section_nr))
1816                         continue;
1817
1818                 if (pfn_to_nid(pfn) != nid)
1819                         continue;
1820
1821                 /*
1822                  * some memory sections of this node are not removed, and we
1823                  * can't offline node now.
1824                  */
1825                 return;
1826         }
1827
1828         if (check_cpu_on_node(pgdat))
1829                 return;
1830
1831         /*
1832          * all memory/cpu of this node are removed, we can offline this
1833          * node now.
1834          */
1835         node_set_offline(nid);
1836         unregister_one_node(nid);
1837 }
1838 EXPORT_SYMBOL(try_offline_node);
1839
1840 /**
1841  * remove_memory
1842  * @nid: the node ID
1843  * @start: physical address of the region to remove
1844  * @size: size of the region to remove
1845  *
1846  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
1847  * and online/offline operations before this call, as required by
1848  * try_offline_node().
1849  */
1850 void __ref __remove_memory(int nid, u64 start, u64 size)
1851 {
1852         int ret;
1853
1854         BUG_ON(check_hotplug_memory_range(start, size));
1855
1856         mem_hotplug_begin();
1857
1858         /*
1859          * All memory blocks must be offlined before removing memory.  Check
1860          * whether all memory blocks in question are offline and trigger a BUG()
1861          * if this is not the case.
1862          */
1863         ret = walk_memory_range(PFN_DOWN(start), PFN_UP(start + size - 1), NULL,
1864                                 check_memblock_offlined_cb);
1865         if (ret)
1866                 BUG();
1867
1868         /* remove memmap entry */
1869         firmware_map_remove(start, start + size, "System RAM");
1870         memblock_free(start, size);
1871         memblock_remove(start, size);
1872
1873         arch_remove_memory(nid, start, size, NULL);
1874
1875         try_offline_node(nid);
1876
1877         mem_hotplug_done();
1878 }
1879
1880 void remove_memory(int nid, u64 start, u64 size)
1881 {
1882         lock_device_hotplug();
1883         __remove_memory(nid, start, size);
1884         unlock_device_hotplug();
1885 }
1886 EXPORT_SYMBOL_GPL(remove_memory);
1887 #endif /* CONFIG_MEMORY_HOTREMOVE */