]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - mm/memory_hotplug.c
mm, vmstat: skip reporting offline pages in pagetypeinfo
[karo-tx-linux.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 void __meminit grow_zone_span(struct zone *zone, unsigned long start_pfn,
304                                      unsigned long end_pfn)
305 {
306         unsigned long old_zone_end_pfn;
307
308         zone_span_writelock(zone);
309
310         old_zone_end_pfn = zone_end_pfn(zone);
311         if (zone_is_empty(zone) || start_pfn < zone->zone_start_pfn)
312                 zone->zone_start_pfn = start_pfn;
313
314         zone->spanned_pages = max(old_zone_end_pfn, end_pfn) -
315                                 zone->zone_start_pfn;
316
317         zone_span_writeunlock(zone);
318 }
319
320 static void resize_zone(struct zone *zone, unsigned long start_pfn,
321                 unsigned long end_pfn)
322 {
323         zone_span_writelock(zone);
324
325         if (end_pfn - start_pfn) {
326                 zone->zone_start_pfn = start_pfn;
327                 zone->spanned_pages = end_pfn - start_pfn;
328         } else {
329                 /*
330                  * make it consist as free_area_init_core(),
331                  * if spanned_pages = 0, then keep start_pfn = 0
332                  */
333                 zone->zone_start_pfn = 0;
334                 zone->spanned_pages = 0;
335         }
336
337         zone_span_writeunlock(zone);
338 }
339
340 static void fix_zone_id(struct zone *zone, unsigned long start_pfn,
341                 unsigned long end_pfn)
342 {
343         enum zone_type zid = zone_idx(zone);
344         int nid = zone->zone_pgdat->node_id;
345         unsigned long pfn;
346
347         for (pfn = start_pfn; pfn < end_pfn; pfn++)
348                 set_page_links(pfn_to_page(pfn), zid, nid, pfn);
349 }
350
351 static void __ref ensure_zone_is_initialized(struct zone *zone,
352                         unsigned long start_pfn, unsigned long num_pages)
353 {
354         if (!zone_is_initialized(zone))
355                 init_currently_empty_zone(zone, start_pfn, num_pages);
356 }
357
358 static int __meminit move_pfn_range_left(struct zone *z1, struct zone *z2,
359                 unsigned long start_pfn, unsigned long end_pfn)
360 {
361         unsigned long flags;
362         unsigned long z1_start_pfn;
363
364         ensure_zone_is_initialized(z1, start_pfn, end_pfn - start_pfn);
365
366         pgdat_resize_lock(z1->zone_pgdat, &flags);
367
368         /* can't move pfns which are higher than @z2 */
369         if (end_pfn > zone_end_pfn(z2))
370                 goto out_fail;
371         /* the move out part must be at the left most of @z2 */
372         if (start_pfn > z2->zone_start_pfn)
373                 goto out_fail;
374         /* must included/overlap */
375         if (end_pfn <= z2->zone_start_pfn)
376                 goto out_fail;
377
378         /* use start_pfn for z1's start_pfn if z1 is empty */
379         if (!zone_is_empty(z1))
380                 z1_start_pfn = z1->zone_start_pfn;
381         else
382                 z1_start_pfn = start_pfn;
383
384         resize_zone(z1, z1_start_pfn, end_pfn);
385         resize_zone(z2, end_pfn, zone_end_pfn(z2));
386
387         pgdat_resize_unlock(z1->zone_pgdat, &flags);
388
389         fix_zone_id(z1, start_pfn, end_pfn);
390
391         return 0;
392 out_fail:
393         pgdat_resize_unlock(z1->zone_pgdat, &flags);
394         return -1;
395 }
396
397 static int __meminit move_pfn_range_right(struct zone *z1, struct zone *z2,
398                 unsigned long start_pfn, unsigned long end_pfn)
399 {
400         unsigned long flags;
401         unsigned long z2_end_pfn;
402
403         ensure_zone_is_initialized(z2, start_pfn, end_pfn - start_pfn);
404
405         pgdat_resize_lock(z1->zone_pgdat, &flags);
406
407         /* can't move pfns which are lower than @z1 */
408         if (z1->zone_start_pfn > start_pfn)
409                 goto out_fail;
410         /* the move out part mast at the right most of @z1 */
411         if (zone_end_pfn(z1) >  end_pfn)
412                 goto out_fail;
413         /* must included/overlap */
414         if (start_pfn >= zone_end_pfn(z1))
415                 goto out_fail;
416
417         /* use end_pfn for z2's end_pfn if z2 is empty */
418         if (!zone_is_empty(z2))
419                 z2_end_pfn = zone_end_pfn(z2);
420         else
421                 z2_end_pfn = end_pfn;
422
423         resize_zone(z1, z1->zone_start_pfn, start_pfn);
424         resize_zone(z2, start_pfn, z2_end_pfn);
425
426         pgdat_resize_unlock(z1->zone_pgdat, &flags);
427
428         fix_zone_id(z2, start_pfn, end_pfn);
429
430         return 0;
431 out_fail:
432         pgdat_resize_unlock(z1->zone_pgdat, &flags);
433         return -1;
434 }
435
436 static struct zone * __meminit move_pfn_range(int zone_shift,
437                 unsigned long start_pfn, unsigned long end_pfn)
438 {
439         struct zone *zone = page_zone(pfn_to_page(start_pfn));
440         int ret = 0;
441
442         if (zone_shift < 0)
443                 ret = move_pfn_range_left(zone + zone_shift, zone,
444                                           start_pfn, end_pfn);
445         else if (zone_shift)
446                 ret = move_pfn_range_right(zone, zone + zone_shift,
447                                            start_pfn, end_pfn);
448
449         if (ret)
450                 return NULL;
451
452         return zone + zone_shift;
453 }
454
455 static void __meminit grow_pgdat_span(struct pglist_data *pgdat, unsigned long start_pfn,
456                                       unsigned long end_pfn)
457 {
458         unsigned long old_pgdat_end_pfn = pgdat_end_pfn(pgdat);
459
460         if (!pgdat->node_spanned_pages || start_pfn < pgdat->node_start_pfn)
461                 pgdat->node_start_pfn = start_pfn;
462
463         pgdat->node_spanned_pages = max(old_pgdat_end_pfn, end_pfn) -
464                                         pgdat->node_start_pfn;
465 }
466
467 static int __meminit __add_zone(struct zone *zone, unsigned long phys_start_pfn)
468 {
469         struct pglist_data *pgdat = zone->zone_pgdat;
470         int nr_pages = PAGES_PER_SECTION;
471         int nid = pgdat->node_id;
472         int zone_type;
473         unsigned long flags, pfn;
474
475         zone_type = zone - pgdat->node_zones;
476         ensure_zone_is_initialized(zone, phys_start_pfn, nr_pages);
477
478         pgdat_resize_lock(zone->zone_pgdat, &flags);
479         grow_zone_span(zone, phys_start_pfn, phys_start_pfn + nr_pages);
480         grow_pgdat_span(zone->zone_pgdat, phys_start_pfn,
481                         phys_start_pfn + nr_pages);
482         pgdat_resize_unlock(zone->zone_pgdat, &flags);
483         memmap_init_zone(nr_pages, nid, zone_type,
484                          phys_start_pfn, MEMMAP_HOTPLUG);
485
486         /* online_page_range is called later and expects pages reserved */
487         for (pfn = phys_start_pfn; pfn < phys_start_pfn + nr_pages; pfn++) {
488                 if (!pfn_valid(pfn))
489                         continue;
490
491                 SetPageReserved(pfn_to_page(pfn));
492         }
493         return 0;
494 }
495
496 static int __meminit __add_section(int nid, struct zone *zone,
497                 unsigned long phys_start_pfn, bool want_memblock)
498 {
499         int ret;
500
501         if (pfn_valid(phys_start_pfn))
502                 return -EEXIST;
503
504         ret = sparse_add_one_section(zone, phys_start_pfn);
505
506         if (ret < 0)
507                 return ret;
508
509         ret = __add_zone(zone, phys_start_pfn);
510
511         if (ret < 0)
512                 return ret;
513
514         if (!want_memblock)
515                 return 0;
516
517         return register_new_memory(nid, __pfn_to_section(phys_start_pfn));
518 }
519
520 /*
521  * Reasonably generic function for adding memory.  It is
522  * expected that archs that support memory hotplug will
523  * call this function after deciding the zone to which to
524  * add the new pages.
525  */
526 int __ref __add_pages(int nid, struct zone *zone, unsigned long phys_start_pfn,
527                         unsigned long nr_pages, bool want_memblock)
528 {
529         unsigned long i;
530         int err = 0;
531         int start_sec, end_sec;
532         struct vmem_altmap *altmap;
533
534         clear_zone_contiguous(zone);
535
536         /* during initialize mem_map, align hot-added range to section */
537         start_sec = pfn_to_section_nr(phys_start_pfn);
538         end_sec = pfn_to_section_nr(phys_start_pfn + nr_pages - 1);
539
540         altmap = to_vmem_altmap((unsigned long) pfn_to_page(phys_start_pfn));
541         if (altmap) {
542                 /*
543                  * Validate altmap is within bounds of the total request
544                  */
545                 if (altmap->base_pfn != phys_start_pfn
546                                 || vmem_altmap_offset(altmap) > nr_pages) {
547                         pr_warn_once("memory add fail, invalid altmap\n");
548                         err = -EINVAL;
549                         goto out;
550                 }
551                 altmap->alloc = 0;
552         }
553
554         for (i = start_sec; i <= end_sec; i++) {
555                 err = __add_section(nid, zone, section_nr_to_pfn(i), want_memblock);
556
557                 /*
558                  * EEXIST is finally dealt with by ioresource collision
559                  * check. see add_memory() => register_memory_resource()
560                  * Warning will be printed if there is collision.
561                  */
562                 if (err && (err != -EEXIST))
563                         break;
564                 err = 0;
565         }
566         vmemmap_populate_print_last();
567 out:
568         set_zone_contiguous(zone);
569         return err;
570 }
571 EXPORT_SYMBOL_GPL(__add_pages);
572
573 #ifdef CONFIG_MEMORY_HOTREMOVE
574 /* find the smallest valid pfn in the range [start_pfn, end_pfn) */
575 static int find_smallest_section_pfn(int nid, struct zone *zone,
576                                      unsigned long start_pfn,
577                                      unsigned long end_pfn)
578 {
579         struct mem_section *ms;
580
581         for (; start_pfn < end_pfn; start_pfn += PAGES_PER_SECTION) {
582                 ms = __pfn_to_section(start_pfn);
583
584                 if (unlikely(!valid_section(ms)))
585                         continue;
586
587                 if (unlikely(pfn_to_nid(start_pfn) != nid))
588                         continue;
589
590                 if (zone && zone != page_zone(pfn_to_page(start_pfn)))
591                         continue;
592
593                 return start_pfn;
594         }
595
596         return 0;
597 }
598
599 /* find the biggest valid pfn in the range [start_pfn, end_pfn). */
600 static int find_biggest_section_pfn(int nid, struct zone *zone,
601                                     unsigned long start_pfn,
602                                     unsigned long end_pfn)
603 {
604         struct mem_section *ms;
605         unsigned long pfn;
606
607         /* pfn is the end pfn of a memory section. */
608         pfn = end_pfn - 1;
609         for (; pfn >= start_pfn; pfn -= PAGES_PER_SECTION) {
610                 ms = __pfn_to_section(pfn);
611
612                 if (unlikely(!valid_section(ms)))
613                         continue;
614
615                 if (unlikely(pfn_to_nid(pfn) != nid))
616                         continue;
617
618                 if (zone && zone != page_zone(pfn_to_page(pfn)))
619                         continue;
620
621                 return pfn;
622         }
623
624         return 0;
625 }
626
627 static void shrink_zone_span(struct zone *zone, unsigned long start_pfn,
628                              unsigned long end_pfn)
629 {
630         unsigned long zone_start_pfn = zone->zone_start_pfn;
631         unsigned long z = zone_end_pfn(zone); /* zone_end_pfn namespace clash */
632         unsigned long zone_end_pfn = z;
633         unsigned long pfn;
634         struct mem_section *ms;
635         int nid = zone_to_nid(zone);
636
637         zone_span_writelock(zone);
638         if (zone_start_pfn == start_pfn) {
639                 /*
640                  * If the section is smallest section in the zone, it need
641                  * shrink zone->zone_start_pfn and zone->zone_spanned_pages.
642                  * In this case, we find second smallest valid mem_section
643                  * for shrinking zone.
644                  */
645                 pfn = find_smallest_section_pfn(nid, zone, end_pfn,
646                                                 zone_end_pfn);
647                 if (pfn) {
648                         zone->zone_start_pfn = pfn;
649                         zone->spanned_pages = zone_end_pfn - pfn;
650                 }
651         } else if (zone_end_pfn == end_pfn) {
652                 /*
653                  * If the section is biggest section in the zone, it need
654                  * shrink zone->spanned_pages.
655                  * In this case, we find second biggest valid mem_section for
656                  * shrinking zone.
657                  */
658                 pfn = find_biggest_section_pfn(nid, zone, zone_start_pfn,
659                                                start_pfn);
660                 if (pfn)
661                         zone->spanned_pages = pfn - zone_start_pfn + 1;
662         }
663
664         /*
665          * The section is not biggest or smallest mem_section in the zone, it
666          * only creates a hole in the zone. So in this case, we need not
667          * change the zone. But perhaps, the zone has only hole data. Thus
668          * it check the zone has only hole or not.
669          */
670         pfn = zone_start_pfn;
671         for (; pfn < zone_end_pfn; pfn += PAGES_PER_SECTION) {
672                 ms = __pfn_to_section(pfn);
673
674                 if (unlikely(!valid_section(ms)))
675                         continue;
676
677                 if (page_zone(pfn_to_page(pfn)) != zone)
678                         continue;
679
680                  /* If the section is current section, it continues the loop */
681                 if (start_pfn == pfn)
682                         continue;
683
684                 /* If we find valid section, we have nothing to do */
685                 zone_span_writeunlock(zone);
686                 return;
687         }
688
689         /* The zone has no valid section */
690         zone->zone_start_pfn = 0;
691         zone->spanned_pages = 0;
692         zone_span_writeunlock(zone);
693 }
694
695 static void shrink_pgdat_span(struct pglist_data *pgdat,
696                               unsigned long start_pfn, unsigned long end_pfn)
697 {
698         unsigned long pgdat_start_pfn = pgdat->node_start_pfn;
699         unsigned long p = pgdat_end_pfn(pgdat); /* pgdat_end_pfn namespace clash */
700         unsigned long pgdat_end_pfn = p;
701         unsigned long pfn;
702         struct mem_section *ms;
703         int nid = pgdat->node_id;
704
705         if (pgdat_start_pfn == start_pfn) {
706                 /*
707                  * If the section is smallest section in the pgdat, it need
708                  * shrink pgdat->node_start_pfn and pgdat->node_spanned_pages.
709                  * In this case, we find second smallest valid mem_section
710                  * for shrinking zone.
711                  */
712                 pfn = find_smallest_section_pfn(nid, NULL, end_pfn,
713                                                 pgdat_end_pfn);
714                 if (pfn) {
715                         pgdat->node_start_pfn = pfn;
716                         pgdat->node_spanned_pages = pgdat_end_pfn - pfn;
717                 }
718         } else if (pgdat_end_pfn == end_pfn) {
719                 /*
720                  * If the section is biggest section in the pgdat, it need
721                  * shrink pgdat->node_spanned_pages.
722                  * In this case, we find second biggest valid mem_section for
723                  * shrinking zone.
724                  */
725                 pfn = find_biggest_section_pfn(nid, NULL, pgdat_start_pfn,
726                                                start_pfn);
727                 if (pfn)
728                         pgdat->node_spanned_pages = pfn - pgdat_start_pfn + 1;
729         }
730
731         /*
732          * If the section is not biggest or smallest mem_section in the pgdat,
733          * it only creates a hole in the pgdat. So in this case, we need not
734          * change the pgdat.
735          * But perhaps, the pgdat has only hole data. Thus it check the pgdat
736          * has only hole or not.
737          */
738         pfn = pgdat_start_pfn;
739         for (; pfn < pgdat_end_pfn; pfn += PAGES_PER_SECTION) {
740                 ms = __pfn_to_section(pfn);
741
742                 if (unlikely(!valid_section(ms)))
743                         continue;
744
745                 if (pfn_to_nid(pfn) != nid)
746                         continue;
747
748                  /* If the section is current section, it continues the loop */
749                 if (start_pfn == pfn)
750                         continue;
751
752                 /* If we find valid section, we have nothing to do */
753                 return;
754         }
755
756         /* The pgdat has no valid section */
757         pgdat->node_start_pfn = 0;
758         pgdat->node_spanned_pages = 0;
759 }
760
761 static void __remove_zone(struct zone *zone, unsigned long start_pfn)
762 {
763         struct pglist_data *pgdat = zone->zone_pgdat;
764         int nr_pages = PAGES_PER_SECTION;
765         int zone_type;
766         unsigned long flags;
767
768         zone_type = zone - pgdat->node_zones;
769
770         pgdat_resize_lock(zone->zone_pgdat, &flags);
771         shrink_zone_span(zone, start_pfn, start_pfn + nr_pages);
772         shrink_pgdat_span(pgdat, start_pfn, start_pfn + nr_pages);
773         pgdat_resize_unlock(zone->zone_pgdat, &flags);
774 }
775
776 static int __remove_section(struct zone *zone, struct mem_section *ms,
777                 unsigned long map_offset)
778 {
779         unsigned long start_pfn;
780         int scn_nr;
781         int ret = -EINVAL;
782
783         if (!valid_section(ms))
784                 return ret;
785
786         ret = unregister_memory_section(ms);
787         if (ret)
788                 return ret;
789
790         scn_nr = __section_nr(ms);
791         start_pfn = section_nr_to_pfn(scn_nr);
792         __remove_zone(zone, start_pfn);
793
794         sparse_remove_one_section(zone, ms, map_offset);
795         return 0;
796 }
797
798 /**
799  * __remove_pages() - remove sections of pages from a zone
800  * @zone: zone from which pages need to be removed
801  * @phys_start_pfn: starting pageframe (must be aligned to start of a section)
802  * @nr_pages: number of pages to remove (must be multiple of section size)
803  *
804  * Generic helper function to remove section mappings and sysfs entries
805  * for the section of the memory we are removing. Caller needs to make
806  * sure that pages are marked reserved and zones are adjust properly by
807  * calling offline_pages().
808  */
809 int __remove_pages(struct zone *zone, unsigned long phys_start_pfn,
810                  unsigned long nr_pages)
811 {
812         unsigned long i;
813         unsigned long map_offset = 0;
814         int sections_to_remove, ret = 0;
815
816         /* In the ZONE_DEVICE case device driver owns the memory region */
817         if (is_dev_zone(zone)) {
818                 struct page *page = pfn_to_page(phys_start_pfn);
819                 struct vmem_altmap *altmap;
820
821                 altmap = to_vmem_altmap((unsigned long) page);
822                 if (altmap)
823                         map_offset = vmem_altmap_offset(altmap);
824         } else {
825                 resource_size_t start, size;
826
827                 start = phys_start_pfn << PAGE_SHIFT;
828                 size = nr_pages * PAGE_SIZE;
829
830                 ret = release_mem_region_adjustable(&iomem_resource, start,
831                                         size);
832                 if (ret) {
833                         resource_size_t endres = start + size - 1;
834
835                         pr_warn("Unable to release resource <%pa-%pa> (%d)\n",
836                                         &start, &endres, ret);
837                 }
838         }
839
840         clear_zone_contiguous(zone);
841
842         /*
843          * We can only remove entire sections
844          */
845         BUG_ON(phys_start_pfn & ~PAGE_SECTION_MASK);
846         BUG_ON(nr_pages % PAGES_PER_SECTION);
847
848         sections_to_remove = nr_pages / PAGES_PER_SECTION;
849         for (i = 0; i < sections_to_remove; i++) {
850                 unsigned long pfn = phys_start_pfn + i*PAGES_PER_SECTION;
851
852                 ret = __remove_section(zone, __pfn_to_section(pfn), map_offset);
853                 map_offset = 0;
854                 if (ret)
855                         break;
856         }
857
858         set_zone_contiguous(zone);
859
860         return ret;
861 }
862 #endif /* CONFIG_MEMORY_HOTREMOVE */
863
864 int set_online_page_callback(online_page_callback_t callback)
865 {
866         int rc = -EINVAL;
867
868         get_online_mems();
869         mutex_lock(&online_page_callback_lock);
870
871         if (online_page_callback == generic_online_page) {
872                 online_page_callback = callback;
873                 rc = 0;
874         }
875
876         mutex_unlock(&online_page_callback_lock);
877         put_online_mems();
878
879         return rc;
880 }
881 EXPORT_SYMBOL_GPL(set_online_page_callback);
882
883 int restore_online_page_callback(online_page_callback_t callback)
884 {
885         int rc = -EINVAL;
886
887         get_online_mems();
888         mutex_lock(&online_page_callback_lock);
889
890         if (online_page_callback == callback) {
891                 online_page_callback = generic_online_page;
892                 rc = 0;
893         }
894
895         mutex_unlock(&online_page_callback_lock);
896         put_online_mems();
897
898         return rc;
899 }
900 EXPORT_SYMBOL_GPL(restore_online_page_callback);
901
902 void __online_page_set_limits(struct page *page)
903 {
904 }
905 EXPORT_SYMBOL_GPL(__online_page_set_limits);
906
907 void __online_page_increment_counters(struct page *page)
908 {
909         adjust_managed_page_count(page, 1);
910 }
911 EXPORT_SYMBOL_GPL(__online_page_increment_counters);
912
913 void __online_page_free(struct page *page)
914 {
915         __free_reserved_page(page);
916 }
917 EXPORT_SYMBOL_GPL(__online_page_free);
918
919 static void generic_online_page(struct page *page)
920 {
921         __online_page_set_limits(page);
922         __online_page_increment_counters(page);
923         __online_page_free(page);
924 }
925
926 static int online_pages_range(unsigned long start_pfn, unsigned long nr_pages,
927                         void *arg)
928 {
929         unsigned long i;
930         unsigned long onlined_pages = *(unsigned long *)arg;
931         struct page *page;
932
933         if (PageReserved(pfn_to_page(start_pfn)))
934                 for (i = 0; i < nr_pages; i++) {
935                         page = pfn_to_page(start_pfn + i);
936                         (*online_page_callback)(page);
937                         onlined_pages++;
938                 }
939
940         online_mem_sections(start_pfn, start_pfn + nr_pages);
941
942         *(unsigned long *)arg = onlined_pages;
943         return 0;
944 }
945
946 #ifdef CONFIG_MOVABLE_NODE
947 /*
948  * When CONFIG_MOVABLE_NODE, we permit onlining of a node which doesn't have
949  * normal memory.
950  */
951 static bool can_online_high_movable(int nid)
952 {
953         return true;
954 }
955 #else /* CONFIG_MOVABLE_NODE */
956 /* ensure every online node has NORMAL memory */
957 static bool can_online_high_movable(int nid)
958 {
959         return node_state(nid, N_NORMAL_MEMORY);
960 }
961 #endif /* CONFIG_MOVABLE_NODE */
962
963 /* check which state of node_states will be changed when online memory */
964 static void node_states_check_changes_online(unsigned long nr_pages,
965         struct zone *zone, struct memory_notify *arg)
966 {
967         int nid = zone_to_nid(zone);
968         enum zone_type zone_last = ZONE_NORMAL;
969
970         /*
971          * If we have HIGHMEM or movable node, node_states[N_NORMAL_MEMORY]
972          * contains nodes which have zones of 0...ZONE_NORMAL,
973          * set zone_last to ZONE_NORMAL.
974          *
975          * If we don't have HIGHMEM nor movable node,
976          * node_states[N_NORMAL_MEMORY] contains nodes which have zones of
977          * 0...ZONE_MOVABLE, set zone_last to ZONE_MOVABLE.
978          */
979         if (N_MEMORY == N_NORMAL_MEMORY)
980                 zone_last = ZONE_MOVABLE;
981
982         /*
983          * if the memory to be online is in a zone of 0...zone_last, and
984          * the zones of 0...zone_last don't have memory before online, we will
985          * need to set the node to node_states[N_NORMAL_MEMORY] after
986          * the memory is online.
987          */
988         if (zone_idx(zone) <= zone_last && !node_state(nid, N_NORMAL_MEMORY))
989                 arg->status_change_nid_normal = nid;
990         else
991                 arg->status_change_nid_normal = -1;
992
993 #ifdef CONFIG_HIGHMEM
994         /*
995          * If we have movable node, node_states[N_HIGH_MEMORY]
996          * contains nodes which have zones of 0...ZONE_HIGHMEM,
997          * set zone_last to ZONE_HIGHMEM.
998          *
999          * If we don't have movable node, node_states[N_NORMAL_MEMORY]
1000          * contains nodes which have zones of 0...ZONE_MOVABLE,
1001          * set zone_last to ZONE_MOVABLE.
1002          */
1003         zone_last = ZONE_HIGHMEM;
1004         if (N_MEMORY == N_HIGH_MEMORY)
1005                 zone_last = ZONE_MOVABLE;
1006
1007         if (zone_idx(zone) <= zone_last && !node_state(nid, N_HIGH_MEMORY))
1008                 arg->status_change_nid_high = nid;
1009         else
1010                 arg->status_change_nid_high = -1;
1011 #else
1012         arg->status_change_nid_high = arg->status_change_nid_normal;
1013 #endif
1014
1015         /*
1016          * if the node don't have memory befor online, we will need to
1017          * set the node to node_states[N_MEMORY] after the memory
1018          * is online.
1019          */
1020         if (!node_state(nid, N_MEMORY))
1021                 arg->status_change_nid = nid;
1022         else
1023                 arg->status_change_nid = -1;
1024 }
1025
1026 static void node_states_set_node(int node, struct memory_notify *arg)
1027 {
1028         if (arg->status_change_nid_normal >= 0)
1029                 node_set_state(node, N_NORMAL_MEMORY);
1030
1031         if (arg->status_change_nid_high >= 0)
1032                 node_set_state(node, N_HIGH_MEMORY);
1033
1034         node_set_state(node, N_MEMORY);
1035 }
1036
1037 bool zone_can_shift(unsigned long pfn, unsigned long nr_pages,
1038                    enum zone_type target, int *zone_shift)
1039 {
1040         struct zone *zone = page_zone(pfn_to_page(pfn));
1041         enum zone_type idx = zone_idx(zone);
1042         int i;
1043
1044         *zone_shift = 0;
1045
1046         if (idx < target) {
1047                 /* pages must be at end of current zone */
1048                 if (pfn + nr_pages != zone_end_pfn(zone))
1049                         return false;
1050
1051                 /* no zones in use between current zone and target */
1052                 for (i = idx + 1; i < target; i++)
1053                         if (zone_is_initialized(zone - idx + i))
1054                                 return false;
1055         }
1056
1057         if (target < idx) {
1058                 /* pages must be at beginning of current zone */
1059                 if (pfn != zone->zone_start_pfn)
1060                         return false;
1061
1062                 /* no zones in use between current zone and target */
1063                 for (i = target + 1; i < idx; i++)
1064                         if (zone_is_initialized(zone - idx + i))
1065                                 return false;
1066         }
1067
1068         *zone_shift = target - idx;
1069         return true;
1070 }
1071
1072 /* Must be protected by mem_hotplug_begin() */
1073 int __ref online_pages(unsigned long pfn, unsigned long nr_pages, int online_type)
1074 {
1075         unsigned long flags;
1076         unsigned long onlined_pages = 0;
1077         struct zone *zone;
1078         int need_zonelists_rebuild = 0;
1079         int nid;
1080         int ret;
1081         struct memory_notify arg;
1082         int zone_shift = 0;
1083
1084         /*
1085          * This doesn't need a lock to do pfn_to_page().
1086          * The section can't be removed here because of the
1087          * memory_block->state_mutex.
1088          */
1089         zone = page_zone(pfn_to_page(pfn));
1090
1091         if ((zone_idx(zone) > ZONE_NORMAL ||
1092             online_type == MMOP_ONLINE_MOVABLE) &&
1093             !can_online_high_movable(pfn_to_nid(pfn)))
1094                 return -EINVAL;
1095
1096         if (online_type == MMOP_ONLINE_KERNEL) {
1097                 if (!zone_can_shift(pfn, nr_pages, ZONE_NORMAL, &zone_shift))
1098                         return -EINVAL;
1099         } else if (online_type == MMOP_ONLINE_MOVABLE) {
1100                 if (!zone_can_shift(pfn, nr_pages, ZONE_MOVABLE, &zone_shift))
1101                         return -EINVAL;
1102         }
1103
1104         zone = move_pfn_range(zone_shift, pfn, pfn + nr_pages);
1105         if (!zone)
1106                 return -EINVAL;
1107
1108         arg.start_pfn = pfn;
1109         arg.nr_pages = nr_pages;
1110         node_states_check_changes_online(nr_pages, zone, &arg);
1111
1112         nid = zone_to_nid(zone);
1113
1114         ret = memory_notify(MEM_GOING_ONLINE, &arg);
1115         ret = notifier_to_errno(ret);
1116         if (ret)
1117                 goto failed_addition;
1118
1119         /*
1120          * If this zone is not populated, then it is not in zonelist.
1121          * This means the page allocator ignores this zone.
1122          * So, zonelist must be updated after online.
1123          */
1124         mutex_lock(&zonelists_mutex);
1125         if (!populated_zone(zone)) {
1126                 need_zonelists_rebuild = 1;
1127                 build_all_zonelists(NULL, zone);
1128         }
1129
1130         ret = walk_system_ram_range(pfn, nr_pages, &onlined_pages,
1131                 online_pages_range);
1132         if (ret) {
1133                 if (need_zonelists_rebuild)
1134                         zone_pcp_reset(zone);
1135                 mutex_unlock(&zonelists_mutex);
1136                 goto failed_addition;
1137         }
1138
1139         zone->present_pages += onlined_pages;
1140
1141         pgdat_resize_lock(zone->zone_pgdat, &flags);
1142         zone->zone_pgdat->node_present_pages += onlined_pages;
1143         pgdat_resize_unlock(zone->zone_pgdat, &flags);
1144
1145         if (onlined_pages) {
1146                 node_states_set_node(nid, &arg);
1147                 if (need_zonelists_rebuild)
1148                         build_all_zonelists(NULL, NULL);
1149                 else
1150                         zone_pcp_update(zone);
1151         }
1152
1153         mutex_unlock(&zonelists_mutex);
1154
1155         init_per_zone_wmark_min();
1156
1157         if (onlined_pages) {
1158                 kswapd_run(nid);
1159                 kcompactd_run(nid);
1160         }
1161
1162         vm_total_pages = nr_free_pagecache_pages();
1163
1164         writeback_set_ratelimit();
1165
1166         if (onlined_pages)
1167                 memory_notify(MEM_ONLINE, &arg);
1168         return 0;
1169
1170 failed_addition:
1171         pr_debug("online_pages [mem %#010llx-%#010llx] failed\n",
1172                  (unsigned long long) pfn << PAGE_SHIFT,
1173                  (((unsigned long long) pfn + nr_pages) << PAGE_SHIFT) - 1);
1174         memory_notify(MEM_CANCEL_ONLINE, &arg);
1175         return ret;
1176 }
1177 #endif /* CONFIG_MEMORY_HOTPLUG_SPARSE */
1178
1179 static void reset_node_present_pages(pg_data_t *pgdat)
1180 {
1181         struct zone *z;
1182
1183         for (z = pgdat->node_zones; z < pgdat->node_zones + MAX_NR_ZONES; z++)
1184                 z->present_pages = 0;
1185
1186         pgdat->node_present_pages = 0;
1187 }
1188
1189 /* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
1190 static pg_data_t __ref *hotadd_new_pgdat(int nid, u64 start)
1191 {
1192         struct pglist_data *pgdat;
1193         unsigned long zones_size[MAX_NR_ZONES] = {0};
1194         unsigned long zholes_size[MAX_NR_ZONES] = {0};
1195         unsigned long start_pfn = PFN_DOWN(start);
1196
1197         pgdat = NODE_DATA(nid);
1198         if (!pgdat) {
1199                 pgdat = arch_alloc_nodedata(nid);
1200                 if (!pgdat)
1201                         return NULL;
1202
1203                 arch_refresh_nodedata(nid, pgdat);
1204         } else {
1205                 /*
1206                  * Reset the nr_zones, order and classzone_idx before reuse.
1207                  * Note that kswapd will init kswapd_classzone_idx properly
1208                  * when it starts in the near future.
1209                  */
1210                 pgdat->nr_zones = 0;
1211                 pgdat->kswapd_order = 0;
1212                 pgdat->kswapd_classzone_idx = 0;
1213         }
1214
1215         /* we can use NODE_DATA(nid) from here */
1216
1217         /* init node's zones as empty zones, we don't have any present pages.*/
1218         free_area_init_node(nid, zones_size, start_pfn, zholes_size);
1219         pgdat->per_cpu_nodestats = alloc_percpu(struct per_cpu_nodestat);
1220
1221         /*
1222          * The node we allocated has no zone fallback lists. For avoiding
1223          * to access not-initialized zonelist, build here.
1224          */
1225         mutex_lock(&zonelists_mutex);
1226         build_all_zonelists(pgdat, NULL);
1227         mutex_unlock(&zonelists_mutex);
1228
1229         /*
1230          * zone->managed_pages is set to an approximate value in
1231          * free_area_init_core(), which will cause
1232          * /sys/device/system/node/nodeX/meminfo has wrong data.
1233          * So reset it to 0 before any memory is onlined.
1234          */
1235         reset_node_managed_pages(pgdat);
1236
1237         /*
1238          * When memory is hot-added, all the memory is in offline state. So
1239          * clear all zones' present_pages because they will be updated in
1240          * online_pages() and offline_pages().
1241          */
1242         reset_node_present_pages(pgdat);
1243
1244         return pgdat;
1245 }
1246
1247 static void rollback_node_hotadd(int nid, pg_data_t *pgdat)
1248 {
1249         arch_refresh_nodedata(nid, NULL);
1250         free_percpu(pgdat->per_cpu_nodestats);
1251         arch_free_nodedata(pgdat);
1252         return;
1253 }
1254
1255
1256 /**
1257  * try_online_node - online a node if offlined
1258  *
1259  * called by cpu_up() to online a node without onlined memory.
1260  */
1261 int try_online_node(int nid)
1262 {
1263         pg_data_t       *pgdat;
1264         int     ret;
1265
1266         if (node_online(nid))
1267                 return 0;
1268
1269         mem_hotplug_begin();
1270         pgdat = hotadd_new_pgdat(nid, 0);
1271         if (!pgdat) {
1272                 pr_err("Cannot online node %d due to NULL pgdat\n", nid);
1273                 ret = -ENOMEM;
1274                 goto out;
1275         }
1276         node_set_online(nid);
1277         ret = register_one_node(nid);
1278         BUG_ON(ret);
1279
1280         if (pgdat->node_zonelists->_zonerefs->zone == NULL) {
1281                 mutex_lock(&zonelists_mutex);
1282                 build_all_zonelists(NULL, NULL);
1283                 mutex_unlock(&zonelists_mutex);
1284         }
1285
1286 out:
1287         mem_hotplug_done();
1288         return ret;
1289 }
1290
1291 static int check_hotplug_memory_range(u64 start, u64 size)
1292 {
1293         u64 start_pfn = PFN_DOWN(start);
1294         u64 nr_pages = size >> PAGE_SHIFT;
1295
1296         /* Memory range must be aligned with section */
1297         if ((start_pfn & ~PAGE_SECTION_MASK) ||
1298             (nr_pages % PAGES_PER_SECTION) || (!nr_pages)) {
1299                 pr_err("Section-unaligned hotplug range: start 0x%llx, size 0x%llx\n",
1300                                 (unsigned long long)start,
1301                                 (unsigned long long)size);
1302                 return -EINVAL;
1303         }
1304
1305         return 0;
1306 }
1307
1308 /*
1309  * If movable zone has already been setup, newly added memory should be check.
1310  * If its address is higher than movable zone, it should be added as movable.
1311  * Without this check, movable zone may overlap with other zone.
1312  */
1313 static int should_add_memory_movable(int nid, u64 start, u64 size)
1314 {
1315         unsigned long start_pfn = start >> PAGE_SHIFT;
1316         pg_data_t *pgdat = NODE_DATA(nid);
1317         struct zone *movable_zone = pgdat->node_zones + ZONE_MOVABLE;
1318
1319         if (zone_is_empty(movable_zone))
1320                 return 0;
1321
1322         if (movable_zone->zone_start_pfn <= start_pfn)
1323                 return 1;
1324
1325         return 0;
1326 }
1327
1328 int zone_for_memory(int nid, u64 start, u64 size, int zone_default,
1329                 bool for_device)
1330 {
1331 #ifdef CONFIG_ZONE_DEVICE
1332         if (for_device)
1333                 return ZONE_DEVICE;
1334 #endif
1335         if (should_add_memory_movable(nid, start, size))
1336                 return ZONE_MOVABLE;
1337
1338         return zone_default;
1339 }
1340
1341 static int online_memory_block(struct memory_block *mem, void *arg)
1342 {
1343         return device_online(&mem->dev);
1344 }
1345
1346 /* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
1347 int __ref add_memory_resource(int nid, struct resource *res, bool online)
1348 {
1349         u64 start, size;
1350         pg_data_t *pgdat = NULL;
1351         bool new_pgdat;
1352         bool new_node;
1353         int ret;
1354
1355         start = res->start;
1356         size = resource_size(res);
1357
1358         ret = check_hotplug_memory_range(start, size);
1359         if (ret)
1360                 return ret;
1361
1362         {       /* Stupid hack to suppress address-never-null warning */
1363                 void *p = NODE_DATA(nid);
1364                 new_pgdat = !p;
1365         }
1366
1367         mem_hotplug_begin();
1368
1369         /*
1370          * Add new range to memblock so that when hotadd_new_pgdat() is called
1371          * to allocate new pgdat, get_pfn_range_for_nid() will be able to find
1372          * this new range and calculate total pages correctly.  The range will
1373          * be removed at hot-remove time.
1374          */
1375         memblock_add_node(start, size, nid);
1376
1377         new_node = !node_online(nid);
1378         if (new_node) {
1379                 pgdat = hotadd_new_pgdat(nid, start);
1380                 ret = -ENOMEM;
1381                 if (!pgdat)
1382                         goto error;
1383         }
1384
1385         /* call arch's memory hotadd */
1386         ret = arch_add_memory(nid, start, size, false);
1387
1388         if (ret < 0)
1389                 goto error;
1390
1391         /* we online node here. we can't roll back from here. */
1392         node_set_online(nid);
1393
1394         if (new_node) {
1395                 unsigned long start_pfn = start >> PAGE_SHIFT;
1396                 unsigned long nr_pages = size >> PAGE_SHIFT;
1397
1398                 ret = __register_one_node(nid);
1399                 if (ret)
1400                         goto register_fail;
1401
1402                 /*
1403                  * link memory sections under this node. This is already
1404                  * done when creatig memory section in register_new_memory
1405                  * but that depends to have the node registered so offline
1406                  * nodes have to go through register_node.
1407                  * TODO clean up this mess.
1408                  */
1409                 ret = link_mem_sections(nid, start_pfn, nr_pages);
1410 register_fail:
1411                 /*
1412                  * If sysfs file of new node can't create, cpu on the node
1413                  * can't be hot-added. There is no rollback way now.
1414                  * So, check by BUG_ON() to catch it reluctantly..
1415                  */
1416                 BUG_ON(ret);
1417         }
1418
1419         /* create new memmap entry */
1420         firmware_map_add_hotplug(start, start + size, "System RAM");
1421
1422         /* online pages if requested */
1423         if (online)
1424                 walk_memory_range(PFN_DOWN(start), PFN_UP(start + size - 1),
1425                                   NULL, online_memory_block);
1426
1427         goto out;
1428
1429 error:
1430         /* rollback pgdat allocation and others */
1431         if (new_pgdat)
1432                 rollback_node_hotadd(nid, pgdat);
1433         memblock_remove(start, size);
1434
1435 out:
1436         mem_hotplug_done();
1437         return ret;
1438 }
1439 EXPORT_SYMBOL_GPL(add_memory_resource);
1440
1441 int __ref add_memory(int nid, u64 start, u64 size)
1442 {
1443         struct resource *res;
1444         int ret;
1445
1446         res = register_memory_resource(start, size);
1447         if (IS_ERR(res))
1448                 return PTR_ERR(res);
1449
1450         ret = add_memory_resource(nid, res, memhp_auto_online);
1451         if (ret < 0)
1452                 release_memory_resource(res);
1453         return ret;
1454 }
1455 EXPORT_SYMBOL_GPL(add_memory);
1456
1457 #ifdef CONFIG_MEMORY_HOTREMOVE
1458 /*
1459  * A free page on the buddy free lists (not the per-cpu lists) has PageBuddy
1460  * set and the size of the free page is given by page_order(). Using this,
1461  * the function determines if the pageblock contains only free pages.
1462  * Due to buddy contraints, a free page at least the size of a pageblock will
1463  * be located at the start of the pageblock
1464  */
1465 static inline int pageblock_free(struct page *page)
1466 {
1467         return PageBuddy(page) && page_order(page) >= pageblock_order;
1468 }
1469
1470 /* Return the start of the next active pageblock after a given page */
1471 static struct page *next_active_pageblock(struct page *page)
1472 {
1473         /* Ensure the starting page is pageblock-aligned */
1474         BUG_ON(page_to_pfn(page) & (pageblock_nr_pages - 1));
1475
1476         /* If the entire pageblock is free, move to the end of free page */
1477         if (pageblock_free(page)) {
1478                 int order;
1479                 /* be careful. we don't have locks, page_order can be changed.*/
1480                 order = page_order(page);
1481                 if ((order < MAX_ORDER) && (order >= pageblock_order))
1482                         return page + (1 << order);
1483         }
1484
1485         return page + pageblock_nr_pages;
1486 }
1487
1488 /* Checks if this range of memory is likely to be hot-removable. */
1489 bool is_mem_section_removable(unsigned long start_pfn, unsigned long nr_pages)
1490 {
1491         struct page *page = pfn_to_page(start_pfn);
1492         struct page *end_page = page + nr_pages;
1493
1494         /* Check the starting page of each pageblock within the range */
1495         for (; page < end_page; page = next_active_pageblock(page)) {
1496                 if (!is_pageblock_removable_nolock(page))
1497                         return false;
1498                 cond_resched();
1499         }
1500
1501         /* All pageblocks in the memory block are likely to be hot-removable */
1502         return true;
1503 }
1504
1505 /*
1506  * Confirm all pages in a range [start, end) belong to the same zone.
1507  * When true, return its valid [start, end).
1508  */
1509 int test_pages_in_a_zone(unsigned long start_pfn, unsigned long end_pfn,
1510                          unsigned long *valid_start, unsigned long *valid_end)
1511 {
1512         unsigned long pfn, sec_end_pfn;
1513         unsigned long start, end;
1514         struct zone *zone = NULL;
1515         struct page *page;
1516         int i;
1517         for (pfn = start_pfn, sec_end_pfn = SECTION_ALIGN_UP(start_pfn + 1);
1518              pfn < end_pfn;
1519              pfn = sec_end_pfn, sec_end_pfn += PAGES_PER_SECTION) {
1520                 /* Make sure the memory section is present first */
1521                 if (!present_section_nr(pfn_to_section_nr(pfn)))
1522                         continue;
1523                 for (; pfn < sec_end_pfn && pfn < end_pfn;
1524                      pfn += MAX_ORDER_NR_PAGES) {
1525                         i = 0;
1526                         /* This is just a CONFIG_HOLES_IN_ZONE check.*/
1527                         while ((i < MAX_ORDER_NR_PAGES) &&
1528                                 !pfn_valid_within(pfn + i))
1529                                 i++;
1530                         if (i == MAX_ORDER_NR_PAGES || pfn + i >= end_pfn)
1531                                 continue;
1532                         page = pfn_to_page(pfn + i);
1533                         if (zone && page_zone(page) != zone)
1534                                 return 0;
1535                         if (!zone)
1536                                 start = pfn + i;
1537                         zone = page_zone(page);
1538                         end = pfn + MAX_ORDER_NR_PAGES;
1539                 }
1540         }
1541
1542         if (zone) {
1543                 *valid_start = start;
1544                 *valid_end = min(end, end_pfn);
1545                 return 1;
1546         } else {
1547                 return 0;
1548         }
1549 }
1550
1551 /*
1552  * Scan pfn range [start,end) to find movable/migratable pages (LRU pages,
1553  * non-lru movable pages and hugepages). We scan pfn because it's much
1554  * easier than scanning over linked list. This function returns the pfn
1555  * of the first found movable page if it's found, otherwise 0.
1556  */
1557 static unsigned long scan_movable_pages(unsigned long start, unsigned long end)
1558 {
1559         unsigned long pfn;
1560         struct page *page;
1561         for (pfn = start; pfn < end; pfn++) {
1562                 if (pfn_valid(pfn)) {
1563                         page = pfn_to_page(pfn);
1564                         if (PageLRU(page))
1565                                 return pfn;
1566                         if (__PageMovable(page))
1567                                 return pfn;
1568                         if (PageHuge(page)) {
1569                                 if (page_huge_active(page))
1570                                         return pfn;
1571                                 else
1572                                         pfn = round_up(pfn + 1,
1573                                                 1 << compound_order(page)) - 1;
1574                         }
1575                 }
1576         }
1577         return 0;
1578 }
1579
1580 static struct page *new_node_page(struct page *page, unsigned long private,
1581                 int **result)
1582 {
1583         gfp_t gfp_mask = GFP_USER | __GFP_MOVABLE;
1584         int nid = page_to_nid(page);
1585         nodemask_t nmask = node_states[N_MEMORY];
1586         struct page *new_page = NULL;
1587
1588         /*
1589          * TODO: allocate a destination hugepage from a nearest neighbor node,
1590          * accordance with memory policy of the user process if possible. For
1591          * now as a simple work-around, we use the next node for destination.
1592          */
1593         if (PageHuge(page))
1594                 return alloc_huge_page_node(page_hstate(compound_head(page)),
1595                                         next_node_in(nid, nmask));
1596
1597         node_clear(nid, nmask);
1598
1599         if (PageHighMem(page)
1600             || (zone_idx(page_zone(page)) == ZONE_MOVABLE))
1601                 gfp_mask |= __GFP_HIGHMEM;
1602
1603         if (!nodes_empty(nmask))
1604                 new_page = __alloc_pages_nodemask(gfp_mask, 0,
1605                                         node_zonelist(nid, gfp_mask), &nmask);
1606         if (!new_page)
1607                 new_page = __alloc_pages(gfp_mask, 0,
1608                                         node_zonelist(nid, gfp_mask));
1609
1610         return new_page;
1611 }
1612
1613 #define NR_OFFLINE_AT_ONCE_PAGES        (256)
1614 static int
1615 do_migrate_range(unsigned long start_pfn, unsigned long end_pfn)
1616 {
1617         unsigned long pfn;
1618         struct page *page;
1619         int move_pages = NR_OFFLINE_AT_ONCE_PAGES;
1620         int not_managed = 0;
1621         int ret = 0;
1622         LIST_HEAD(source);
1623
1624         for (pfn = start_pfn; pfn < end_pfn && move_pages > 0; pfn++) {
1625                 if (!pfn_valid(pfn))
1626                         continue;
1627                 page = pfn_to_page(pfn);
1628
1629                 if (PageHuge(page)) {
1630                         struct page *head = compound_head(page);
1631                         pfn = page_to_pfn(head) + (1<<compound_order(head)) - 1;
1632                         if (compound_order(head) > PFN_SECTION_SHIFT) {
1633                                 ret = -EBUSY;
1634                                 break;
1635                         }
1636                         if (isolate_huge_page(page, &source))
1637                                 move_pages -= 1 << compound_order(head);
1638                         continue;
1639                 }
1640
1641                 if (!get_page_unless_zero(page))
1642                         continue;
1643                 /*
1644                  * We can skip free pages. And we can deal with pages on
1645                  * LRU and non-lru movable pages.
1646                  */
1647                 if (PageLRU(page))
1648                         ret = isolate_lru_page(page);
1649                 else
1650                         ret = isolate_movable_page(page, ISOLATE_UNEVICTABLE);
1651                 if (!ret) { /* Success */
1652                         put_page(page);
1653                         list_add_tail(&page->lru, &source);
1654                         move_pages--;
1655                         if (!__PageMovable(page))
1656                                 inc_node_page_state(page, NR_ISOLATED_ANON +
1657                                                     page_is_file_cache(page));
1658
1659                 } else {
1660 #ifdef CONFIG_DEBUG_VM
1661                         pr_alert("failed to isolate pfn %lx\n", pfn);
1662                         dump_page(page, "isolation failed");
1663 #endif
1664                         put_page(page);
1665                         /* Because we don't have big zone->lock. we should
1666                            check this again here. */
1667                         if (page_count(page)) {
1668                                 not_managed++;
1669                                 ret = -EBUSY;
1670                                 break;
1671                         }
1672                 }
1673         }
1674         if (!list_empty(&source)) {
1675                 if (not_managed) {
1676                         putback_movable_pages(&source);
1677                         goto out;
1678                 }
1679
1680                 /* Allocate a new page from the nearest neighbor node */
1681                 ret = migrate_pages(&source, new_node_page, NULL, 0,
1682                                         MIGRATE_SYNC, MR_MEMORY_HOTPLUG);
1683                 if (ret)
1684                         putback_movable_pages(&source);
1685         }
1686 out:
1687         return ret;
1688 }
1689
1690 /*
1691  * remove from free_area[] and mark all as Reserved.
1692  */
1693 static int
1694 offline_isolated_pages_cb(unsigned long start, unsigned long nr_pages,
1695                         void *data)
1696 {
1697         __offline_isolated_pages(start, start + nr_pages);
1698         return 0;
1699 }
1700
1701 static void
1702 offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
1703 {
1704         walk_system_ram_range(start_pfn, end_pfn - start_pfn, NULL,
1705                                 offline_isolated_pages_cb);
1706 }
1707
1708 /*
1709  * Check all pages in range, recoreded as memory resource, are isolated.
1710  */
1711 static int
1712 check_pages_isolated_cb(unsigned long start_pfn, unsigned long nr_pages,
1713                         void *data)
1714 {
1715         int ret;
1716         long offlined = *(long *)data;
1717         ret = test_pages_isolated(start_pfn, start_pfn + nr_pages, true);
1718         offlined = nr_pages;
1719         if (!ret)
1720                 *(long *)data += offlined;
1721         return ret;
1722 }
1723
1724 static long
1725 check_pages_isolated(unsigned long start_pfn, unsigned long end_pfn)
1726 {
1727         long offlined = 0;
1728         int ret;
1729
1730         ret = walk_system_ram_range(start_pfn, end_pfn - start_pfn, &offlined,
1731                         check_pages_isolated_cb);
1732         if (ret < 0)
1733                 offlined = (long)ret;
1734         return offlined;
1735 }
1736
1737 #ifdef CONFIG_MOVABLE_NODE
1738 /*
1739  * When CONFIG_MOVABLE_NODE, we permit offlining of a node which doesn't have
1740  * normal memory.
1741  */
1742 static bool can_offline_normal(struct zone *zone, unsigned long nr_pages)
1743 {
1744         return true;
1745 }
1746 #else /* CONFIG_MOVABLE_NODE */
1747 /* ensure the node has NORMAL memory if it is still online */
1748 static bool can_offline_normal(struct zone *zone, unsigned long nr_pages)
1749 {
1750         struct pglist_data *pgdat = zone->zone_pgdat;
1751         unsigned long present_pages = 0;
1752         enum zone_type zt;
1753
1754         for (zt = 0; zt <= ZONE_NORMAL; zt++)
1755                 present_pages += pgdat->node_zones[zt].present_pages;
1756
1757         if (present_pages > nr_pages)
1758                 return true;
1759
1760         present_pages = 0;
1761         for (; zt <= ZONE_MOVABLE; zt++)
1762                 present_pages += pgdat->node_zones[zt].present_pages;
1763
1764         /*
1765          * we can't offline the last normal memory until all
1766          * higher memory is offlined.
1767          */
1768         return present_pages == 0;
1769 }
1770 #endif /* CONFIG_MOVABLE_NODE */
1771
1772 static int __init cmdline_parse_movable_node(char *p)
1773 {
1774 #ifdef CONFIG_MOVABLE_NODE
1775         movable_node_enabled = true;
1776 #else
1777         pr_warn("movable_node option not supported\n");
1778 #endif
1779         return 0;
1780 }
1781 early_param("movable_node", cmdline_parse_movable_node);
1782
1783 /* check which state of node_states will be changed when offline memory */
1784 static void node_states_check_changes_offline(unsigned long nr_pages,
1785                 struct zone *zone, struct memory_notify *arg)
1786 {
1787         struct pglist_data *pgdat = zone->zone_pgdat;
1788         unsigned long present_pages = 0;
1789         enum zone_type zt, zone_last = ZONE_NORMAL;
1790
1791         /*
1792          * If we have HIGHMEM or movable node, node_states[N_NORMAL_MEMORY]
1793          * contains nodes which have zones of 0...ZONE_NORMAL,
1794          * set zone_last to ZONE_NORMAL.
1795          *
1796          * If we don't have HIGHMEM nor movable node,
1797          * node_states[N_NORMAL_MEMORY] contains nodes which have zones of
1798          * 0...ZONE_MOVABLE, set zone_last to ZONE_MOVABLE.
1799          */
1800         if (N_MEMORY == N_NORMAL_MEMORY)
1801                 zone_last = ZONE_MOVABLE;
1802
1803         /*
1804          * check whether node_states[N_NORMAL_MEMORY] will be changed.
1805          * If the memory to be offline is in a zone of 0...zone_last,
1806          * and it is the last present memory, 0...zone_last will
1807          * become empty after offline , thus we can determind we will
1808          * need to clear the node from node_states[N_NORMAL_MEMORY].
1809          */
1810         for (zt = 0; zt <= zone_last; zt++)
1811                 present_pages += pgdat->node_zones[zt].present_pages;
1812         if (zone_idx(zone) <= zone_last && nr_pages >= present_pages)
1813                 arg->status_change_nid_normal = zone_to_nid(zone);
1814         else
1815                 arg->status_change_nid_normal = -1;
1816
1817 #ifdef CONFIG_HIGHMEM
1818         /*
1819          * If we have movable node, node_states[N_HIGH_MEMORY]
1820          * contains nodes which have zones of 0...ZONE_HIGHMEM,
1821          * set zone_last to ZONE_HIGHMEM.
1822          *
1823          * If we don't have movable node, node_states[N_NORMAL_MEMORY]
1824          * contains nodes which have zones of 0...ZONE_MOVABLE,
1825          * set zone_last to ZONE_MOVABLE.
1826          */
1827         zone_last = ZONE_HIGHMEM;
1828         if (N_MEMORY == N_HIGH_MEMORY)
1829                 zone_last = ZONE_MOVABLE;
1830
1831         for (; zt <= zone_last; zt++)
1832                 present_pages += pgdat->node_zones[zt].present_pages;
1833         if (zone_idx(zone) <= zone_last && nr_pages >= present_pages)
1834                 arg->status_change_nid_high = zone_to_nid(zone);
1835         else
1836                 arg->status_change_nid_high = -1;
1837 #else
1838         arg->status_change_nid_high = arg->status_change_nid_normal;
1839 #endif
1840
1841         /*
1842          * node_states[N_HIGH_MEMORY] contains nodes which have 0...ZONE_MOVABLE
1843          */
1844         zone_last = ZONE_MOVABLE;
1845
1846         /*
1847          * check whether node_states[N_HIGH_MEMORY] will be changed
1848          * If we try to offline the last present @nr_pages from the node,
1849          * we can determind we will need to clear the node from
1850          * node_states[N_HIGH_MEMORY].
1851          */
1852         for (; zt <= zone_last; zt++)
1853                 present_pages += pgdat->node_zones[zt].present_pages;
1854         if (nr_pages >= present_pages)
1855                 arg->status_change_nid = zone_to_nid(zone);
1856         else
1857                 arg->status_change_nid = -1;
1858 }
1859
1860 static void node_states_clear_node(int node, struct memory_notify *arg)
1861 {
1862         if (arg->status_change_nid_normal >= 0)
1863                 node_clear_state(node, N_NORMAL_MEMORY);
1864
1865         if ((N_MEMORY != N_NORMAL_MEMORY) &&
1866             (arg->status_change_nid_high >= 0))
1867                 node_clear_state(node, N_HIGH_MEMORY);
1868
1869         if ((N_MEMORY != N_HIGH_MEMORY) &&
1870             (arg->status_change_nid >= 0))
1871                 node_clear_state(node, N_MEMORY);
1872 }
1873
1874 static int __ref __offline_pages(unsigned long start_pfn,
1875                   unsigned long end_pfn, unsigned long timeout)
1876 {
1877         unsigned long pfn, nr_pages, expire;
1878         long offlined_pages;
1879         int ret, drain, retry_max, node;
1880         unsigned long flags;
1881         unsigned long valid_start, valid_end;
1882         struct zone *zone;
1883         struct memory_notify arg;
1884
1885         /* at least, alignment against pageblock is necessary */
1886         if (!IS_ALIGNED(start_pfn, pageblock_nr_pages))
1887                 return -EINVAL;
1888         if (!IS_ALIGNED(end_pfn, pageblock_nr_pages))
1889                 return -EINVAL;
1890         /* This makes hotplug much easier...and readable.
1891            we assume this for now. .*/
1892         if (!test_pages_in_a_zone(start_pfn, end_pfn, &valid_start, &valid_end))
1893                 return -EINVAL;
1894
1895         zone = page_zone(pfn_to_page(valid_start));
1896         node = zone_to_nid(zone);
1897         nr_pages = end_pfn - start_pfn;
1898
1899         if (zone_idx(zone) <= ZONE_NORMAL && !can_offline_normal(zone, nr_pages))
1900                 return -EINVAL;
1901
1902         /* set above range as isolated */
1903         ret = start_isolate_page_range(start_pfn, end_pfn,
1904                                        MIGRATE_MOVABLE, true);
1905         if (ret)
1906                 return ret;
1907
1908         arg.start_pfn = start_pfn;
1909         arg.nr_pages = nr_pages;
1910         node_states_check_changes_offline(nr_pages, zone, &arg);
1911
1912         ret = memory_notify(MEM_GOING_OFFLINE, &arg);
1913         ret = notifier_to_errno(ret);
1914         if (ret)
1915                 goto failed_removal;
1916
1917         pfn = start_pfn;
1918         expire = jiffies + timeout;
1919         drain = 0;
1920         retry_max = 5;
1921 repeat:
1922         /* start memory hot removal */
1923         ret = -EAGAIN;
1924         if (time_after(jiffies, expire))
1925                 goto failed_removal;
1926         ret = -EINTR;
1927         if (signal_pending(current))
1928                 goto failed_removal;
1929         ret = 0;
1930         if (drain) {
1931                 lru_add_drain_all();
1932                 cond_resched();
1933                 drain_all_pages(zone);
1934         }
1935
1936         pfn = scan_movable_pages(start_pfn, end_pfn);
1937         if (pfn) { /* We have movable pages */
1938                 ret = do_migrate_range(pfn, end_pfn);
1939                 if (!ret) {
1940                         drain = 1;
1941                         goto repeat;
1942                 } else {
1943                         if (ret < 0)
1944                                 if (--retry_max == 0)
1945                                         goto failed_removal;
1946                         yield();
1947                         drain = 1;
1948                         goto repeat;
1949                 }
1950         }
1951         /* drain all zone's lru pagevec, this is asynchronous... */
1952         lru_add_drain_all();
1953         yield();
1954         /* drain pcp pages, this is synchronous. */
1955         drain_all_pages(zone);
1956         /*
1957          * dissolve free hugepages in the memory block before doing offlining
1958          * actually in order to make hugetlbfs's object counting consistent.
1959          */
1960         ret = dissolve_free_huge_pages(start_pfn, end_pfn);
1961         if (ret)
1962                 goto failed_removal;
1963         /* check again */
1964         offlined_pages = check_pages_isolated(start_pfn, end_pfn);
1965         if (offlined_pages < 0) {
1966                 ret = -EBUSY;
1967                 goto failed_removal;
1968         }
1969         pr_info("Offlined Pages %ld\n", offlined_pages);
1970         /* Ok, all of our target is isolated.
1971            We cannot do rollback at this point. */
1972         offline_isolated_pages(start_pfn, end_pfn);
1973         /* reset pagetype flags and makes migrate type to be MOVABLE */
1974         undo_isolate_page_range(start_pfn, end_pfn, MIGRATE_MOVABLE);
1975         /* removal success */
1976         adjust_managed_page_count(pfn_to_page(start_pfn), -offlined_pages);
1977         zone->present_pages -= offlined_pages;
1978
1979         pgdat_resize_lock(zone->zone_pgdat, &flags);
1980         zone->zone_pgdat->node_present_pages -= offlined_pages;
1981         pgdat_resize_unlock(zone->zone_pgdat, &flags);
1982
1983         init_per_zone_wmark_min();
1984
1985         if (!populated_zone(zone)) {
1986                 zone_pcp_reset(zone);
1987                 mutex_lock(&zonelists_mutex);
1988                 build_all_zonelists(NULL, NULL);
1989                 mutex_unlock(&zonelists_mutex);
1990         } else
1991                 zone_pcp_update(zone);
1992
1993         node_states_clear_node(node, &arg);
1994         if (arg.status_change_nid >= 0) {
1995                 kswapd_stop(node);
1996                 kcompactd_stop(node);
1997         }
1998
1999         vm_total_pages = nr_free_pagecache_pages();
2000         writeback_set_ratelimit();
2001
2002         memory_notify(MEM_OFFLINE, &arg);
2003         return 0;
2004
2005 failed_removal:
2006         pr_debug("memory offlining [mem %#010llx-%#010llx] failed\n",
2007                  (unsigned long long) start_pfn << PAGE_SHIFT,
2008                  ((unsigned long long) end_pfn << PAGE_SHIFT) - 1);
2009         memory_notify(MEM_CANCEL_OFFLINE, &arg);
2010         /* pushback to free area */
2011         undo_isolate_page_range(start_pfn, end_pfn, MIGRATE_MOVABLE);
2012         return ret;
2013 }
2014
2015 /* Must be protected by mem_hotplug_begin() */
2016 int offline_pages(unsigned long start_pfn, unsigned long nr_pages)
2017 {
2018         return __offline_pages(start_pfn, start_pfn + nr_pages, 120 * HZ);
2019 }
2020 #endif /* CONFIG_MEMORY_HOTREMOVE */
2021
2022 /**
2023  * walk_memory_range - walks through all mem sections in [start_pfn, end_pfn)
2024  * @start_pfn: start pfn of the memory range
2025  * @end_pfn: end pfn of the memory range
2026  * @arg: argument passed to func
2027  * @func: callback for each memory section walked
2028  *
2029  * This function walks through all present mem sections in range
2030  * [start_pfn, end_pfn) and call func on each mem section.
2031  *
2032  * Returns the return value of func.
2033  */
2034 int walk_memory_range(unsigned long start_pfn, unsigned long end_pfn,
2035                 void *arg, int (*func)(struct memory_block *, void *))
2036 {
2037         struct memory_block *mem = NULL;
2038         struct mem_section *section;
2039         unsigned long pfn, section_nr;
2040         int ret;
2041
2042         for (pfn = start_pfn; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
2043                 section_nr = pfn_to_section_nr(pfn);
2044                 if (!present_section_nr(section_nr))
2045                         continue;
2046
2047                 section = __nr_to_section(section_nr);
2048                 /* same memblock? */
2049                 if (mem)
2050                         if ((section_nr >= mem->start_section_nr) &&
2051                             (section_nr <= mem->end_section_nr))
2052                                 continue;
2053
2054                 mem = find_memory_block_hinted(section, mem);
2055                 if (!mem)
2056                         continue;
2057
2058                 ret = func(mem, arg);
2059                 if (ret) {
2060                         kobject_put(&mem->dev.kobj);
2061                         return ret;
2062                 }
2063         }
2064
2065         if (mem)
2066                 kobject_put(&mem->dev.kobj);
2067
2068         return 0;
2069 }
2070
2071 #ifdef CONFIG_MEMORY_HOTREMOVE
2072 static int check_memblock_offlined_cb(struct memory_block *mem, void *arg)
2073 {
2074         int ret = !is_memblock_offlined(mem);
2075
2076         if (unlikely(ret)) {
2077                 phys_addr_t beginpa, endpa;
2078
2079                 beginpa = PFN_PHYS(section_nr_to_pfn(mem->start_section_nr));
2080                 endpa = PFN_PHYS(section_nr_to_pfn(mem->end_section_nr + 1))-1;
2081                 pr_warn("removing memory fails, because memory [%pa-%pa] is onlined\n",
2082                         &beginpa, &endpa);
2083         }
2084
2085         return ret;
2086 }
2087
2088 static int check_cpu_on_node(pg_data_t *pgdat)
2089 {
2090         int cpu;
2091
2092         for_each_present_cpu(cpu) {
2093                 if (cpu_to_node(cpu) == pgdat->node_id)
2094                         /*
2095                          * the cpu on this node isn't removed, and we can't
2096                          * offline this node.
2097                          */
2098                         return -EBUSY;
2099         }
2100
2101         return 0;
2102 }
2103
2104 static void unmap_cpu_on_node(pg_data_t *pgdat)
2105 {
2106 #ifdef CONFIG_ACPI_NUMA
2107         int cpu;
2108
2109         for_each_possible_cpu(cpu)
2110                 if (cpu_to_node(cpu) == pgdat->node_id)
2111                         numa_clear_node(cpu);
2112 #endif
2113 }
2114
2115 static int check_and_unmap_cpu_on_node(pg_data_t *pgdat)
2116 {
2117         int ret;
2118
2119         ret = check_cpu_on_node(pgdat);
2120         if (ret)
2121                 return ret;
2122
2123         /*
2124          * the node will be offlined when we come here, so we can clear
2125          * the cpu_to_node() now.
2126          */
2127
2128         unmap_cpu_on_node(pgdat);
2129         return 0;
2130 }
2131
2132 /**
2133  * try_offline_node
2134  *
2135  * Offline a node if all memory sections and cpus of the node are removed.
2136  *
2137  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
2138  * and online/offline operations before this call.
2139  */
2140 void try_offline_node(int nid)
2141 {
2142         pg_data_t *pgdat = NODE_DATA(nid);
2143         unsigned long start_pfn = pgdat->node_start_pfn;
2144         unsigned long end_pfn = start_pfn + pgdat->node_spanned_pages;
2145         unsigned long pfn;
2146
2147         for (pfn = start_pfn; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
2148                 unsigned long section_nr = pfn_to_section_nr(pfn);
2149
2150                 if (!present_section_nr(section_nr))
2151                         continue;
2152
2153                 if (pfn_to_nid(pfn) != nid)
2154                         continue;
2155
2156                 /*
2157                  * some memory sections of this node are not removed, and we
2158                  * can't offline node now.
2159                  */
2160                 return;
2161         }
2162
2163         if (check_and_unmap_cpu_on_node(pgdat))
2164                 return;
2165
2166         /*
2167          * all memory/cpu of this node are removed, we can offline this
2168          * node now.
2169          */
2170         node_set_offline(nid);
2171         unregister_one_node(nid);
2172 }
2173 EXPORT_SYMBOL(try_offline_node);
2174
2175 /**
2176  * remove_memory
2177  *
2178  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
2179  * and online/offline operations before this call, as required by
2180  * try_offline_node().
2181  */
2182 void __ref remove_memory(int nid, u64 start, u64 size)
2183 {
2184         int ret;
2185
2186         BUG_ON(check_hotplug_memory_range(start, size));
2187
2188         mem_hotplug_begin();
2189
2190         /*
2191          * All memory blocks must be offlined before removing memory.  Check
2192          * whether all memory blocks in question are offline and trigger a BUG()
2193          * if this is not the case.
2194          */
2195         ret = walk_memory_range(PFN_DOWN(start), PFN_UP(start + size - 1), NULL,
2196                                 check_memblock_offlined_cb);
2197         if (ret)
2198                 BUG();
2199
2200         /* remove memmap entry */
2201         firmware_map_remove(start, start + size, "System RAM");
2202         memblock_free(start, size);
2203         memblock_remove(start, size);
2204
2205         arch_remove_memory(start, size);
2206
2207         try_offline_node(nid);
2208
2209         mem_hotplug_done();
2210 }
2211 EXPORT_SYMBOL_GPL(remove_memory);
2212 #endif /* CONFIG_MEMORY_HOTREMOVE */