OSDN Git Service

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