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