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