xref: /openbmc/linux/mm/memory_hotplug.c (revision a08a2ae3461383c2d50d0997dcc6cd1dd1fefb08)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
23947be19SDave Hansen /*
33947be19SDave Hansen  *  linux/mm/memory_hotplug.c
43947be19SDave Hansen  *
53947be19SDave Hansen  *  Copyright (C)
63947be19SDave Hansen  */
73947be19SDave Hansen 
83947be19SDave Hansen #include <linux/stddef.h>
93947be19SDave Hansen #include <linux/mm.h>
10174cd4b1SIngo Molnar #include <linux/sched/signal.h>
113947be19SDave Hansen #include <linux/swap.h>
123947be19SDave Hansen #include <linux/interrupt.h>
133947be19SDave Hansen #include <linux/pagemap.h>
143947be19SDave Hansen #include <linux/compiler.h>
15b95f1b31SPaul Gortmaker #include <linux/export.h>
163947be19SDave Hansen #include <linux/pagevec.h>
172d1d43f6SChandra Seetharaman #include <linux/writeback.h>
183947be19SDave Hansen #include <linux/slab.h>
193947be19SDave Hansen #include <linux/sysctl.h>
203947be19SDave Hansen #include <linux/cpu.h>
213947be19SDave Hansen #include <linux/memory.h>
224b94ffdcSDan Williams #include <linux/memremap.h>
233947be19SDave Hansen #include <linux/memory_hotplug.h>
243947be19SDave Hansen #include <linux/highmem.h>
253947be19SDave Hansen #include <linux/vmalloc.h>
260a547039SKAMEZAWA Hiroyuki #include <linux/ioport.h>
270c0e6195SKAMEZAWA Hiroyuki #include <linux/delay.h>
280c0e6195SKAMEZAWA Hiroyuki #include <linux/migrate.h>
290c0e6195SKAMEZAWA Hiroyuki #include <linux/page-isolation.h>
3071088785SBadari Pulavarty #include <linux/pfn.h>
316ad696d2SAndi Kleen #include <linux/suspend.h>
326d9c285aSKOSAKI Motohiro #include <linux/mm_inline.h>
33d96ae530Sakpm@linux-foundation.org #include <linux/firmware-map.h>
3460a5a19eSTang Chen #include <linux/stop_machine.h>
35c8721bbbSNaoya Horiguchi #include <linux/hugetlb.h>
36c5320926STang Chen #include <linux/memblock.h>
37698b1b30SVlastimil Babka #include <linux/compaction.h>
38b15c8726SMichal Hocko #include <linux/rmap.h>
393947be19SDave Hansen 
403947be19SDave Hansen #include <asm/tlbflush.h>
413947be19SDave Hansen 
421e5ad9a3SAdrian Bunk #include "internal.h"
43e900a918SDan Williams #include "shuffle.h"
441e5ad9a3SAdrian Bunk 
45*a08a2ae3SOscar Salvador static bool memmap_on_memory;
46*a08a2ae3SOscar Salvador 
479d0ad8caSDaniel Kiper /*
489d0ad8caSDaniel Kiper  * online_page_callback contains pointer to current page onlining function.
499d0ad8caSDaniel Kiper  * Initially it is generic_online_page(). If it is required it could be
509d0ad8caSDaniel Kiper  * changed by calling set_online_page_callback() for callback registration
519d0ad8caSDaniel Kiper  * and restore_online_page_callback() for generic callback restore.
529d0ad8caSDaniel Kiper  */
539d0ad8caSDaniel Kiper 
549d0ad8caSDaniel Kiper static online_page_callback_t online_page_callback = generic_online_page;
55bfc8c901SVladimir Davydov static DEFINE_MUTEX(online_page_callback_lock);
569d0ad8caSDaniel Kiper 
573f906ba2SThomas Gleixner DEFINE_STATIC_PERCPU_RWSEM(mem_hotplug_lock);
5820d6c96bSKOSAKI Motohiro 
593f906ba2SThomas Gleixner void get_online_mems(void)
603f906ba2SThomas Gleixner {
613f906ba2SThomas Gleixner 	percpu_down_read(&mem_hotplug_lock);
623f906ba2SThomas Gleixner }
63bfc8c901SVladimir Davydov 
643f906ba2SThomas Gleixner void put_online_mems(void)
653f906ba2SThomas Gleixner {
663f906ba2SThomas Gleixner 	percpu_up_read(&mem_hotplug_lock);
673f906ba2SThomas Gleixner }
68bfc8c901SVladimir Davydov 
694932381eSMichal Hocko bool movable_node_enabled = false;
704932381eSMichal Hocko 
718604d9e5SVitaly Kuznetsov #ifndef CONFIG_MEMORY_HOTPLUG_DEFAULT_ONLINE
721adf8b46SAnshuman Khandual int mhp_default_online_type = MMOP_OFFLINE;
738604d9e5SVitaly Kuznetsov #else
741adf8b46SAnshuman Khandual int mhp_default_online_type = MMOP_ONLINE;
758604d9e5SVitaly Kuznetsov #endif
7631bc3858SVitaly Kuznetsov 
7786dd995dSVitaly Kuznetsov static int __init setup_memhp_default_state(char *str)
7886dd995dSVitaly Kuznetsov {
791adf8b46SAnshuman Khandual 	const int online_type = mhp_online_type_from_str(str);
805f47adf7SDavid Hildenbrand 
815f47adf7SDavid Hildenbrand 	if (online_type >= 0)
821adf8b46SAnshuman Khandual 		mhp_default_online_type = online_type;
8386dd995dSVitaly Kuznetsov 
8486dd995dSVitaly Kuznetsov 	return 1;
8586dd995dSVitaly Kuznetsov }
8686dd995dSVitaly Kuznetsov __setup("memhp_default_state=", setup_memhp_default_state);
8786dd995dSVitaly Kuznetsov 
8830467e0bSDavid Rientjes void mem_hotplug_begin(void)
89bfc8c901SVladimir Davydov {
903f906ba2SThomas Gleixner 	cpus_read_lock();
913f906ba2SThomas Gleixner 	percpu_down_write(&mem_hotplug_lock);
92bfc8c901SVladimir Davydov }
93bfc8c901SVladimir Davydov 
9430467e0bSDavid Rientjes void mem_hotplug_done(void)
95bfc8c901SVladimir Davydov {
963f906ba2SThomas Gleixner 	percpu_up_write(&mem_hotplug_lock);
973f906ba2SThomas Gleixner 	cpus_read_unlock();
98bfc8c901SVladimir Davydov }
9920d6c96bSKOSAKI Motohiro 
100357b4da5SJuergen Gross u64 max_mem_size = U64_MAX;
101357b4da5SJuergen Gross 
10245e0b78bSKeith Mannthey /* add this memory to iomem resource */
1037b7b2721SDavid Hildenbrand static struct resource *register_memory_resource(u64 start, u64 size,
1047b7b2721SDavid Hildenbrand 						 const char *resource_name)
10545e0b78bSKeith Mannthey {
1062794129eSDave Hansen 	struct resource *res;
1072794129eSDave Hansen 	unsigned long flags =  IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
1087b7b2721SDavid Hildenbrand 
1097b7b2721SDavid Hildenbrand 	if (strcmp(resource_name, "System RAM"))
1107cf603d1SDavid Hildenbrand 		flags |= IORESOURCE_SYSRAM_DRIVER_MANAGED;
111357b4da5SJuergen Gross 
112bca3feaaSAnshuman Khandual 	if (!mhp_range_allowed(start, size, true))
113bca3feaaSAnshuman Khandual 		return ERR_PTR(-E2BIG);
114bca3feaaSAnshuman Khandual 
115f3cd4c86SBaoquan He 	/*
116f3cd4c86SBaoquan He 	 * Make sure value parsed from 'mem=' only restricts memory adding
117f3cd4c86SBaoquan He 	 * while booting, so that memory hotplug won't be impacted. Please
118f3cd4c86SBaoquan He 	 * refer to document of 'mem=' in kernel-parameters.txt for more
119f3cd4c86SBaoquan He 	 * details.
120f3cd4c86SBaoquan He 	 */
121f3cd4c86SBaoquan He 	if (start + size > max_mem_size && system_state < SYSTEM_RUNNING)
122357b4da5SJuergen Gross 		return ERR_PTR(-E2BIG);
123357b4da5SJuergen Gross 
1242794129eSDave Hansen 	/*
1252794129eSDave Hansen 	 * Request ownership of the new memory range.  This might be
1262794129eSDave Hansen 	 * a child of an existing resource that was present but
1272794129eSDave Hansen 	 * not marked as busy.
1282794129eSDave Hansen 	 */
1292794129eSDave Hansen 	res = __request_region(&iomem_resource, start, size,
1302794129eSDave Hansen 			       resource_name, flags);
13145e0b78bSKeith Mannthey 
1322794129eSDave Hansen 	if (!res) {
1332794129eSDave Hansen 		pr_debug("Unable to reserve System RAM region: %016llx->%016llx\n",
1342794129eSDave Hansen 				start, start + size);
1356f754ba4SVitaly Kuznetsov 		return ERR_PTR(-EEXIST);
13645e0b78bSKeith Mannthey 	}
13745e0b78bSKeith Mannthey 	return res;
13845e0b78bSKeith Mannthey }
13945e0b78bSKeith Mannthey 
14045e0b78bSKeith Mannthey static void release_memory_resource(struct resource *res)
14145e0b78bSKeith Mannthey {
14245e0b78bSKeith Mannthey 	if (!res)
14345e0b78bSKeith Mannthey 		return;
14445e0b78bSKeith Mannthey 	release_resource(res);
14545e0b78bSKeith Mannthey 	kfree(res);
14645e0b78bSKeith Mannthey }
14745e0b78bSKeith Mannthey 
14853947027SKeith Mannthey #ifdef CONFIG_MEMORY_HOTPLUG_SPARSE
14946723bfaSYasuaki Ishimatsu void get_page_bootmem(unsigned long info,  struct page *page,
1505f24ce5fSAndrea Arcangeli 		      unsigned long type)
15104753278SYasunori Goto {
152ddffe98dSYasuaki Ishimatsu 	page->freelist = (void *)type;
15304753278SYasunori Goto 	SetPagePrivate(page);
15404753278SYasunori Goto 	set_page_private(page, info);
155fe896d18SJoonsoo Kim 	page_ref_inc(page);
15604753278SYasunori Goto }
15704753278SYasunori Goto 
158170a5a7eSJiang Liu void put_page_bootmem(struct page *page)
15904753278SYasunori Goto {
1605f24ce5fSAndrea Arcangeli 	unsigned long type;
16104753278SYasunori Goto 
162ddffe98dSYasuaki Ishimatsu 	type = (unsigned long) page->freelist;
1635f24ce5fSAndrea Arcangeli 	BUG_ON(type < MEMORY_HOTPLUG_MIN_BOOTMEM_TYPE ||
1645f24ce5fSAndrea Arcangeli 	       type > MEMORY_HOTPLUG_MAX_BOOTMEM_TYPE);
16504753278SYasunori Goto 
166fe896d18SJoonsoo Kim 	if (page_ref_dec_return(page) == 1) {
167ddffe98dSYasuaki Ishimatsu 		page->freelist = NULL;
16804753278SYasunori Goto 		ClearPagePrivate(page);
16904753278SYasunori Goto 		set_page_private(page, 0);
1705f24ce5fSAndrea Arcangeli 		INIT_LIST_HEAD(&page->lru);
171170a5a7eSJiang Liu 		free_reserved_page(page);
17204753278SYasunori Goto 	}
17304753278SYasunori Goto }
17404753278SYasunori Goto 
17546723bfaSYasuaki Ishimatsu #ifdef CONFIG_HAVE_BOOTMEM_INFO_NODE
17646723bfaSYasuaki Ishimatsu #ifndef CONFIG_SPARSEMEM_VMEMMAP
177d92bc318SAdrian Bunk static void register_page_bootmem_info_section(unsigned long start_pfn)
17804753278SYasunori Goto {
179f1eca35aSDan Williams 	unsigned long mapsize, section_nr, i;
18004753278SYasunori Goto 	struct mem_section *ms;
18104753278SYasunori Goto 	struct page *page, *memmap;
182f1eca35aSDan Williams 	struct mem_section_usage *usage;
18304753278SYasunori Goto 
18404753278SYasunori Goto 	section_nr = pfn_to_section_nr(start_pfn);
18504753278SYasunori Goto 	ms = __nr_to_section(section_nr);
18604753278SYasunori Goto 
18704753278SYasunori Goto 	/* Get section's memmap address */
18804753278SYasunori Goto 	memmap = sparse_decode_mem_map(ms->section_mem_map, section_nr);
18904753278SYasunori Goto 
19004753278SYasunori Goto 	/*
19104753278SYasunori Goto 	 * Get page for the memmap's phys address
19204753278SYasunori Goto 	 * XXX: need more consideration for sparse_vmemmap...
19304753278SYasunori Goto 	 */
19404753278SYasunori Goto 	page = virt_to_page(memmap);
19504753278SYasunori Goto 	mapsize = sizeof(struct page) * PAGES_PER_SECTION;
19604753278SYasunori Goto 	mapsize = PAGE_ALIGN(mapsize) >> PAGE_SHIFT;
19704753278SYasunori Goto 
19804753278SYasunori Goto 	/* remember memmap's page */
19904753278SYasunori Goto 	for (i = 0; i < mapsize; i++, page++)
20004753278SYasunori Goto 		get_page_bootmem(section_nr, page, SECTION_INFO);
20104753278SYasunori Goto 
202f1eca35aSDan Williams 	usage = ms->usage;
203f1eca35aSDan Williams 	page = virt_to_page(usage);
20404753278SYasunori Goto 
205f1eca35aSDan Williams 	mapsize = PAGE_ALIGN(mem_section_usage_size()) >> PAGE_SHIFT;
20604753278SYasunori Goto 
20704753278SYasunori Goto 	for (i = 0; i < mapsize; i++, page++)
208af370fb8SYasunori Goto 		get_page_bootmem(section_nr, page, MIX_SECTION_INFO);
20904753278SYasunori Goto 
21004753278SYasunori Goto }
21146723bfaSYasuaki Ishimatsu #else /* CONFIG_SPARSEMEM_VMEMMAP */
21246723bfaSYasuaki Ishimatsu static void register_page_bootmem_info_section(unsigned long start_pfn)
21346723bfaSYasuaki Ishimatsu {
214f1eca35aSDan Williams 	unsigned long mapsize, section_nr, i;
21546723bfaSYasuaki Ishimatsu 	struct mem_section *ms;
21646723bfaSYasuaki Ishimatsu 	struct page *page, *memmap;
217f1eca35aSDan Williams 	struct mem_section_usage *usage;
21846723bfaSYasuaki Ishimatsu 
21946723bfaSYasuaki Ishimatsu 	section_nr = pfn_to_section_nr(start_pfn);
22046723bfaSYasuaki Ishimatsu 	ms = __nr_to_section(section_nr);
22146723bfaSYasuaki Ishimatsu 
22246723bfaSYasuaki Ishimatsu 	memmap = sparse_decode_mem_map(ms->section_mem_map, section_nr);
22346723bfaSYasuaki Ishimatsu 
22446723bfaSYasuaki Ishimatsu 	register_page_bootmem_memmap(section_nr, memmap, PAGES_PER_SECTION);
22546723bfaSYasuaki Ishimatsu 
226f1eca35aSDan Williams 	usage = ms->usage;
227f1eca35aSDan Williams 	page = virt_to_page(usage);
22846723bfaSYasuaki Ishimatsu 
229f1eca35aSDan Williams 	mapsize = PAGE_ALIGN(mem_section_usage_size()) >> PAGE_SHIFT;
23046723bfaSYasuaki Ishimatsu 
23146723bfaSYasuaki Ishimatsu 	for (i = 0; i < mapsize; i++, page++)
23246723bfaSYasuaki Ishimatsu 		get_page_bootmem(section_nr, page, MIX_SECTION_INFO);
23346723bfaSYasuaki Ishimatsu }
23446723bfaSYasuaki Ishimatsu #endif /* !CONFIG_SPARSEMEM_VMEMMAP */
23504753278SYasunori Goto 
2367ded384aSLinus Torvalds void __init register_page_bootmem_info_node(struct pglist_data *pgdat)
23704753278SYasunori Goto {
23804753278SYasunori Goto 	unsigned long i, pfn, end_pfn, nr_pages;
23904753278SYasunori Goto 	int node = pgdat->node_id;
24004753278SYasunori Goto 	struct page *page;
24104753278SYasunori Goto 
24204753278SYasunori Goto 	nr_pages = PAGE_ALIGN(sizeof(struct pglist_data)) >> PAGE_SHIFT;
24304753278SYasunori Goto 	page = virt_to_page(pgdat);
24404753278SYasunori Goto 
24504753278SYasunori Goto 	for (i = 0; i < nr_pages; i++, page++)
24604753278SYasunori Goto 		get_page_bootmem(node, page, NODE_INFO);
24704753278SYasunori Goto 
24804753278SYasunori Goto 	pfn = pgdat->node_start_pfn;
249c1f19495SCody P Schafer 	end_pfn = pgdat_end_pfn(pgdat);
25004753278SYasunori Goto 
2517e9f5eb0STang Chen 	/* register section info */
252f14851afSqiuxishi 	for (; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
253f14851afSqiuxishi 		/*
254f14851afSqiuxishi 		 * Some platforms can assign the same pfn to multiple nodes - on
255f14851afSqiuxishi 		 * node0 as well as nodeN.  To avoid registering a pfn against
256f14851afSqiuxishi 		 * multiple nodes we check that this pfn does not already
2577e9f5eb0STang Chen 		 * reside in some other nodes.
258f14851afSqiuxishi 		 */
259f65e91dfSYang Shi 		if (pfn_valid(pfn) && (early_pfn_to_nid(pfn) == node))
26004753278SYasunori Goto 			register_page_bootmem_info_section(pfn);
261f14851afSqiuxishi 	}
26204753278SYasunori Goto }
26346723bfaSYasuaki Ishimatsu #endif /* CONFIG_HAVE_BOOTMEM_INFO_NODE */
26404753278SYasunori Goto 
2657ea62160SDan Williams static int check_pfn_span(unsigned long pfn, unsigned long nr_pages,
2667ea62160SDan Williams 		const char *reason)
2677ea62160SDan Williams {
2687ea62160SDan Williams 	/*
2697ea62160SDan Williams 	 * Disallow all operations smaller than a sub-section and only
2707ea62160SDan Williams 	 * allow operations smaller than a section for
2717ea62160SDan Williams 	 * SPARSEMEM_VMEMMAP. Note that check_hotplug_memory_range()
2727ea62160SDan Williams 	 * enforces a larger memory_block_size_bytes() granularity for
2737ea62160SDan Williams 	 * memory that will be marked online, so this check should only
2747ea62160SDan Williams 	 * fire for direct arch_{add,remove}_memory() users outside of
2757ea62160SDan Williams 	 * add_memory_resource().
2767ea62160SDan Williams 	 */
2777ea62160SDan Williams 	unsigned long min_align;
2787ea62160SDan Williams 
2797ea62160SDan Williams 	if (IS_ENABLED(CONFIG_SPARSEMEM_VMEMMAP))
2807ea62160SDan Williams 		min_align = PAGES_PER_SUBSECTION;
2817ea62160SDan Williams 	else
2827ea62160SDan Williams 		min_align = PAGES_PER_SECTION;
2837ea62160SDan Williams 	if (!IS_ALIGNED(pfn, min_align)
2847ea62160SDan Williams 			|| !IS_ALIGNED(nr_pages, min_align)) {
2857ea62160SDan Williams 		WARN(1, "Misaligned __%s_pages start: %#lx end: #%lx\n",
2867ea62160SDan Williams 				reason, pfn, pfn + nr_pages - 1);
2877ea62160SDan Williams 		return -EINVAL;
2887ea62160SDan Williams 	}
2897ea62160SDan Williams 	return 0;
2907ea62160SDan Williams }
2917ea62160SDan Williams 
2924edd7cefSDavid Rientjes /*
2939f605f26SDan Williams  * Return page for the valid pfn only if the page is online. All pfn
2949f605f26SDan Williams  * walkers which rely on the fully initialized page->flags and others
2959f605f26SDan Williams  * should use this rather than pfn_valid && pfn_to_page
2969f605f26SDan Williams  */
2979f605f26SDan Williams struct page *pfn_to_online_page(unsigned long pfn)
2989f605f26SDan Williams {
2999f605f26SDan Williams 	unsigned long nr = pfn_to_section_nr(pfn);
3001f90a347SDan Williams 	struct dev_pagemap *pgmap;
3019f9b02e5SDan Williams 	struct mem_section *ms;
3029f605f26SDan Williams 
3039f9b02e5SDan Williams 	if (nr >= NR_MEM_SECTIONS)
3049f605f26SDan Williams 		return NULL;
3059f9b02e5SDan Williams 
3069f9b02e5SDan Williams 	ms = __nr_to_section(nr);
3079f9b02e5SDan Williams 	if (!online_section(ms))
3089f9b02e5SDan Williams 		return NULL;
3099f9b02e5SDan Williams 
3109f9b02e5SDan Williams 	/*
3119f9b02e5SDan Williams 	 * Save some code text when online_section() +
3129f9b02e5SDan Williams 	 * pfn_section_valid() are sufficient.
3139f9b02e5SDan Williams 	 */
3149f9b02e5SDan Williams 	if (IS_ENABLED(CONFIG_HAVE_ARCH_PFN_VALID) && !pfn_valid(pfn))
3159f9b02e5SDan Williams 		return NULL;
3169f9b02e5SDan Williams 
3179f9b02e5SDan Williams 	if (!pfn_section_valid(ms, pfn))
3189f9b02e5SDan Williams 		return NULL;
3199f9b02e5SDan Williams 
3201f90a347SDan Williams 	if (!online_device_section(ms))
3211f90a347SDan Williams 		return pfn_to_page(pfn);
3221f90a347SDan Williams 
3231f90a347SDan Williams 	/*
3241f90a347SDan Williams 	 * Slowpath: when ZONE_DEVICE collides with
3251f90a347SDan Williams 	 * ZONE_{NORMAL,MOVABLE} within the same section some pfns in
3261f90a347SDan Williams 	 * the section may be 'offline' but 'valid'. Only
3271f90a347SDan Williams 	 * get_dev_pagemap() can determine sub-section online status.
3281f90a347SDan Williams 	 */
3291f90a347SDan Williams 	pgmap = get_dev_pagemap(pfn, NULL);
3301f90a347SDan Williams 	put_dev_pagemap(pgmap);
3311f90a347SDan Williams 
3321f90a347SDan Williams 	/* The presence of a pgmap indicates ZONE_DEVICE offline pfn */
3331f90a347SDan Williams 	if (pgmap)
3341f90a347SDan Williams 		return NULL;
3351f90a347SDan Williams 
3369f9b02e5SDan Williams 	return pfn_to_page(pfn);
3379f605f26SDan Williams }
3389f605f26SDan Williams EXPORT_SYMBOL_GPL(pfn_to_online_page);
3399f605f26SDan Williams 
3409f605f26SDan Williams /*
3414edd7cefSDavid Rientjes  * Reasonably generic function for adding memory.  It is
3424edd7cefSDavid Rientjes  * expected that archs that support memory hotplug will
3434edd7cefSDavid Rientjes  * call this function after deciding the zone to which to
3444edd7cefSDavid Rientjes  * add the new pages.
3454edd7cefSDavid Rientjes  */
3467ea62160SDan Williams int __ref __add_pages(int nid, unsigned long pfn, unsigned long nr_pages,
347f5637d3bSLogan Gunthorpe 		struct mhp_params *params)
3484edd7cefSDavid Rientjes {
3496cdd0b30SDavid Hildenbrand 	const unsigned long end_pfn = pfn + nr_pages;
3506cdd0b30SDavid Hildenbrand 	unsigned long cur_nr_pages;
3519a845030SDan Williams 	int err;
352f5637d3bSLogan Gunthorpe 	struct vmem_altmap *altmap = params->altmap;
3534b94ffdcSDan Williams 
354bfeb022fSLogan Gunthorpe 	if (WARN_ON_ONCE(!params->pgprot.pgprot))
355bfeb022fSLogan Gunthorpe 		return -EINVAL;
356bfeb022fSLogan Gunthorpe 
357bca3feaaSAnshuman Khandual 	VM_BUG_ON(!mhp_range_allowed(PFN_PHYS(pfn), nr_pages * PAGE_SIZE, false));
358dca4436dSAlastair D'Silva 
3594b94ffdcSDan Williams 	if (altmap) {
3604b94ffdcSDan Williams 		/*
3614b94ffdcSDan Williams 		 * Validate altmap is within bounds of the total request
3624b94ffdcSDan Williams 		 */
3637ea62160SDan Williams 		if (altmap->base_pfn != pfn
3644b94ffdcSDan Williams 				|| vmem_altmap_offset(altmap) > nr_pages) {
3654b94ffdcSDan Williams 			pr_warn_once("memory add fail, invalid altmap\n");
3667ea62160SDan Williams 			return -EINVAL;
3674b94ffdcSDan Williams 		}
3684b94ffdcSDan Williams 		altmap->alloc = 0;
3694b94ffdcSDan Williams 	}
3704b94ffdcSDan Williams 
3717ea62160SDan Williams 	err = check_pfn_span(pfn, nr_pages, "add");
3727ea62160SDan Williams 	if (err)
3737ea62160SDan Williams 		return err;
3747ea62160SDan Williams 
3756cdd0b30SDavid Hildenbrand 	for (; pfn < end_pfn; pfn += cur_nr_pages) {
3766cdd0b30SDavid Hildenbrand 		/* Select all remaining pages up to the next section boundary */
3776cdd0b30SDavid Hildenbrand 		cur_nr_pages = min(end_pfn - pfn,
3786cdd0b30SDavid Hildenbrand 				   SECTION_ALIGN_UP(pfn + 1) - pfn);
3796cdd0b30SDavid Hildenbrand 		err = sparse_add_section(nid, pfn, cur_nr_pages, altmap);
380ba72b4c8SDan Williams 		if (err)
381ba72b4c8SDan Williams 			break;
382f64ac5e6SMichal Hocko 		cond_resched();
3834edd7cefSDavid Rientjes 	}
384c435a390SZhu Guihua 	vmemmap_populate_print_last();
3854edd7cefSDavid Rientjes 	return err;
3864edd7cefSDavid Rientjes }
3874edd7cefSDavid Rientjes 
388815121d2SYasuaki Ishimatsu /* find the smallest valid pfn in the range [start_pfn, end_pfn) */
389d09b0137SYASUAKI ISHIMATSU static unsigned long find_smallest_section_pfn(int nid, struct zone *zone,
390815121d2SYasuaki Ishimatsu 				     unsigned long start_pfn,
391815121d2SYasuaki Ishimatsu 				     unsigned long end_pfn)
392815121d2SYasuaki Ishimatsu {
39349ba3c6bSDan Williams 	for (; start_pfn < end_pfn; start_pfn += PAGES_PER_SUBSECTION) {
3947ce700bfSDavid Hildenbrand 		if (unlikely(!pfn_to_online_page(start_pfn)))
395815121d2SYasuaki Ishimatsu 			continue;
396815121d2SYasuaki Ishimatsu 
397815121d2SYasuaki Ishimatsu 		if (unlikely(pfn_to_nid(start_pfn) != nid))
398815121d2SYasuaki Ishimatsu 			continue;
399815121d2SYasuaki Ishimatsu 
4009b05158fSDavid Hildenbrand 		if (zone != page_zone(pfn_to_page(start_pfn)))
401815121d2SYasuaki Ishimatsu 			continue;
402815121d2SYasuaki Ishimatsu 
403815121d2SYasuaki Ishimatsu 		return start_pfn;
404815121d2SYasuaki Ishimatsu 	}
405815121d2SYasuaki Ishimatsu 
406815121d2SYasuaki Ishimatsu 	return 0;
407815121d2SYasuaki Ishimatsu }
408815121d2SYasuaki Ishimatsu 
409815121d2SYasuaki Ishimatsu /* find the biggest valid pfn in the range [start_pfn, end_pfn). */
410d09b0137SYASUAKI ISHIMATSU static unsigned long find_biggest_section_pfn(int nid, struct zone *zone,
411815121d2SYasuaki Ishimatsu 				    unsigned long start_pfn,
412815121d2SYasuaki Ishimatsu 				    unsigned long end_pfn)
413815121d2SYasuaki Ishimatsu {
414815121d2SYasuaki Ishimatsu 	unsigned long pfn;
415815121d2SYasuaki Ishimatsu 
416815121d2SYasuaki Ishimatsu 	/* pfn is the end pfn of a memory section. */
417815121d2SYasuaki Ishimatsu 	pfn = end_pfn - 1;
41849ba3c6bSDan Williams 	for (; pfn >= start_pfn; pfn -= PAGES_PER_SUBSECTION) {
4197ce700bfSDavid Hildenbrand 		if (unlikely(!pfn_to_online_page(pfn)))
420815121d2SYasuaki Ishimatsu 			continue;
421815121d2SYasuaki Ishimatsu 
422815121d2SYasuaki Ishimatsu 		if (unlikely(pfn_to_nid(pfn) != nid))
423815121d2SYasuaki Ishimatsu 			continue;
424815121d2SYasuaki Ishimatsu 
4259b05158fSDavid Hildenbrand 		if (zone != page_zone(pfn_to_page(pfn)))
426815121d2SYasuaki Ishimatsu 			continue;
427815121d2SYasuaki Ishimatsu 
428815121d2SYasuaki Ishimatsu 		return pfn;
429815121d2SYasuaki Ishimatsu 	}
430815121d2SYasuaki Ishimatsu 
431815121d2SYasuaki Ishimatsu 	return 0;
432815121d2SYasuaki Ishimatsu }
433815121d2SYasuaki Ishimatsu 
434815121d2SYasuaki Ishimatsu static void shrink_zone_span(struct zone *zone, unsigned long start_pfn,
435815121d2SYasuaki Ishimatsu 			     unsigned long end_pfn)
436815121d2SYasuaki Ishimatsu {
437815121d2SYasuaki Ishimatsu 	unsigned long pfn;
438815121d2SYasuaki Ishimatsu 	int nid = zone_to_nid(zone);
439815121d2SYasuaki Ishimatsu 
440815121d2SYasuaki Ishimatsu 	zone_span_writelock(zone);
4415d12071cSDavid Hildenbrand 	if (zone->zone_start_pfn == start_pfn) {
442815121d2SYasuaki Ishimatsu 		/*
443815121d2SYasuaki Ishimatsu 		 * If the section is smallest section in the zone, it need
444815121d2SYasuaki Ishimatsu 		 * shrink zone->zone_start_pfn and zone->zone_spanned_pages.
445815121d2SYasuaki Ishimatsu 		 * In this case, we find second smallest valid mem_section
446815121d2SYasuaki Ishimatsu 		 * for shrinking zone.
447815121d2SYasuaki Ishimatsu 		 */
448815121d2SYasuaki Ishimatsu 		pfn = find_smallest_section_pfn(nid, zone, end_pfn,
4495d12071cSDavid Hildenbrand 						zone_end_pfn(zone));
450815121d2SYasuaki Ishimatsu 		if (pfn) {
4515d12071cSDavid Hildenbrand 			zone->spanned_pages = zone_end_pfn(zone) - pfn;
452815121d2SYasuaki Ishimatsu 			zone->zone_start_pfn = pfn;
453950b68d9SDavid Hildenbrand 		} else {
454950b68d9SDavid Hildenbrand 			zone->zone_start_pfn = 0;
455950b68d9SDavid Hildenbrand 			zone->spanned_pages = 0;
456815121d2SYasuaki Ishimatsu 		}
4575d12071cSDavid Hildenbrand 	} else if (zone_end_pfn(zone) == end_pfn) {
458815121d2SYasuaki Ishimatsu 		/*
459815121d2SYasuaki Ishimatsu 		 * If the section is biggest section in the zone, it need
460815121d2SYasuaki Ishimatsu 		 * shrink zone->spanned_pages.
461815121d2SYasuaki Ishimatsu 		 * In this case, we find second biggest valid mem_section for
462815121d2SYasuaki Ishimatsu 		 * shrinking zone.
463815121d2SYasuaki Ishimatsu 		 */
4645d12071cSDavid Hildenbrand 		pfn = find_biggest_section_pfn(nid, zone, zone->zone_start_pfn,
465815121d2SYasuaki Ishimatsu 					       start_pfn);
466815121d2SYasuaki Ishimatsu 		if (pfn)
4675d12071cSDavid Hildenbrand 			zone->spanned_pages = pfn - zone->zone_start_pfn + 1;
468950b68d9SDavid Hildenbrand 		else {
469815121d2SYasuaki Ishimatsu 			zone->zone_start_pfn = 0;
470815121d2SYasuaki Ishimatsu 			zone->spanned_pages = 0;
471950b68d9SDavid Hildenbrand 		}
472950b68d9SDavid Hildenbrand 	}
473815121d2SYasuaki Ishimatsu 	zone_span_writeunlock(zone);
474815121d2SYasuaki Ishimatsu }
475815121d2SYasuaki Ishimatsu 
47600d6c019SDavid Hildenbrand static void update_pgdat_span(struct pglist_data *pgdat)
477815121d2SYasuaki Ishimatsu {
47800d6c019SDavid Hildenbrand 	unsigned long node_start_pfn = 0, node_end_pfn = 0;
47900d6c019SDavid Hildenbrand 	struct zone *zone;
480815121d2SYasuaki Ishimatsu 
48100d6c019SDavid Hildenbrand 	for (zone = pgdat->node_zones;
48200d6c019SDavid Hildenbrand 	     zone < pgdat->node_zones + MAX_NR_ZONES; zone++) {
4836c922cf7SMiaohe Lin 		unsigned long end_pfn = zone_end_pfn(zone);
48400d6c019SDavid Hildenbrand 
48500d6c019SDavid Hildenbrand 		/* No need to lock the zones, they can't change. */
486656d5711SDavid Hildenbrand 		if (!zone->spanned_pages)
487656d5711SDavid Hildenbrand 			continue;
488656d5711SDavid Hildenbrand 		if (!node_end_pfn) {
489656d5711SDavid Hildenbrand 			node_start_pfn = zone->zone_start_pfn;
4906c922cf7SMiaohe Lin 			node_end_pfn = end_pfn;
491656d5711SDavid Hildenbrand 			continue;
492656d5711SDavid Hildenbrand 		}
493656d5711SDavid Hildenbrand 
4946c922cf7SMiaohe Lin 		if (end_pfn > node_end_pfn)
4956c922cf7SMiaohe Lin 			node_end_pfn = end_pfn;
49600d6c019SDavid Hildenbrand 		if (zone->zone_start_pfn < node_start_pfn)
49700d6c019SDavid Hildenbrand 			node_start_pfn = zone->zone_start_pfn;
498815121d2SYasuaki Ishimatsu 	}
499815121d2SYasuaki Ishimatsu 
50000d6c019SDavid Hildenbrand 	pgdat->node_start_pfn = node_start_pfn;
50100d6c019SDavid Hildenbrand 	pgdat->node_spanned_pages = node_end_pfn - node_start_pfn;
502815121d2SYasuaki Ishimatsu }
503815121d2SYasuaki Ishimatsu 
504feee6b29SDavid Hildenbrand void __ref remove_pfn_range_from_zone(struct zone *zone,
505feee6b29SDavid Hildenbrand 				      unsigned long start_pfn,
5067ea62160SDan Williams 				      unsigned long nr_pages)
507815121d2SYasuaki Ishimatsu {
508b7e3debdSBen Widawsky 	const unsigned long end_pfn = start_pfn + nr_pages;
509815121d2SYasuaki Ishimatsu 	struct pglist_data *pgdat = zone->zone_pgdat;
510b7e3debdSBen Widawsky 	unsigned long pfn, cur_nr_pages, flags;
511815121d2SYasuaki Ishimatsu 
512d33695b1SDavid Hildenbrand 	/* Poison struct pages because they are now uninitialized again. */
513b7e3debdSBen Widawsky 	for (pfn = start_pfn; pfn < end_pfn; pfn += cur_nr_pages) {
514b7e3debdSBen Widawsky 		cond_resched();
515b7e3debdSBen Widawsky 
516b7e3debdSBen Widawsky 		/* Select all remaining pages up to the next section boundary */
517b7e3debdSBen Widawsky 		cur_nr_pages =
518b7e3debdSBen Widawsky 			min(end_pfn - pfn, SECTION_ALIGN_UP(pfn + 1) - pfn);
519b7e3debdSBen Widawsky 		page_init_poison(pfn_to_page(pfn),
520b7e3debdSBen Widawsky 				 sizeof(struct page) * cur_nr_pages);
521b7e3debdSBen Widawsky 	}
522d33695b1SDavid Hildenbrand 
5237ce700bfSDavid Hildenbrand #ifdef CONFIG_ZONE_DEVICE
5247ce700bfSDavid Hildenbrand 	/*
5257ce700bfSDavid Hildenbrand 	 * Zone shrinking code cannot properly deal with ZONE_DEVICE. So
5267ce700bfSDavid Hildenbrand 	 * we will not try to shrink the zones - which is okay as
5277ce700bfSDavid Hildenbrand 	 * set_zone_contiguous() cannot deal with ZONE_DEVICE either way.
5287ce700bfSDavid Hildenbrand 	 */
5297ce700bfSDavid Hildenbrand 	if (zone_idx(zone) == ZONE_DEVICE)
5307ce700bfSDavid Hildenbrand 		return;
5317ce700bfSDavid Hildenbrand #endif
5327ce700bfSDavid Hildenbrand 
533feee6b29SDavid Hildenbrand 	clear_zone_contiguous(zone);
534feee6b29SDavid Hildenbrand 
535815121d2SYasuaki Ishimatsu 	pgdat_resize_lock(zone->zone_pgdat, &flags);
536815121d2SYasuaki Ishimatsu 	shrink_zone_span(zone, start_pfn, start_pfn + nr_pages);
53700d6c019SDavid Hildenbrand 	update_pgdat_span(pgdat);
538815121d2SYasuaki Ishimatsu 	pgdat_resize_unlock(zone->zone_pgdat, &flags);
539feee6b29SDavid Hildenbrand 
540feee6b29SDavid Hildenbrand 	set_zone_contiguous(zone);
541815121d2SYasuaki Ishimatsu }
542815121d2SYasuaki Ishimatsu 
543feee6b29SDavid Hildenbrand static void __remove_section(unsigned long pfn, unsigned long nr_pages,
544feee6b29SDavid Hildenbrand 			     unsigned long map_offset,
5459d1d887dSDavid Hildenbrand 			     struct vmem_altmap *altmap)
546ea01ea93SBadari Pulavarty {
54710404901Schenqiwu 	struct mem_section *ms = __pfn_to_section(pfn);
548ea01ea93SBadari Pulavarty 
5499d1d887dSDavid Hildenbrand 	if (WARN_ON_ONCE(!valid_section(ms)))
5509d1d887dSDavid Hildenbrand 		return;
551ea01ea93SBadari Pulavarty 
552ba72b4c8SDan Williams 	sparse_remove_section(ms, pfn, nr_pages, map_offset, altmap);
553ea01ea93SBadari Pulavarty }
554ea01ea93SBadari Pulavarty 
555ea01ea93SBadari Pulavarty /**
556feee6b29SDavid Hildenbrand  * __remove_pages() - remove sections of pages
5577ea62160SDan Williams  * @pfn: starting pageframe (must be aligned to start of a section)
558ea01ea93SBadari Pulavarty  * @nr_pages: number of pages to remove (must be multiple of section size)
559e8b098fcSMike Rapoport  * @altmap: alternative device page map or %NULL if default memmap is used
560ea01ea93SBadari Pulavarty  *
561ea01ea93SBadari Pulavarty  * Generic helper function to remove section mappings and sysfs entries
562ea01ea93SBadari Pulavarty  * for the section of the memory we are removing. Caller needs to make
563ea01ea93SBadari Pulavarty  * sure that pages are marked reserved and zones are adjust properly by
564ea01ea93SBadari Pulavarty  * calling offline_pages().
565ea01ea93SBadari Pulavarty  */
566feee6b29SDavid Hildenbrand void __remove_pages(unsigned long pfn, unsigned long nr_pages,
567feee6b29SDavid Hildenbrand 		    struct vmem_altmap *altmap)
568ea01ea93SBadari Pulavarty {
56952fb87c8SDavid Hildenbrand 	const unsigned long end_pfn = pfn + nr_pages;
57052fb87c8SDavid Hildenbrand 	unsigned long cur_nr_pages;
5714b94ffdcSDan Williams 	unsigned long map_offset = 0;
5724b94ffdcSDan Williams 
5734b94ffdcSDan Williams 	map_offset = vmem_altmap_offset(altmap);
574ea01ea93SBadari Pulavarty 
5757ea62160SDan Williams 	if (check_pfn_span(pfn, nr_pages, "remove"))
5767ea62160SDan Williams 		return;
577ea01ea93SBadari Pulavarty 
57852fb87c8SDavid Hildenbrand 	for (; pfn < end_pfn; pfn += cur_nr_pages) {
579dd33ad7bSMichal Hocko 		cond_resched();
58052fb87c8SDavid Hildenbrand 		/* Select all remaining pages up to the next section boundary */
581a11b9419SDavid Hildenbrand 		cur_nr_pages = min(end_pfn - pfn,
582a11b9419SDavid Hildenbrand 				   SECTION_ALIGN_UP(pfn + 1) - pfn);
58352fb87c8SDavid Hildenbrand 		__remove_section(pfn, cur_nr_pages, map_offset, altmap);
5844b94ffdcSDan Williams 		map_offset = 0;
585ea01ea93SBadari Pulavarty 	}
586ea01ea93SBadari Pulavarty }
587ea01ea93SBadari Pulavarty 
5889d0ad8caSDaniel Kiper int set_online_page_callback(online_page_callback_t callback)
5899d0ad8caSDaniel Kiper {
5909d0ad8caSDaniel Kiper 	int rc = -EINVAL;
5919d0ad8caSDaniel Kiper 
592bfc8c901SVladimir Davydov 	get_online_mems();
593bfc8c901SVladimir Davydov 	mutex_lock(&online_page_callback_lock);
5949d0ad8caSDaniel Kiper 
5959d0ad8caSDaniel Kiper 	if (online_page_callback == generic_online_page) {
5969d0ad8caSDaniel Kiper 		online_page_callback = callback;
5979d0ad8caSDaniel Kiper 		rc = 0;
5989d0ad8caSDaniel Kiper 	}
5999d0ad8caSDaniel Kiper 
600bfc8c901SVladimir Davydov 	mutex_unlock(&online_page_callback_lock);
601bfc8c901SVladimir Davydov 	put_online_mems();
6029d0ad8caSDaniel Kiper 
6039d0ad8caSDaniel Kiper 	return rc;
6049d0ad8caSDaniel Kiper }
6059d0ad8caSDaniel Kiper EXPORT_SYMBOL_GPL(set_online_page_callback);
6069d0ad8caSDaniel Kiper 
6079d0ad8caSDaniel Kiper int restore_online_page_callback(online_page_callback_t callback)
6089d0ad8caSDaniel Kiper {
6099d0ad8caSDaniel Kiper 	int rc = -EINVAL;
6109d0ad8caSDaniel Kiper 
611bfc8c901SVladimir Davydov 	get_online_mems();
612bfc8c901SVladimir Davydov 	mutex_lock(&online_page_callback_lock);
6139d0ad8caSDaniel Kiper 
6149d0ad8caSDaniel Kiper 	if (online_page_callback == callback) {
6159d0ad8caSDaniel Kiper 		online_page_callback = generic_online_page;
6169d0ad8caSDaniel Kiper 		rc = 0;
6179d0ad8caSDaniel Kiper 	}
6189d0ad8caSDaniel Kiper 
619bfc8c901SVladimir Davydov 	mutex_unlock(&online_page_callback_lock);
620bfc8c901SVladimir Davydov 	put_online_mems();
6219d0ad8caSDaniel Kiper 
6229d0ad8caSDaniel Kiper 	return rc;
6239d0ad8caSDaniel Kiper }
6249d0ad8caSDaniel Kiper EXPORT_SYMBOL_GPL(restore_online_page_callback);
6259d0ad8caSDaniel Kiper 
62618db1491SDavid Hildenbrand void generic_online_page(struct page *page, unsigned int order)
6279d0ad8caSDaniel Kiper {
628c87cbc1fSVlastimil Babka 	/*
629c87cbc1fSVlastimil Babka 	 * Freeing the page with debug_pagealloc enabled will try to unmap it,
630c87cbc1fSVlastimil Babka 	 * so we should map it first. This is better than introducing a special
631c87cbc1fSVlastimil Babka 	 * case in page freeing fast path.
632c87cbc1fSVlastimil Babka 	 */
63377bc7fd6SMike Rapoport 	debug_pagealloc_map_pages(page, 1 << order);
634a9cd410aSArun KS 	__free_pages_core(page, order);
635a9cd410aSArun KS 	totalram_pages_add(1UL << order);
636a9cd410aSArun KS #ifdef CONFIG_HIGHMEM
637a9cd410aSArun KS 	if (PageHighMem(page))
638a9cd410aSArun KS 		totalhigh_pages_add(1UL << order);
639a9cd410aSArun KS #endif
640a9cd410aSArun KS }
64118db1491SDavid Hildenbrand EXPORT_SYMBOL_GPL(generic_online_page);
642a9cd410aSArun KS 
643aac65321SDavid Hildenbrand static void online_pages_range(unsigned long start_pfn, unsigned long nr_pages)
6443947be19SDave Hansen {
645b2c2ab20SDavid Hildenbrand 	const unsigned long end_pfn = start_pfn + nr_pages;
646b2c2ab20SDavid Hildenbrand 	unsigned long pfn;
6472d070eabSMichal Hocko 
648b2c2ab20SDavid Hildenbrand 	/*
649aac65321SDavid Hildenbrand 	 * Online the pages in MAX_ORDER - 1 aligned chunks. The callback might
650aac65321SDavid Hildenbrand 	 * decide to not expose all pages to the buddy (e.g., expose them
651aac65321SDavid Hildenbrand 	 * later). We account all pages as being online and belonging to this
652aac65321SDavid Hildenbrand 	 * zone ("present").
653*a08a2ae3SOscar Salvador 	 * When using memmap_on_memory, the range might not be aligned to
654*a08a2ae3SOscar Salvador 	 * MAX_ORDER_NR_PAGES - 1, but pageblock aligned. __ffs() will detect
655*a08a2ae3SOscar Salvador 	 * this and the first chunk to online will be pageblock_nr_pages.
656b2c2ab20SDavid Hildenbrand 	 */
657*a08a2ae3SOscar Salvador 	for (pfn = start_pfn; pfn < end_pfn;) {
658*a08a2ae3SOscar Salvador 		int order = min(MAX_ORDER - 1UL, __ffs(pfn));
659*a08a2ae3SOscar Salvador 
660*a08a2ae3SOscar Salvador 		(*online_page_callback)(pfn_to_page(pfn), order);
661*a08a2ae3SOscar Salvador 		pfn += (1UL << order);
662*a08a2ae3SOscar Salvador 	}
6632d070eabSMichal Hocko 
664b2c2ab20SDavid Hildenbrand 	/* mark all involved sections as online */
665b2c2ab20SDavid Hildenbrand 	online_mem_sections(start_pfn, end_pfn);
66675884fb1SKAMEZAWA Hiroyuki }
66775884fb1SKAMEZAWA Hiroyuki 
668d9713679SLai Jiangshan /* check which state of node_states will be changed when online memory */
669d9713679SLai Jiangshan static void node_states_check_changes_online(unsigned long nr_pages,
670d9713679SLai Jiangshan 	struct zone *zone, struct memory_notify *arg)
671d9713679SLai Jiangshan {
672d9713679SLai Jiangshan 	int nid = zone_to_nid(zone);
673d9713679SLai Jiangshan 
67498fa15f3SAnshuman Khandual 	arg->status_change_nid = NUMA_NO_NODE;
67598fa15f3SAnshuman Khandual 	arg->status_change_nid_normal = NUMA_NO_NODE;
67698fa15f3SAnshuman Khandual 	arg->status_change_nid_high = NUMA_NO_NODE;
6776715ddf9SLai Jiangshan 
6786715ddf9SLai Jiangshan 	if (!node_state(nid, N_MEMORY))
679d9713679SLai Jiangshan 		arg->status_change_nid = nid;
6808efe33f4SOscar Salvador 	if (zone_idx(zone) <= ZONE_NORMAL && !node_state(nid, N_NORMAL_MEMORY))
6818efe33f4SOscar Salvador 		arg->status_change_nid_normal = nid;
6828efe33f4SOscar Salvador #ifdef CONFIG_HIGHMEM
683d3ba3ae1SBaoquan He 	if (zone_idx(zone) <= ZONE_HIGHMEM && !node_state(nid, N_HIGH_MEMORY))
6848efe33f4SOscar Salvador 		arg->status_change_nid_high = nid;
6858efe33f4SOscar Salvador #endif
686d9713679SLai Jiangshan }
687d9713679SLai Jiangshan 
688d9713679SLai Jiangshan static void node_states_set_node(int node, struct memory_notify *arg)
689d9713679SLai Jiangshan {
690d9713679SLai Jiangshan 	if (arg->status_change_nid_normal >= 0)
691d9713679SLai Jiangshan 		node_set_state(node, N_NORMAL_MEMORY);
692d9713679SLai Jiangshan 
6936715ddf9SLai Jiangshan 	if (arg->status_change_nid_high >= 0)
694d9713679SLai Jiangshan 		node_set_state(node, N_HIGH_MEMORY);
6956715ddf9SLai Jiangshan 
69683d83612SOscar Salvador 	if (arg->status_change_nid >= 0)
6976715ddf9SLai Jiangshan 		node_set_state(node, N_MEMORY);
698d9713679SLai Jiangshan }
699d9713679SLai Jiangshan 
700f1dd2cd1SMichal Hocko static void __meminit resize_zone_range(struct zone *zone, unsigned long start_pfn,
701f1dd2cd1SMichal Hocko 		unsigned long nr_pages)
702f1dd2cd1SMichal Hocko {
703f1dd2cd1SMichal Hocko 	unsigned long old_end_pfn = zone_end_pfn(zone);
704f1dd2cd1SMichal Hocko 
705f1dd2cd1SMichal Hocko 	if (zone_is_empty(zone) || start_pfn < zone->zone_start_pfn)
706f1dd2cd1SMichal Hocko 		zone->zone_start_pfn = start_pfn;
707f1dd2cd1SMichal Hocko 
708f1dd2cd1SMichal Hocko 	zone->spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - zone->zone_start_pfn;
709f1dd2cd1SMichal Hocko }
710f1dd2cd1SMichal Hocko 
711f1dd2cd1SMichal Hocko static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned long start_pfn,
712f1dd2cd1SMichal Hocko                                      unsigned long nr_pages)
713f1dd2cd1SMichal Hocko {
714f1dd2cd1SMichal Hocko 	unsigned long old_end_pfn = pgdat_end_pfn(pgdat);
715f1dd2cd1SMichal Hocko 
716f1dd2cd1SMichal Hocko 	if (!pgdat->node_spanned_pages || start_pfn < pgdat->node_start_pfn)
717f1dd2cd1SMichal Hocko 		pgdat->node_start_pfn = start_pfn;
718f1dd2cd1SMichal Hocko 
719f1dd2cd1SMichal Hocko 	pgdat->node_spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - pgdat->node_start_pfn;
720f1dd2cd1SMichal Hocko 
7213fccb74cSDavid Hildenbrand }
7221f90a347SDan Williams 
7231f90a347SDan Williams static void section_taint_zone_device(unsigned long pfn)
7241f90a347SDan Williams {
7251f90a347SDan Williams 	struct mem_section *ms = __pfn_to_section(pfn);
7261f90a347SDan Williams 
7271f90a347SDan Williams 	ms->section_mem_map |= SECTION_TAINT_ZONE_DEVICE;
7281f90a347SDan Williams }
7291f90a347SDan Williams 
7303fccb74cSDavid Hildenbrand /*
7313fccb74cSDavid Hildenbrand  * Associate the pfn range with the given zone, initializing the memmaps
7323fccb74cSDavid Hildenbrand  * and resizing the pgdat/zone data to span the added pages. After this
7333fccb74cSDavid Hildenbrand  * call, all affected pages are PG_reserved.
734d882c006SDavid Hildenbrand  *
735d882c006SDavid Hildenbrand  * All aligned pageblocks are initialized to the specified migratetype
736d882c006SDavid Hildenbrand  * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related
737d882c006SDavid Hildenbrand  * zone stats (e.g., nr_isolate_pageblock) are touched.
7383fccb74cSDavid Hildenbrand  */
739a99583e7SChristoph Hellwig void __ref move_pfn_range_to_zone(struct zone *zone, unsigned long start_pfn,
740d882c006SDavid Hildenbrand 				  unsigned long nr_pages,
741d882c006SDavid Hildenbrand 				  struct vmem_altmap *altmap, int migratetype)
742f1dd2cd1SMichal Hocko {
743f1dd2cd1SMichal Hocko 	struct pglist_data *pgdat = zone->zone_pgdat;
744f1dd2cd1SMichal Hocko 	int nid = pgdat->node_id;
745f1dd2cd1SMichal Hocko 	unsigned long flags;
746f1dd2cd1SMichal Hocko 
747f1dd2cd1SMichal Hocko 	clear_zone_contiguous(zone);
748f1dd2cd1SMichal Hocko 
749f1dd2cd1SMichal Hocko 	/* TODO Huh pgdat is irqsave while zone is not. It used to be like that before */
750f1dd2cd1SMichal Hocko 	pgdat_resize_lock(pgdat, &flags);
751f1dd2cd1SMichal Hocko 	zone_span_writelock(zone);
752fa004ab7SWei Yang 	if (zone_is_empty(zone))
753fa004ab7SWei Yang 		init_currently_empty_zone(zone, start_pfn, nr_pages);
754f1dd2cd1SMichal Hocko 	resize_zone_range(zone, start_pfn, nr_pages);
755f1dd2cd1SMichal Hocko 	zone_span_writeunlock(zone);
756f1dd2cd1SMichal Hocko 	resize_pgdat_range(pgdat, start_pfn, nr_pages);
757f1dd2cd1SMichal Hocko 	pgdat_resize_unlock(pgdat, &flags);
758f1dd2cd1SMichal Hocko 
759f1dd2cd1SMichal Hocko 	/*
7601f90a347SDan Williams 	 * Subsection population requires care in pfn_to_online_page().
7611f90a347SDan Williams 	 * Set the taint to enable the slow path detection of
7621f90a347SDan Williams 	 * ZONE_DEVICE pages in an otherwise  ZONE_{NORMAL,MOVABLE}
7631f90a347SDan Williams 	 * section.
7641f90a347SDan Williams 	 */
7651f90a347SDan Williams 	if (zone_is_zone_device(zone)) {
7661f90a347SDan Williams 		if (!IS_ALIGNED(start_pfn, PAGES_PER_SECTION))
7671f90a347SDan Williams 			section_taint_zone_device(start_pfn);
7681f90a347SDan Williams 		if (!IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION))
7691f90a347SDan Williams 			section_taint_zone_device(start_pfn + nr_pages);
7701f90a347SDan Williams 	}
7711f90a347SDan Williams 
7721f90a347SDan Williams 	/*
773f1dd2cd1SMichal Hocko 	 * TODO now we have a visible range of pages which are not associated
774f1dd2cd1SMichal Hocko 	 * with their zone properly. Not nice but set_pfnblock_flags_mask
775f1dd2cd1SMichal Hocko 	 * expects the zone spans the pfn range. All the pages in the range
776f1dd2cd1SMichal Hocko 	 * are reserved so nobody should be touching them so we should be safe
777f1dd2cd1SMichal Hocko 	 */
778ab28cb6eSBaoquan He 	memmap_init_range(nr_pages, nid, zone_idx(zone), start_pfn, 0,
779d882c006SDavid Hildenbrand 			 MEMINIT_HOTPLUG, altmap, migratetype);
780f1dd2cd1SMichal Hocko 
781f1dd2cd1SMichal Hocko 	set_zone_contiguous(zone);
782f1dd2cd1SMichal Hocko }
783f1dd2cd1SMichal Hocko 
784f1dd2cd1SMichal Hocko /*
785c246a213SMichal Hocko  * Returns a default kernel memory zone for the given pfn range.
786c246a213SMichal Hocko  * If no kernel zone covers this pfn range it will automatically go
787c246a213SMichal Hocko  * to the ZONE_NORMAL.
788c246a213SMichal Hocko  */
789c6f03e29SMichal Hocko static struct zone *default_kernel_zone_for_pfn(int nid, unsigned long start_pfn,
790c246a213SMichal Hocko 		unsigned long nr_pages)
791c246a213SMichal Hocko {
792c246a213SMichal Hocko 	struct pglist_data *pgdat = NODE_DATA(nid);
793c246a213SMichal Hocko 	int zid;
794c246a213SMichal Hocko 
795c246a213SMichal Hocko 	for (zid = 0; zid <= ZONE_NORMAL; zid++) {
796c246a213SMichal Hocko 		struct zone *zone = &pgdat->node_zones[zid];
797c246a213SMichal Hocko 
798c246a213SMichal Hocko 		if (zone_intersects(zone, start_pfn, nr_pages))
799c246a213SMichal Hocko 			return zone;
800c246a213SMichal Hocko 	}
801c246a213SMichal Hocko 
802c246a213SMichal Hocko 	return &pgdat->node_zones[ZONE_NORMAL];
803c246a213SMichal Hocko }
804c246a213SMichal Hocko 
805c6f03e29SMichal Hocko static inline struct zone *default_zone_for_pfn(int nid, unsigned long start_pfn,
806c6f03e29SMichal Hocko 		unsigned long nr_pages)
807e5e68930SMichal Hocko {
808c6f03e29SMichal Hocko 	struct zone *kernel_zone = default_kernel_zone_for_pfn(nid, start_pfn,
809c6f03e29SMichal Hocko 			nr_pages);
810c6f03e29SMichal Hocko 	struct zone *movable_zone = &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
811c6f03e29SMichal Hocko 	bool in_kernel = zone_intersects(kernel_zone, start_pfn, nr_pages);
812c6f03e29SMichal Hocko 	bool in_movable = zone_intersects(movable_zone, start_pfn, nr_pages);
813e5e68930SMichal Hocko 
814e5e68930SMichal Hocko 	/*
815c6f03e29SMichal Hocko 	 * We inherit the existing zone in a simple case where zones do not
816c6f03e29SMichal Hocko 	 * overlap in the given range
817e5e68930SMichal Hocko 	 */
818c6f03e29SMichal Hocko 	if (in_kernel ^ in_movable)
819c6f03e29SMichal Hocko 		return (in_kernel) ? kernel_zone : movable_zone;
820e5e68930SMichal Hocko 
821c6f03e29SMichal Hocko 	/*
822c6f03e29SMichal Hocko 	 * If the range doesn't belong to any zone or two zones overlap in the
823c6f03e29SMichal Hocko 	 * given range then we use movable zone only if movable_node is
824c6f03e29SMichal Hocko 	 * enabled because we always online to a kernel zone by default.
825c6f03e29SMichal Hocko 	 */
826c6f03e29SMichal Hocko 	return movable_node_enabled ? movable_zone : kernel_zone;
8279f123ab5SMichal Hocko }
8289f123ab5SMichal Hocko 
829e5e68930SMichal Hocko struct zone * zone_for_pfn_range(int online_type, int nid, unsigned start_pfn,
830e5e68930SMichal Hocko 		unsigned long nr_pages)
831f1dd2cd1SMichal Hocko {
832c6f03e29SMichal Hocko 	if (online_type == MMOP_ONLINE_KERNEL)
833c6f03e29SMichal Hocko 		return default_kernel_zone_for_pfn(nid, start_pfn, nr_pages);
834f1dd2cd1SMichal Hocko 
835c6f03e29SMichal Hocko 	if (online_type == MMOP_ONLINE_MOVABLE)
836c6f03e29SMichal Hocko 		return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
837f1dd2cd1SMichal Hocko 
838c6f03e29SMichal Hocko 	return default_zone_for_pfn(nid, start_pfn, nr_pages);
839e5e68930SMichal Hocko }
840e5e68930SMichal Hocko 
841*a08a2ae3SOscar Salvador /*
842*a08a2ae3SOscar Salvador  * This function should only be called by memory_block_{online,offline},
843*a08a2ae3SOscar Salvador  * and {online,offline}_pages.
844*a08a2ae3SOscar Salvador  */
845*a08a2ae3SOscar Salvador void adjust_present_page_count(struct zone *zone, long nr_pages)
846f9901144SDavid Hildenbrand {
847f9901144SDavid Hildenbrand 	unsigned long flags;
848f9901144SDavid Hildenbrand 
849f9901144SDavid Hildenbrand 	zone->present_pages += nr_pages;
850f9901144SDavid Hildenbrand 	pgdat_resize_lock(zone->zone_pgdat, &flags);
851f9901144SDavid Hildenbrand 	zone->zone_pgdat->node_present_pages += nr_pages;
852f9901144SDavid Hildenbrand 	pgdat_resize_unlock(zone->zone_pgdat, &flags);
853f9901144SDavid Hildenbrand }
854f9901144SDavid Hildenbrand 
855*a08a2ae3SOscar Salvador int mhp_init_memmap_on_memory(unsigned long pfn, unsigned long nr_pages,
856*a08a2ae3SOscar Salvador 			      struct zone *zone)
857*a08a2ae3SOscar Salvador {
858*a08a2ae3SOscar Salvador 	unsigned long end_pfn = pfn + nr_pages;
859*a08a2ae3SOscar Salvador 	int ret;
860*a08a2ae3SOscar Salvador 
861*a08a2ae3SOscar Salvador 	ret = kasan_add_zero_shadow(__va(PFN_PHYS(pfn)), PFN_PHYS(nr_pages));
862*a08a2ae3SOscar Salvador 	if (ret)
863*a08a2ae3SOscar Salvador 		return ret;
864*a08a2ae3SOscar Salvador 
865*a08a2ae3SOscar Salvador 	move_pfn_range_to_zone(zone, pfn, nr_pages, NULL, MIGRATE_UNMOVABLE);
866*a08a2ae3SOscar Salvador 
867*a08a2ae3SOscar Salvador 	/*
868*a08a2ae3SOscar Salvador 	 * It might be that the vmemmap_pages fully span sections. If that is
869*a08a2ae3SOscar Salvador 	 * the case, mark those sections online here as otherwise they will be
870*a08a2ae3SOscar Salvador 	 * left offline.
871*a08a2ae3SOscar Salvador 	 */
872*a08a2ae3SOscar Salvador 	if (nr_pages >= PAGES_PER_SECTION)
873*a08a2ae3SOscar Salvador 	        online_mem_sections(pfn, ALIGN_DOWN(end_pfn, PAGES_PER_SECTION));
874*a08a2ae3SOscar Salvador 
875*a08a2ae3SOscar Salvador 	return ret;
876*a08a2ae3SOscar Salvador }
877*a08a2ae3SOscar Salvador 
878*a08a2ae3SOscar Salvador void mhp_deinit_memmap_on_memory(unsigned long pfn, unsigned long nr_pages)
879*a08a2ae3SOscar Salvador {
880*a08a2ae3SOscar Salvador 	unsigned long end_pfn = pfn + nr_pages;
881*a08a2ae3SOscar Salvador 
882*a08a2ae3SOscar Salvador 	/*
883*a08a2ae3SOscar Salvador 	 * It might be that the vmemmap_pages fully span sections. If that is
884*a08a2ae3SOscar Salvador 	 * the case, mark those sections offline here as otherwise they will be
885*a08a2ae3SOscar Salvador 	 * left online.
886*a08a2ae3SOscar Salvador 	 */
887*a08a2ae3SOscar Salvador 	if (nr_pages >= PAGES_PER_SECTION)
888*a08a2ae3SOscar Salvador 		offline_mem_sections(pfn, ALIGN_DOWN(end_pfn, PAGES_PER_SECTION));
889*a08a2ae3SOscar Salvador 
890*a08a2ae3SOscar Salvador         /*
891*a08a2ae3SOscar Salvador 	 * The pages associated with this vmemmap have been offlined, so
892*a08a2ae3SOscar Salvador 	 * we can reset its state here.
893*a08a2ae3SOscar Salvador 	 */
894*a08a2ae3SOscar Salvador 	remove_pfn_range_from_zone(page_zone(pfn_to_page(pfn)), pfn, nr_pages);
895*a08a2ae3SOscar Salvador 	kasan_remove_zero_shadow(__va(PFN_PHYS(pfn)), PFN_PHYS(nr_pages));
896*a08a2ae3SOscar Salvador }
897*a08a2ae3SOscar Salvador 
898*a08a2ae3SOscar Salvador int __ref online_pages(unsigned long pfn, unsigned long nr_pages, struct zone *zone)
89975884fb1SKAMEZAWA Hiroyuki {
900aa47228aSCody P Schafer 	unsigned long flags;
9016811378eSYasunori Goto 	int need_zonelists_rebuild = 0;
902*a08a2ae3SOscar Salvador 	const int nid = zone_to_nid(zone);
9037b78d335SYasunori Goto 	int ret;
9047b78d335SYasunori Goto 	struct memory_notify arg;
9053947be19SDave Hansen 
906dd8e2f23SOscar Salvador 	/*
907dd8e2f23SOscar Salvador 	 * {on,off}lining is constrained to full memory sections (or more
908dd8e2f23SOscar Salvador 	 * precisly to memory blocks from the user space POV).
909dd8e2f23SOscar Salvador 	 * memmap_on_memory is an exception because it reserves initial part
910dd8e2f23SOscar Salvador 	 * of the physical memory space for vmemmaps. That space is pageblock
911dd8e2f23SOscar Salvador 	 * aligned.
912dd8e2f23SOscar Salvador 	 */
9134986fac1SDavid Hildenbrand 	if (WARN_ON_ONCE(!nr_pages ||
914dd8e2f23SOscar Salvador 			 !IS_ALIGNED(pfn, pageblock_nr_pages) ||
915dd8e2f23SOscar Salvador 			 !IS_ALIGNED(pfn + nr_pages, PAGES_PER_SECTION)))
9164986fac1SDavid Hildenbrand 		return -EINVAL;
9174986fac1SDavid Hildenbrand 
918381eab4aSDavid Hildenbrand 	mem_hotplug_begin();
919381eab4aSDavid Hildenbrand 
920f1dd2cd1SMichal Hocko 	/* associate pfn range with the zone */
921b30c5927SDavid Hildenbrand 	move_pfn_range_to_zone(zone, pfn, nr_pages, NULL, MIGRATE_ISOLATE);
922511c2abaSLai Jiangshan 
9237b78d335SYasunori Goto 	arg.start_pfn = pfn;
9247b78d335SYasunori Goto 	arg.nr_pages = nr_pages;
925d9713679SLai Jiangshan 	node_states_check_changes_online(nr_pages, zone, &arg);
9267b78d335SYasunori Goto 
9277b78d335SYasunori Goto 	ret = memory_notify(MEM_GOING_ONLINE, &arg);
9287b78d335SYasunori Goto 	ret = notifier_to_errno(ret);
929e33e33b4SChen Yucong 	if (ret)
930e33e33b4SChen Yucong 		goto failed_addition;
931e33e33b4SChen Yucong 
9323947be19SDave Hansen 	/*
933b30c5927SDavid Hildenbrand 	 * Fixup the number of isolated pageblocks before marking the sections
934b30c5927SDavid Hildenbrand 	 * onlining, such that undo_isolate_page_range() works correctly.
935b30c5927SDavid Hildenbrand 	 */
936b30c5927SDavid Hildenbrand 	spin_lock_irqsave(&zone->lock, flags);
937b30c5927SDavid Hildenbrand 	zone->nr_isolate_pageblock += nr_pages / pageblock_nr_pages;
938b30c5927SDavid Hildenbrand 	spin_unlock_irqrestore(&zone->lock, flags);
939b30c5927SDavid Hildenbrand 
940b30c5927SDavid Hildenbrand 	/*
9416811378eSYasunori Goto 	 * If this zone is not populated, then it is not in zonelist.
9426811378eSYasunori Goto 	 * This means the page allocator ignores this zone.
9436811378eSYasunori Goto 	 * So, zonelist must be updated after online.
9446811378eSYasunori Goto 	 */
9456dcd73d7SWen Congyang 	if (!populated_zone(zone)) {
9466811378eSYasunori Goto 		need_zonelists_rebuild = 1;
94772675e13SMichal Hocko 		setup_zone_pageset(zone);
9486dcd73d7SWen Congyang 	}
9496811378eSYasunori Goto 
950aac65321SDavid Hildenbrand 	online_pages_range(pfn, nr_pages);
951f9901144SDavid Hildenbrand 	adjust_present_page_count(zone, nr_pages);
952aa47228aSCody P Schafer 
953b30c5927SDavid Hildenbrand 	node_states_set_node(nid, &arg);
954b30c5927SDavid Hildenbrand 	if (need_zonelists_rebuild)
955b30c5927SDavid Hildenbrand 		build_all_zonelists(NULL);
956b30c5927SDavid Hildenbrand 	zone_pcp_update(zone);
957b30c5927SDavid Hildenbrand 
958b30c5927SDavid Hildenbrand 	/* Basic onlining is complete, allow allocation of onlined pages. */
959b30c5927SDavid Hildenbrand 	undo_isolate_page_range(pfn, pfn + nr_pages, MIGRATE_MOVABLE);
960b30c5927SDavid Hildenbrand 
96193146d98SDavid Hildenbrand 	/*
962b86c5fc4SDavid Hildenbrand 	 * Freshly onlined pages aren't shuffled (e.g., all pages are placed to
963b86c5fc4SDavid Hildenbrand 	 * the tail of the freelist when undoing isolation). Shuffle the whole
964b86c5fc4SDavid Hildenbrand 	 * zone to make sure the just onlined pages are properly distributed
965b86c5fc4SDavid Hildenbrand 	 * across the whole freelist - to create an initial shuffle.
96693146d98SDavid Hildenbrand 	 */
967e900a918SDan Williams 	shuffle_zone(zone);
968e900a918SDan Williams 
9691b79acc9SKOSAKI Motohiro 	init_per_zone_wmark_min();
9701b79acc9SKOSAKI Motohiro 
971e888ca35SVlastimil Babka 	kswapd_run(nid);
972698b1b30SVlastimil Babka 	kcompactd_run(nid);
97361b13993SDave Hansen 
9742d1d43f6SChandra Seetharaman 	writeback_set_ratelimit();
9757b78d335SYasunori Goto 
9767b78d335SYasunori Goto 	memory_notify(MEM_ONLINE, &arg);
977381eab4aSDavid Hildenbrand 	mem_hotplug_done();
97830467e0bSDavid Rientjes 	return 0;
979e33e33b4SChen Yucong 
980e33e33b4SChen Yucong failed_addition:
981e33e33b4SChen Yucong 	pr_debug("online_pages [mem %#010llx-%#010llx] failed\n",
982e33e33b4SChen Yucong 		 (unsigned long long) pfn << PAGE_SHIFT,
983e33e33b4SChen Yucong 		 (((unsigned long long) pfn + nr_pages) << PAGE_SHIFT) - 1);
984e33e33b4SChen Yucong 	memory_notify(MEM_CANCEL_ONLINE, &arg);
985feee6b29SDavid Hildenbrand 	remove_pfn_range_from_zone(zone, pfn, nr_pages);
986381eab4aSDavid Hildenbrand 	mem_hotplug_done();
987e33e33b4SChen Yucong 	return ret;
9883947be19SDave Hansen }
98953947027SKeith Mannthey #endif /* CONFIG_MEMORY_HOTPLUG_SPARSE */
990bc02af93SYasunori Goto 
9910bd85420STang Chen static void reset_node_present_pages(pg_data_t *pgdat)
9920bd85420STang Chen {
9930bd85420STang Chen 	struct zone *z;
9940bd85420STang Chen 
9950bd85420STang Chen 	for (z = pgdat->node_zones; z < pgdat->node_zones + MAX_NR_ZONES; z++)
9960bd85420STang Chen 		z->present_pages = 0;
9970bd85420STang Chen 
9980bd85420STang Chen 	pgdat->node_present_pages = 0;
9990bd85420STang Chen }
10000bd85420STang Chen 
1001e1319331SHidetoshi Seto /* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
1002c68ab18cSDavid Hildenbrand static pg_data_t __ref *hotadd_new_pgdat(int nid)
10039af3c2deSYasunori Goto {
10049af3c2deSYasunori Goto 	struct pglist_data *pgdat;
10059af3c2deSYasunori Goto 
1006a1e565aaSTang Chen 	pgdat = NODE_DATA(nid);
1007a1e565aaSTang Chen 	if (!pgdat) {
10089af3c2deSYasunori Goto 		pgdat = arch_alloc_nodedata(nid);
10099af3c2deSYasunori Goto 		if (!pgdat)
10109af3c2deSYasunori Goto 			return NULL;
10119af3c2deSYasunori Goto 
101233fce011SWei Yang 		pgdat->per_cpu_nodestats =
101333fce011SWei Yang 			alloc_percpu(struct per_cpu_nodestat);
10149af3c2deSYasunori Goto 		arch_refresh_nodedata(nid, pgdat);
1015b0dc3a34SGu Zheng 	} else {
101633fce011SWei Yang 		int cpu;
1017e716f2ebSMel Gorman 		/*
101897a225e6SJoonsoo Kim 		 * Reset the nr_zones, order and highest_zoneidx before reuse.
101997a225e6SJoonsoo Kim 		 * Note that kswapd will init kswapd_highest_zoneidx properly
1020e716f2ebSMel Gorman 		 * when it starts in the near future.
1021e716f2ebSMel Gorman 		 */
1022b0dc3a34SGu Zheng 		pgdat->nr_zones = 0;
102338087d9bSMel Gorman 		pgdat->kswapd_order = 0;
102497a225e6SJoonsoo Kim 		pgdat->kswapd_highest_zoneidx = 0;
102533fce011SWei Yang 		for_each_online_cpu(cpu) {
102633fce011SWei Yang 			struct per_cpu_nodestat *p;
102733fce011SWei Yang 
102833fce011SWei Yang 			p = per_cpu_ptr(pgdat->per_cpu_nodestats, cpu);
102933fce011SWei Yang 			memset(p, 0, sizeof(*p));
103033fce011SWei Yang 		}
1031a1e565aaSTang Chen 	}
10329af3c2deSYasunori Goto 
10339af3c2deSYasunori Goto 	/* we can use NODE_DATA(nid) from here */
103403e85f9dSOscar Salvador 	pgdat->node_id = nid;
1035c68ab18cSDavid Hildenbrand 	pgdat->node_start_pfn = 0;
103603e85f9dSOscar Salvador 
10379af3c2deSYasunori Goto 	/* init node's zones as empty zones, we don't have any present pages.*/
103803e85f9dSOscar Salvador 	free_area_init_core_hotplug(nid);
10399af3c2deSYasunori Goto 
1040959ecc48SKAMEZAWA Hiroyuki 	/*
1041959ecc48SKAMEZAWA Hiroyuki 	 * The node we allocated has no zone fallback lists. For avoiding
1042959ecc48SKAMEZAWA Hiroyuki 	 * to access not-initialized zonelist, build here.
1043959ecc48SKAMEZAWA Hiroyuki 	 */
104472675e13SMichal Hocko 	build_all_zonelists(pgdat);
1045959ecc48SKAMEZAWA Hiroyuki 
1046f784a3f1STang Chen 	/*
10470bd85420STang Chen 	 * When memory is hot-added, all the memory is in offline state. So
10480bd85420STang Chen 	 * clear all zones' present_pages because they will be updated in
10490bd85420STang Chen 	 * online_pages() and offline_pages().
10500bd85420STang Chen 	 */
105103e85f9dSOscar Salvador 	reset_node_managed_pages(pgdat);
10520bd85420STang Chen 	reset_node_present_pages(pgdat);
10530bd85420STang Chen 
10549af3c2deSYasunori Goto 	return pgdat;
10559af3c2deSYasunori Goto }
10569af3c2deSYasunori Goto 
1057b9ff0360SOscar Salvador static void rollback_node_hotadd(int nid)
10589af3c2deSYasunori Goto {
1059b9ff0360SOscar Salvador 	pg_data_t *pgdat = NODE_DATA(nid);
1060b9ff0360SOscar Salvador 
10619af3c2deSYasunori Goto 	arch_refresh_nodedata(nid, NULL);
10625830169fSReza Arbab 	free_percpu(pgdat->per_cpu_nodestats);
10639af3c2deSYasunori Goto 	arch_free_nodedata(pgdat);
10649af3c2deSYasunori Goto }
10659af3c2deSYasunori Goto 
10660a547039SKAMEZAWA Hiroyuki 
106701b0f197SToshi Kani /**
106801b0f197SToshi Kani  * try_online_node - online a node if offlined
1069e8b098fcSMike Rapoport  * @nid: the node ID
1070b9ff0360SOscar Salvador  * @set_node_online: Whether we want to online the node
1071cf23422bSminskey guo  * called by cpu_up() to online a node without onlined memory.
1072b9ff0360SOscar Salvador  *
1073b9ff0360SOscar Salvador  * Returns:
1074b9ff0360SOscar Salvador  * 1 -> a new node has been allocated
1075b9ff0360SOscar Salvador  * 0 -> the node is already online
1076b9ff0360SOscar Salvador  * -ENOMEM -> the node could not be allocated
1077cf23422bSminskey guo  */
1078c68ab18cSDavid Hildenbrand static int __try_online_node(int nid, bool set_node_online)
1079cf23422bSminskey guo {
1080cf23422bSminskey guo 	pg_data_t *pgdat;
1081b9ff0360SOscar Salvador 	int ret = 1;
1082cf23422bSminskey guo 
108301b0f197SToshi Kani 	if (node_online(nid))
108401b0f197SToshi Kani 		return 0;
108501b0f197SToshi Kani 
1086c68ab18cSDavid Hildenbrand 	pgdat = hotadd_new_pgdat(nid);
10877553e8f2SDavid Rientjes 	if (!pgdat) {
108801b0f197SToshi Kani 		pr_err("Cannot online node %d due to NULL pgdat\n", nid);
1089cf23422bSminskey guo 		ret = -ENOMEM;
1090cf23422bSminskey guo 		goto out;
1091cf23422bSminskey guo 	}
1092b9ff0360SOscar Salvador 
1093b9ff0360SOscar Salvador 	if (set_node_online) {
1094cf23422bSminskey guo 		node_set_online(nid);
1095cf23422bSminskey guo 		ret = register_one_node(nid);
1096cf23422bSminskey guo 		BUG_ON(ret);
1097b9ff0360SOscar Salvador 	}
1098cf23422bSminskey guo out:
1099b9ff0360SOscar Salvador 	return ret;
1100b9ff0360SOscar Salvador }
1101b9ff0360SOscar Salvador 
1102b9ff0360SOscar Salvador /*
1103b9ff0360SOscar Salvador  * Users of this function always want to online/register the node
1104b9ff0360SOscar Salvador  */
1105b9ff0360SOscar Salvador int try_online_node(int nid)
1106b9ff0360SOscar Salvador {
1107b9ff0360SOscar Salvador 	int ret;
1108b9ff0360SOscar Salvador 
1109b9ff0360SOscar Salvador 	mem_hotplug_begin();
1110c68ab18cSDavid Hildenbrand 	ret =  __try_online_node(nid, true);
1111bfc8c901SVladimir Davydov 	mem_hotplug_done();
1112cf23422bSminskey guo 	return ret;
1113cf23422bSminskey guo }
1114cf23422bSminskey guo 
111527356f54SToshi Kani static int check_hotplug_memory_range(u64 start, u64 size)
111627356f54SToshi Kani {
1117ba325585SPavel Tatashin 	/* memory range must be block size aligned */
1118cec3ebd0SDavid Hildenbrand 	if (!size || !IS_ALIGNED(start, memory_block_size_bytes()) ||
1119cec3ebd0SDavid Hildenbrand 	    !IS_ALIGNED(size, memory_block_size_bytes())) {
1120ba325585SPavel Tatashin 		pr_err("Block size [%#lx] unaligned hotplug range: start %#llx, size %#llx",
1121cec3ebd0SDavid Hildenbrand 		       memory_block_size_bytes(), start, size);
112227356f54SToshi Kani 		return -EINVAL;
112327356f54SToshi Kani 	}
112427356f54SToshi Kani 
112527356f54SToshi Kani 	return 0;
112627356f54SToshi Kani }
112727356f54SToshi Kani 
112831bc3858SVitaly Kuznetsov static int online_memory_block(struct memory_block *mem, void *arg)
112931bc3858SVitaly Kuznetsov {
11301adf8b46SAnshuman Khandual 	mem->online_type = mhp_default_online_type;
1131dc18d706SNathan Fontenot 	return device_online(&mem->dev);
113231bc3858SVitaly Kuznetsov }
113331bc3858SVitaly Kuznetsov 
1134*a08a2ae3SOscar Salvador bool mhp_supports_memmap_on_memory(unsigned long size)
1135*a08a2ae3SOscar Salvador {
1136*a08a2ae3SOscar Salvador 	unsigned long nr_vmemmap_pages = size / PAGE_SIZE;
1137*a08a2ae3SOscar Salvador 	unsigned long vmemmap_size = nr_vmemmap_pages * sizeof(struct page);
1138*a08a2ae3SOscar Salvador 	unsigned long remaining_size = size - vmemmap_size;
1139*a08a2ae3SOscar Salvador 
1140*a08a2ae3SOscar Salvador 	/*
1141*a08a2ae3SOscar Salvador 	 * Besides having arch support and the feature enabled at runtime, we
1142*a08a2ae3SOscar Salvador 	 * need a few more assumptions to hold true:
1143*a08a2ae3SOscar Salvador 	 *
1144*a08a2ae3SOscar Salvador 	 * a) We span a single memory block: memory onlining/offlinin;g happens
1145*a08a2ae3SOscar Salvador 	 *    in memory block granularity. We don't want the vmemmap of online
1146*a08a2ae3SOscar Salvador 	 *    memory blocks to reside on offline memory blocks. In the future,
1147*a08a2ae3SOscar Salvador 	 *    we might want to support variable-sized memory blocks to make the
1148*a08a2ae3SOscar Salvador 	 *    feature more versatile.
1149*a08a2ae3SOscar Salvador 	 *
1150*a08a2ae3SOscar Salvador 	 * b) The vmemmap pages span complete PMDs: We don't want vmemmap code
1151*a08a2ae3SOscar Salvador 	 *    to populate memory from the altmap for unrelated parts (i.e.,
1152*a08a2ae3SOscar Salvador 	 *    other memory blocks)
1153*a08a2ae3SOscar Salvador 	 *
1154*a08a2ae3SOscar Salvador 	 * c) The vmemmap pages (and thereby the pages that will be exposed to
1155*a08a2ae3SOscar Salvador 	 *    the buddy) have to cover full pageblocks: memory onlining/offlining
1156*a08a2ae3SOscar Salvador 	 *    code requires applicable ranges to be page-aligned, for example, to
1157*a08a2ae3SOscar Salvador 	 *    set the migratetypes properly.
1158*a08a2ae3SOscar Salvador 	 *
1159*a08a2ae3SOscar Salvador 	 * TODO: Although we have a check here to make sure that vmemmap pages
1160*a08a2ae3SOscar Salvador 	 *       fully populate a PMD, it is not the right place to check for
1161*a08a2ae3SOscar Salvador 	 *       this. A much better solution involves improving vmemmap code
1162*a08a2ae3SOscar Salvador 	 *       to fallback to base pages when trying to populate vmemmap using
1163*a08a2ae3SOscar Salvador 	 *       altmap as an alternative source of memory, and we do not exactly
1164*a08a2ae3SOscar Salvador 	 *       populate a single PMD.
1165*a08a2ae3SOscar Salvador 	 */
1166*a08a2ae3SOscar Salvador 	return memmap_on_memory &&
1167*a08a2ae3SOscar Salvador 	       IS_ENABLED(CONFIG_MHP_MEMMAP_ON_MEMORY) &&
1168*a08a2ae3SOscar Salvador 	       size == memory_block_size_bytes() &&
1169*a08a2ae3SOscar Salvador 	       IS_ALIGNED(vmemmap_size, PMD_SIZE) &&
1170*a08a2ae3SOscar Salvador 	       IS_ALIGNED(remaining_size, (pageblock_nr_pages << PAGE_SHIFT));
1171*a08a2ae3SOscar Salvador }
1172*a08a2ae3SOscar Salvador 
11738df1d0e4SDavid Hildenbrand /*
11748df1d0e4SDavid Hildenbrand  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
11758df1d0e4SDavid Hildenbrand  * and online/offline operations (triggered e.g. by sysfs).
11768df1d0e4SDavid Hildenbrand  *
11778df1d0e4SDavid Hildenbrand  * we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG
11788df1d0e4SDavid Hildenbrand  */
1179b6117199SDavid Hildenbrand int __ref add_memory_resource(int nid, struct resource *res, mhp_t mhp_flags)
1180bc02af93SYasunori Goto {
1181d15dfd31SCatalin Marinas 	struct mhp_params params = { .pgprot = pgprot_mhp(PAGE_KERNEL) };
1182*a08a2ae3SOscar Salvador 	struct vmem_altmap mhp_altmap = {};
118362cedb9fSDavid Vrabel 	u64 start, size;
1184b9ff0360SOscar Salvador 	bool new_node = false;
1185bc02af93SYasunori Goto 	int ret;
1186bc02af93SYasunori Goto 
118762cedb9fSDavid Vrabel 	start = res->start;
118862cedb9fSDavid Vrabel 	size = resource_size(res);
118962cedb9fSDavid Vrabel 
119027356f54SToshi Kani 	ret = check_hotplug_memory_range(start, size);
119127356f54SToshi Kani 	if (ret)
119227356f54SToshi Kani 		return ret;
119327356f54SToshi Kani 
1194fa6d9ec7SVishal Verma 	if (!node_possible(nid)) {
1195fa6d9ec7SVishal Verma 		WARN(1, "node %d was absent from the node_possible_map\n", nid);
1196fa6d9ec7SVishal Verma 		return -EINVAL;
1197fa6d9ec7SVishal Verma 	}
1198fa6d9ec7SVishal Verma 
1199bfc8c901SVladimir Davydov 	mem_hotplug_begin();
1200ac13c462SNathan Zimmer 
120152219aeaSDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
12027f36e3e5STang Chen 		memblock_add_node(start, size, nid);
12037f36e3e5STang Chen 
1204c68ab18cSDavid Hildenbrand 	ret = __try_online_node(nid, false);
1205b9ff0360SOscar Salvador 	if (ret < 0)
120641b9e2d7SWen Congyang 		goto error;
1207b9ff0360SOscar Salvador 	new_node = ret;
12089af3c2deSYasunori Goto 
1209*a08a2ae3SOscar Salvador 	/*
1210*a08a2ae3SOscar Salvador 	 * Self hosted memmap array
1211*a08a2ae3SOscar Salvador 	 */
1212*a08a2ae3SOscar Salvador 	if (mhp_flags & MHP_MEMMAP_ON_MEMORY) {
1213*a08a2ae3SOscar Salvador 		if (!mhp_supports_memmap_on_memory(size)) {
1214*a08a2ae3SOscar Salvador 			ret = -EINVAL;
1215*a08a2ae3SOscar Salvador 			goto error;
1216*a08a2ae3SOscar Salvador 		}
1217*a08a2ae3SOscar Salvador 		mhp_altmap.free = PHYS_PFN(size);
1218*a08a2ae3SOscar Salvador 		mhp_altmap.base_pfn = PHYS_PFN(start);
1219*a08a2ae3SOscar Salvador 		params.altmap = &mhp_altmap;
1220*a08a2ae3SOscar Salvador 	}
1221*a08a2ae3SOscar Salvador 
1222bc02af93SYasunori Goto 	/* call arch's memory hotadd */
1223f5637d3bSLogan Gunthorpe 	ret = arch_add_memory(nid, start, size, &params);
12249af3c2deSYasunori Goto 	if (ret < 0)
12259af3c2deSYasunori Goto 		goto error;
12269af3c2deSYasunori Goto 
1227db051a0dSDavid Hildenbrand 	/* create memory block devices after memory was added */
1228*a08a2ae3SOscar Salvador 	ret = create_memory_block_devices(start, size, mhp_altmap.alloc);
1229db051a0dSDavid Hildenbrand 	if (ret) {
1230db051a0dSDavid Hildenbrand 		arch_remove_memory(nid, start, size, NULL);
1231db051a0dSDavid Hildenbrand 		goto error;
1232db051a0dSDavid Hildenbrand 	}
1233db051a0dSDavid Hildenbrand 
1234a1e565aaSTang Chen 	if (new_node) {
1235d5b6f6a3SOscar Salvador 		/* If sysfs file of new node can't be created, cpu on the node
12360fc44159SYasunori Goto 		 * can't be hot-added. There is no rollback way now.
12370fc44159SYasunori Goto 		 * So, check by BUG_ON() to catch it reluctantly..
1238d5b6f6a3SOscar Salvador 		 * We online node here. We can't roll back from here.
12390fc44159SYasunori Goto 		 */
1240d5b6f6a3SOscar Salvador 		node_set_online(nid);
1241d5b6f6a3SOscar Salvador 		ret = __register_one_node(nid);
12420fc44159SYasunori Goto 		BUG_ON(ret);
12430fc44159SYasunori Goto 	}
12440fc44159SYasunori Goto 
1245d5b6f6a3SOscar Salvador 	/* link memory sections under this node.*/
124690c7eaebSLaurent Dufour 	link_mem_sections(nid, PFN_DOWN(start), PFN_UP(start + size - 1),
1247f85086f9SLaurent Dufour 			  MEMINIT_HOTPLUG);
1248d5b6f6a3SOscar Salvador 
1249d96ae530Sakpm@linux-foundation.org 	/* create new memmap entry */
12507b7b2721SDavid Hildenbrand 	if (!strcmp(res->name, "System RAM"))
1251d96ae530Sakpm@linux-foundation.org 		firmware_map_add_hotplug(start, start + size, "System RAM");
1252d96ae530Sakpm@linux-foundation.org 
1253381eab4aSDavid Hildenbrand 	/* device_online() will take the lock when calling online_pages() */
1254381eab4aSDavid Hildenbrand 	mem_hotplug_done();
1255381eab4aSDavid Hildenbrand 
12569ca6551eSDavid Hildenbrand 	/*
12579ca6551eSDavid Hildenbrand 	 * In case we're allowed to merge the resource, flag it and trigger
12589ca6551eSDavid Hildenbrand 	 * merging now that adding succeeded.
12599ca6551eSDavid Hildenbrand 	 */
126026011267SDavid Hildenbrand 	if (mhp_flags & MHP_MERGE_RESOURCE)
12619ca6551eSDavid Hildenbrand 		merge_system_ram_resource(res);
12629ca6551eSDavid Hildenbrand 
126331bc3858SVitaly Kuznetsov 	/* online pages if requested */
12641adf8b46SAnshuman Khandual 	if (mhp_default_online_type != MMOP_OFFLINE)
1265fbcf73ceSDavid Hildenbrand 		walk_memory_blocks(start, size, NULL, online_memory_block);
126631bc3858SVitaly Kuznetsov 
1267381eab4aSDavid Hildenbrand 	return ret;
12689af3c2deSYasunori Goto error:
12699af3c2deSYasunori Goto 	/* rollback pgdat allocation and others */
1270b9ff0360SOscar Salvador 	if (new_node)
1271b9ff0360SOscar Salvador 		rollback_node_hotadd(nid);
127252219aeaSDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
12737f36e3e5STang Chen 		memblock_remove(start, size);
1274bfc8c901SVladimir Davydov 	mem_hotplug_done();
1275bc02af93SYasunori Goto 	return ret;
1276bc02af93SYasunori Goto }
127762cedb9fSDavid Vrabel 
12788df1d0e4SDavid Hildenbrand /* requires device_hotplug_lock, see add_memory_resource() */
1279b6117199SDavid Hildenbrand int __ref __add_memory(int nid, u64 start, u64 size, mhp_t mhp_flags)
128062cedb9fSDavid Vrabel {
128162cedb9fSDavid Vrabel 	struct resource *res;
128262cedb9fSDavid Vrabel 	int ret;
128362cedb9fSDavid Vrabel 
12847b7b2721SDavid Hildenbrand 	res = register_memory_resource(start, size, "System RAM");
12856f754ba4SVitaly Kuznetsov 	if (IS_ERR(res))
12866f754ba4SVitaly Kuznetsov 		return PTR_ERR(res);
128762cedb9fSDavid Vrabel 
1288b6117199SDavid Hildenbrand 	ret = add_memory_resource(nid, res, mhp_flags);
128962cedb9fSDavid Vrabel 	if (ret < 0)
129062cedb9fSDavid Vrabel 		release_memory_resource(res);
129162cedb9fSDavid Vrabel 	return ret;
129262cedb9fSDavid Vrabel }
12938df1d0e4SDavid Hildenbrand 
1294b6117199SDavid Hildenbrand int add_memory(int nid, u64 start, u64 size, mhp_t mhp_flags)
12958df1d0e4SDavid Hildenbrand {
12968df1d0e4SDavid Hildenbrand 	int rc;
12978df1d0e4SDavid Hildenbrand 
12988df1d0e4SDavid Hildenbrand 	lock_device_hotplug();
1299b6117199SDavid Hildenbrand 	rc = __add_memory(nid, start, size, mhp_flags);
13008df1d0e4SDavid Hildenbrand 	unlock_device_hotplug();
13018df1d0e4SDavid Hildenbrand 
13028df1d0e4SDavid Hildenbrand 	return rc;
13038df1d0e4SDavid Hildenbrand }
1304bc02af93SYasunori Goto EXPORT_SYMBOL_GPL(add_memory);
13050c0e6195SKAMEZAWA Hiroyuki 
13067b7b2721SDavid Hildenbrand /*
13077b7b2721SDavid Hildenbrand  * Add special, driver-managed memory to the system as system RAM. Such
13087b7b2721SDavid Hildenbrand  * memory is not exposed via the raw firmware-provided memmap as system
13097b7b2721SDavid Hildenbrand  * RAM, instead, it is detected and added by a driver - during cold boot,
13107b7b2721SDavid Hildenbrand  * after a reboot, and after kexec.
13117b7b2721SDavid Hildenbrand  *
13127b7b2721SDavid Hildenbrand  * Reasons why this memory should not be used for the initial memmap of a
13137b7b2721SDavid Hildenbrand  * kexec kernel or for placing kexec images:
13147b7b2721SDavid Hildenbrand  * - The booting kernel is in charge of determining how this memory will be
13157b7b2721SDavid Hildenbrand  *   used (e.g., use persistent memory as system RAM)
13167b7b2721SDavid Hildenbrand  * - Coordination with a hypervisor is required before this memory
13177b7b2721SDavid Hildenbrand  *   can be used (e.g., inaccessible parts).
13187b7b2721SDavid Hildenbrand  *
13197b7b2721SDavid Hildenbrand  * For this memory, no entries in /sys/firmware/memmap ("raw firmware-provided
13207b7b2721SDavid Hildenbrand  * memory map") are created. Also, the created memory resource is flagged
13217cf603d1SDavid Hildenbrand  * with IORESOURCE_SYSRAM_DRIVER_MANAGED, so in-kernel users can special-case
13227b7b2721SDavid Hildenbrand  * this memory as well (esp., not place kexec images onto it).
13237b7b2721SDavid Hildenbrand  *
13247b7b2721SDavid Hildenbrand  * The resource_name (visible via /proc/iomem) has to have the format
13257b7b2721SDavid Hildenbrand  * "System RAM ($DRIVER)".
13267b7b2721SDavid Hildenbrand  */
13277b7b2721SDavid Hildenbrand int add_memory_driver_managed(int nid, u64 start, u64 size,
1328b6117199SDavid Hildenbrand 			      const char *resource_name, mhp_t mhp_flags)
13297b7b2721SDavid Hildenbrand {
13307b7b2721SDavid Hildenbrand 	struct resource *res;
13317b7b2721SDavid Hildenbrand 	int rc;
13327b7b2721SDavid Hildenbrand 
13337b7b2721SDavid Hildenbrand 	if (!resource_name ||
13347b7b2721SDavid Hildenbrand 	    strstr(resource_name, "System RAM (") != resource_name ||
13357b7b2721SDavid Hildenbrand 	    resource_name[strlen(resource_name) - 1] != ')')
13367b7b2721SDavid Hildenbrand 		return -EINVAL;
13377b7b2721SDavid Hildenbrand 
13387b7b2721SDavid Hildenbrand 	lock_device_hotplug();
13397b7b2721SDavid Hildenbrand 
13407b7b2721SDavid Hildenbrand 	res = register_memory_resource(start, size, resource_name);
13417b7b2721SDavid Hildenbrand 	if (IS_ERR(res)) {
13427b7b2721SDavid Hildenbrand 		rc = PTR_ERR(res);
13437b7b2721SDavid Hildenbrand 		goto out_unlock;
13447b7b2721SDavid Hildenbrand 	}
13457b7b2721SDavid Hildenbrand 
1346b6117199SDavid Hildenbrand 	rc = add_memory_resource(nid, res, mhp_flags);
13477b7b2721SDavid Hildenbrand 	if (rc < 0)
13487b7b2721SDavid Hildenbrand 		release_memory_resource(res);
13497b7b2721SDavid Hildenbrand 
13507b7b2721SDavid Hildenbrand out_unlock:
13517b7b2721SDavid Hildenbrand 	unlock_device_hotplug();
13527b7b2721SDavid Hildenbrand 	return rc;
13537b7b2721SDavid Hildenbrand }
13547b7b2721SDavid Hildenbrand EXPORT_SYMBOL_GPL(add_memory_driver_managed);
13557b7b2721SDavid Hildenbrand 
1356bca3feaaSAnshuman Khandual /*
1357bca3feaaSAnshuman Khandual  * Platforms should define arch_get_mappable_range() that provides
1358bca3feaaSAnshuman Khandual  * maximum possible addressable physical memory range for which the
1359bca3feaaSAnshuman Khandual  * linear mapping could be created. The platform returned address
1360bca3feaaSAnshuman Khandual  * range must adhere to these following semantics.
1361bca3feaaSAnshuman Khandual  *
1362bca3feaaSAnshuman Khandual  * - range.start <= range.end
1363bca3feaaSAnshuman Khandual  * - Range includes both end points [range.start..range.end]
1364bca3feaaSAnshuman Khandual  *
1365bca3feaaSAnshuman Khandual  * There is also a fallback definition provided here, allowing the
1366bca3feaaSAnshuman Khandual  * entire possible physical address range in case any platform does
1367bca3feaaSAnshuman Khandual  * not define arch_get_mappable_range().
1368bca3feaaSAnshuman Khandual  */
1369bca3feaaSAnshuman Khandual struct range __weak arch_get_mappable_range(void)
1370bca3feaaSAnshuman Khandual {
1371bca3feaaSAnshuman Khandual 	struct range mhp_range = {
1372bca3feaaSAnshuman Khandual 		.start = 0UL,
1373bca3feaaSAnshuman Khandual 		.end = -1ULL,
1374bca3feaaSAnshuman Khandual 	};
1375bca3feaaSAnshuman Khandual 	return mhp_range;
1376bca3feaaSAnshuman Khandual }
1377bca3feaaSAnshuman Khandual 
1378bca3feaaSAnshuman Khandual struct range mhp_get_pluggable_range(bool need_mapping)
1379bca3feaaSAnshuman Khandual {
1380bca3feaaSAnshuman Khandual 	const u64 max_phys = (1ULL << MAX_PHYSMEM_BITS) - 1;
1381bca3feaaSAnshuman Khandual 	struct range mhp_range;
1382bca3feaaSAnshuman Khandual 
1383bca3feaaSAnshuman Khandual 	if (need_mapping) {
1384bca3feaaSAnshuman Khandual 		mhp_range = arch_get_mappable_range();
1385bca3feaaSAnshuman Khandual 		if (mhp_range.start > max_phys) {
1386bca3feaaSAnshuman Khandual 			mhp_range.start = 0;
1387bca3feaaSAnshuman Khandual 			mhp_range.end = 0;
1388bca3feaaSAnshuman Khandual 		}
1389bca3feaaSAnshuman Khandual 		mhp_range.end = min_t(u64, mhp_range.end, max_phys);
1390bca3feaaSAnshuman Khandual 	} else {
1391bca3feaaSAnshuman Khandual 		mhp_range.start = 0;
1392bca3feaaSAnshuman Khandual 		mhp_range.end = max_phys;
1393bca3feaaSAnshuman Khandual 	}
1394bca3feaaSAnshuman Khandual 	return mhp_range;
1395bca3feaaSAnshuman Khandual }
1396bca3feaaSAnshuman Khandual EXPORT_SYMBOL_GPL(mhp_get_pluggable_range);
1397bca3feaaSAnshuman Khandual 
1398bca3feaaSAnshuman Khandual bool mhp_range_allowed(u64 start, u64 size, bool need_mapping)
1399bca3feaaSAnshuman Khandual {
1400bca3feaaSAnshuman Khandual 	struct range mhp_range = mhp_get_pluggable_range(need_mapping);
1401bca3feaaSAnshuman Khandual 	u64 end = start + size;
1402bca3feaaSAnshuman Khandual 
1403bca3feaaSAnshuman Khandual 	if (start < end && start >= mhp_range.start && (end - 1) <= mhp_range.end)
1404bca3feaaSAnshuman Khandual 		return true;
1405bca3feaaSAnshuman Khandual 
1406bca3feaaSAnshuman Khandual 	pr_warn("Hotplug memory [%#llx-%#llx] exceeds maximum addressable range [%#llx-%#llx]\n",
1407bca3feaaSAnshuman Khandual 		start, end, mhp_range.start, mhp_range.end);
1408bca3feaaSAnshuman Khandual 	return false;
1409bca3feaaSAnshuman Khandual }
1410bca3feaaSAnshuman Khandual 
14110c0e6195SKAMEZAWA Hiroyuki #ifdef CONFIG_MEMORY_HOTREMOVE
14120c0e6195SKAMEZAWA Hiroyuki /*
141392917998SDavid Hildenbrand  * Confirm all pages in a range [start, end) belong to the same zone (skipping
141492917998SDavid Hildenbrand  * memory holes). When true, return the zone.
14150c0e6195SKAMEZAWA Hiroyuki  */
141692917998SDavid Hildenbrand struct zone *test_pages_in_a_zone(unsigned long start_pfn,
141792917998SDavid Hildenbrand 				  unsigned long end_pfn)
14180c0e6195SKAMEZAWA Hiroyuki {
14195f0f2887SAndrew Banman 	unsigned long pfn, sec_end_pfn;
14200c0e6195SKAMEZAWA Hiroyuki 	struct zone *zone = NULL;
14210c0e6195SKAMEZAWA Hiroyuki 	struct page *page;
14220c0e6195SKAMEZAWA Hiroyuki 	int i;
1423deb88a2aSToshi Kani 	for (pfn = start_pfn, sec_end_pfn = SECTION_ALIGN_UP(start_pfn + 1);
14240c0e6195SKAMEZAWA Hiroyuki 	     pfn < end_pfn;
1425deb88a2aSToshi Kani 	     pfn = sec_end_pfn, sec_end_pfn += PAGES_PER_SECTION) {
14265f0f2887SAndrew Banman 		/* Make sure the memory section is present first */
14275f0f2887SAndrew Banman 		if (!present_section_nr(pfn_to_section_nr(pfn)))
14285f0f2887SAndrew Banman 			continue;
14295f0f2887SAndrew Banman 		for (; pfn < sec_end_pfn && pfn < end_pfn;
14300c0e6195SKAMEZAWA Hiroyuki 		     pfn += MAX_ORDER_NR_PAGES) {
14310c0e6195SKAMEZAWA Hiroyuki 			i = 0;
14320c0e6195SKAMEZAWA Hiroyuki 			/* This is just a CONFIG_HOLES_IN_ZONE check.*/
14335f0f2887SAndrew Banman 			while ((i < MAX_ORDER_NR_PAGES) &&
14345f0f2887SAndrew Banman 				!pfn_valid_within(pfn + i))
14350c0e6195SKAMEZAWA Hiroyuki 				i++;
1436d6d8c8a4Szhong jiang 			if (i == MAX_ORDER_NR_PAGES || pfn + i >= end_pfn)
14370c0e6195SKAMEZAWA Hiroyuki 				continue;
143824feb47cSMikhail Zaslonko 			/* Check if we got outside of the zone */
143924feb47cSMikhail Zaslonko 			if (zone && !zone_spans_pfn(zone, pfn + i))
144092917998SDavid Hildenbrand 				return NULL;
14410c0e6195SKAMEZAWA Hiroyuki 			page = pfn_to_page(pfn + i);
14420c0e6195SKAMEZAWA Hiroyuki 			if (zone && page_zone(page) != zone)
144392917998SDavid Hildenbrand 				return NULL;
14440c0e6195SKAMEZAWA Hiroyuki 			zone = page_zone(page);
14450c0e6195SKAMEZAWA Hiroyuki 		}
14465f0f2887SAndrew Banman 	}
1447deb88a2aSToshi Kani 
144892917998SDavid Hildenbrand 	return zone;
1449a96dfddbSToshi Kani }
14500c0e6195SKAMEZAWA Hiroyuki 
14510c0e6195SKAMEZAWA Hiroyuki /*
14520efadf48SYisheng Xie  * Scan pfn range [start,end) to find movable/migratable pages (LRU pages,
1453aa218795SDavid Hildenbrand  * non-lru movable pages and hugepages). Will skip over most unmovable
1454aa218795SDavid Hildenbrand  * pages (esp., pages that can be skipped when offlining), but bail out on
1455aa218795SDavid Hildenbrand  * definitely unmovable pages.
1456aa218795SDavid Hildenbrand  *
1457aa218795SDavid Hildenbrand  * Returns:
1458aa218795SDavid Hildenbrand  *	0 in case a movable page is found and movable_pfn was updated.
1459aa218795SDavid Hildenbrand  *	-ENOENT in case no movable page was found.
1460aa218795SDavid Hildenbrand  *	-EBUSY in case a definitely unmovable page was found.
14610c0e6195SKAMEZAWA Hiroyuki  */
1462aa218795SDavid Hildenbrand static int scan_movable_pages(unsigned long start, unsigned long end,
1463aa218795SDavid Hildenbrand 			      unsigned long *movable_pfn)
14640c0e6195SKAMEZAWA Hiroyuki {
14650c0e6195SKAMEZAWA Hiroyuki 	unsigned long pfn;
1466eeb0efd0SOscar Salvador 
14670c0e6195SKAMEZAWA Hiroyuki 	for (pfn = start; pfn < end; pfn++) {
1468eeb0efd0SOscar Salvador 		struct page *page, *head;
1469eeb0efd0SOscar Salvador 		unsigned long skip;
1470eeb0efd0SOscar Salvador 
1471eeb0efd0SOscar Salvador 		if (!pfn_valid(pfn))
1472eeb0efd0SOscar Salvador 			continue;
14730c0e6195SKAMEZAWA Hiroyuki 		page = pfn_to_page(pfn);
14740c0e6195SKAMEZAWA Hiroyuki 		if (PageLRU(page))
1475aa218795SDavid Hildenbrand 			goto found;
14760efadf48SYisheng Xie 		if (__PageMovable(page))
1477aa218795SDavid Hildenbrand 			goto found;
1478aa218795SDavid Hildenbrand 
1479aa218795SDavid Hildenbrand 		/*
1480aa218795SDavid Hildenbrand 		 * PageOffline() pages that are not marked __PageMovable() and
1481aa218795SDavid Hildenbrand 		 * have a reference count > 0 (after MEM_GOING_OFFLINE) are
1482aa218795SDavid Hildenbrand 		 * definitely unmovable. If their reference count would be 0,
1483aa218795SDavid Hildenbrand 		 * they could at least be skipped when offlining memory.
1484aa218795SDavid Hildenbrand 		 */
1485aa218795SDavid Hildenbrand 		if (PageOffline(page) && page_count(page))
1486aa218795SDavid Hildenbrand 			return -EBUSY;
1487eeb0efd0SOscar Salvador 
1488eeb0efd0SOscar Salvador 		if (!PageHuge(page))
1489eeb0efd0SOscar Salvador 			continue;
1490eeb0efd0SOscar Salvador 		head = compound_head(page);
14918f251a3dSMike Kravetz 		/*
14928f251a3dSMike Kravetz 		 * This test is racy as we hold no reference or lock.  The
14938f251a3dSMike Kravetz 		 * hugetlb page could have been free'ed and head is no longer
14948f251a3dSMike Kravetz 		 * a hugetlb page before the following check.  In such unlikely
14958f251a3dSMike Kravetz 		 * cases false positives and negatives are possible.  Calling
14968f251a3dSMike Kravetz 		 * code must deal with these scenarios.
14978f251a3dSMike Kravetz 		 */
14988f251a3dSMike Kravetz 		if (HPageMigratable(head))
1499aa218795SDavid Hildenbrand 			goto found;
1500d8c6546bSMatthew Wilcox (Oracle) 		skip = compound_nr(head) - (page - head);
1501eeb0efd0SOscar Salvador 		pfn += skip - 1;
15020c0e6195SKAMEZAWA Hiroyuki 	}
1503aa218795SDavid Hildenbrand 	return -ENOENT;
1504aa218795SDavid Hildenbrand found:
1505aa218795SDavid Hildenbrand 	*movable_pfn = pfn;
15060c0e6195SKAMEZAWA Hiroyuki 	return 0;
15070c0e6195SKAMEZAWA Hiroyuki }
15080c0e6195SKAMEZAWA Hiroyuki 
15090c0e6195SKAMEZAWA Hiroyuki static int
15100c0e6195SKAMEZAWA Hiroyuki do_migrate_range(unsigned long start_pfn, unsigned long end_pfn)
15110c0e6195SKAMEZAWA Hiroyuki {
15120c0e6195SKAMEZAWA Hiroyuki 	unsigned long pfn;
15136c357848SMatthew Wilcox (Oracle) 	struct page *page, *head;
15140c0e6195SKAMEZAWA Hiroyuki 	int ret = 0;
15150c0e6195SKAMEZAWA Hiroyuki 	LIST_HEAD(source);
15160c0e6195SKAMEZAWA Hiroyuki 
1517a85009c3SMichal Hocko 	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
15180c0e6195SKAMEZAWA Hiroyuki 		if (!pfn_valid(pfn))
15190c0e6195SKAMEZAWA Hiroyuki 			continue;
15200c0e6195SKAMEZAWA Hiroyuki 		page = pfn_to_page(pfn);
15216c357848SMatthew Wilcox (Oracle) 		head = compound_head(page);
1522c8721bbbSNaoya Horiguchi 
1523c8721bbbSNaoya Horiguchi 		if (PageHuge(page)) {
1524d8c6546bSMatthew Wilcox (Oracle) 			pfn = page_to_pfn(head) + compound_nr(head) - 1;
1525daf3538aSOscar Salvador 			isolate_huge_page(head, &source);
1526c8721bbbSNaoya Horiguchi 			continue;
152794723aafSMichal Hocko 		} else if (PageTransHuge(page))
15286c357848SMatthew Wilcox (Oracle) 			pfn = page_to_pfn(head) + thp_nr_pages(page) - 1;
1529c8721bbbSNaoya Horiguchi 
1530b15c8726SMichal Hocko 		/*
1531b15c8726SMichal Hocko 		 * HWPoison pages have elevated reference counts so the migration would
1532b15c8726SMichal Hocko 		 * fail on them. It also doesn't make any sense to migrate them in the
1533b15c8726SMichal Hocko 		 * first place. Still try to unmap such a page in case it is still mapped
1534b15c8726SMichal Hocko 		 * (e.g. current hwpoison implementation doesn't unmap KSM pages but keep
1535b15c8726SMichal Hocko 		 * the unmap as the catch all safety net).
1536b15c8726SMichal Hocko 		 */
1537b15c8726SMichal Hocko 		if (PageHWPoison(page)) {
1538b15c8726SMichal Hocko 			if (WARN_ON(PageLRU(page)))
1539b15c8726SMichal Hocko 				isolate_lru_page(page);
1540b15c8726SMichal Hocko 			if (page_mapped(page))
1541013339dfSShakeel Butt 				try_to_unmap(page, TTU_IGNORE_MLOCK);
1542b15c8726SMichal Hocko 			continue;
1543b15c8726SMichal Hocko 		}
1544b15c8726SMichal Hocko 
1545700c2a46SKonstantin Khlebnikov 		if (!get_page_unless_zero(page))
15460c0e6195SKAMEZAWA Hiroyuki 			continue;
15470c0e6195SKAMEZAWA Hiroyuki 		/*
15480efadf48SYisheng Xie 		 * We can skip free pages. And we can deal with pages on
15490efadf48SYisheng Xie 		 * LRU and non-lru movable pages.
15500c0e6195SKAMEZAWA Hiroyuki 		 */
15510efadf48SYisheng Xie 		if (PageLRU(page))
155262695a84SNick Piggin 			ret = isolate_lru_page(page);
15530efadf48SYisheng Xie 		else
15540efadf48SYisheng Xie 			ret = isolate_movable_page(page, ISOLATE_UNEVICTABLE);
15550c0e6195SKAMEZAWA Hiroyuki 		if (!ret) { /* Success */
155662695a84SNick Piggin 			list_add_tail(&page->lru, &source);
15570efadf48SYisheng Xie 			if (!__PageMovable(page))
1558599d0c95SMel Gorman 				inc_node_page_state(page, NR_ISOLATED_ANON +
15599de4f22aSHuang Ying 						    page_is_file_lru(page));
15606d9c285aSKOSAKI Motohiro 
15610c0e6195SKAMEZAWA Hiroyuki 		} else {
15622932c8b0SMichal Hocko 			pr_warn("failed to isolate pfn %lx\n", pfn);
15630efadf48SYisheng Xie 			dump_page(page, "isolation failed");
15641723058eSOscar Salvador 		}
1565700c2a46SKonstantin Khlebnikov 		put_page(page);
15660c0e6195SKAMEZAWA Hiroyuki 	}
1567f3ab2636SBob Liu 	if (!list_empty(&source)) {
1568203e6e5cSJoonsoo Kim 		nodemask_t nmask = node_states[N_MEMORY];
1569203e6e5cSJoonsoo Kim 		struct migration_target_control mtc = {
1570203e6e5cSJoonsoo Kim 			.nmask = &nmask,
1571203e6e5cSJoonsoo Kim 			.gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
1572203e6e5cSJoonsoo Kim 		};
1573203e6e5cSJoonsoo Kim 
1574203e6e5cSJoonsoo Kim 		/*
1575203e6e5cSJoonsoo Kim 		 * We have checked that migration range is on a single zone so
1576203e6e5cSJoonsoo Kim 		 * we can use the nid of the first page to all the others.
1577203e6e5cSJoonsoo Kim 		 */
1578203e6e5cSJoonsoo Kim 		mtc.nid = page_to_nid(list_first_entry(&source, struct page, lru));
1579203e6e5cSJoonsoo Kim 
1580203e6e5cSJoonsoo Kim 		/*
1581203e6e5cSJoonsoo Kim 		 * try to allocate from a different node but reuse this node
1582203e6e5cSJoonsoo Kim 		 * if there are no other online nodes to be used (e.g. we are
1583203e6e5cSJoonsoo Kim 		 * offlining a part of the only existing node)
1584203e6e5cSJoonsoo Kim 		 */
1585203e6e5cSJoonsoo Kim 		node_clear(mtc.nid, nmask);
1586203e6e5cSJoonsoo Kim 		if (nodes_empty(nmask))
1587203e6e5cSJoonsoo Kim 			node_set(mtc.nid, nmask);
1588203e6e5cSJoonsoo Kim 		ret = migrate_pages(&source, alloc_migration_target, NULL,
1589203e6e5cSJoonsoo Kim 			(unsigned long)&mtc, MIGRATE_SYNC, MR_MEMORY_HOTPLUG);
15902932c8b0SMichal Hocko 		if (ret) {
15912932c8b0SMichal Hocko 			list_for_each_entry(page, &source, lru) {
15922932c8b0SMichal Hocko 				pr_warn("migrating pfn %lx failed ret:%d ",
15932932c8b0SMichal Hocko 				       page_to_pfn(page), ret);
15942932c8b0SMichal Hocko 				dump_page(page, "migration failure");
15952932c8b0SMichal Hocko 			}
1596c8721bbbSNaoya Horiguchi 			putback_movable_pages(&source);
1597f3ab2636SBob Liu 		}
15982932c8b0SMichal Hocko 	}
15991723058eSOscar Salvador 
16000c0e6195SKAMEZAWA Hiroyuki 	return ret;
16010c0e6195SKAMEZAWA Hiroyuki }
16020c0e6195SKAMEZAWA Hiroyuki 
1603c5320926STang Chen static int __init cmdline_parse_movable_node(char *p)
1604c5320926STang Chen {
160555ac590cSTang Chen 	movable_node_enabled = true;
1606c5320926STang Chen 	return 0;
1607c5320926STang Chen }
1608c5320926STang Chen early_param("movable_node", cmdline_parse_movable_node);
1609c5320926STang Chen 
1610d9713679SLai Jiangshan /* check which state of node_states will be changed when offline memory */
1611d9713679SLai Jiangshan static void node_states_check_changes_offline(unsigned long nr_pages,
1612d9713679SLai Jiangshan 		struct zone *zone, struct memory_notify *arg)
1613d9713679SLai Jiangshan {
1614d9713679SLai Jiangshan 	struct pglist_data *pgdat = zone->zone_pgdat;
1615d9713679SLai Jiangshan 	unsigned long present_pages = 0;
161686b27beaSOscar Salvador 	enum zone_type zt;
1617d9713679SLai Jiangshan 
161898fa15f3SAnshuman Khandual 	arg->status_change_nid = NUMA_NO_NODE;
161998fa15f3SAnshuman Khandual 	arg->status_change_nid_normal = NUMA_NO_NODE;
162098fa15f3SAnshuman Khandual 	arg->status_change_nid_high = NUMA_NO_NODE;
162186b27beaSOscar Salvador 
162286b27beaSOscar Salvador 	/*
162386b27beaSOscar Salvador 	 * Check whether node_states[N_NORMAL_MEMORY] will be changed.
162486b27beaSOscar Salvador 	 * If the memory to be offline is within the range
162586b27beaSOscar Salvador 	 * [0..ZONE_NORMAL], and it is the last present memory there,
162686b27beaSOscar Salvador 	 * the zones in that range will become empty after the offlining,
162786b27beaSOscar Salvador 	 * thus we can determine that we need to clear the node from
162886b27beaSOscar Salvador 	 * node_states[N_NORMAL_MEMORY].
162986b27beaSOscar Salvador 	 */
163086b27beaSOscar Salvador 	for (zt = 0; zt <= ZONE_NORMAL; zt++)
163186b27beaSOscar Salvador 		present_pages += pgdat->node_zones[zt].present_pages;
163286b27beaSOscar Salvador 	if (zone_idx(zone) <= ZONE_NORMAL && nr_pages >= present_pages)
163386b27beaSOscar Salvador 		arg->status_change_nid_normal = zone_to_nid(zone);
1634d9713679SLai Jiangshan 
16356715ddf9SLai Jiangshan #ifdef CONFIG_HIGHMEM
16366715ddf9SLai Jiangshan 	/*
163786b27beaSOscar Salvador 	 * node_states[N_HIGH_MEMORY] contains nodes which
163886b27beaSOscar Salvador 	 * have normal memory or high memory.
163986b27beaSOscar Salvador 	 * Here we add the present_pages belonging to ZONE_HIGHMEM.
164086b27beaSOscar Salvador 	 * If the zone is within the range of [0..ZONE_HIGHMEM), and
164186b27beaSOscar Salvador 	 * we determine that the zones in that range become empty,
164286b27beaSOscar Salvador 	 * we need to clear the node for N_HIGH_MEMORY.
16436715ddf9SLai Jiangshan 	 */
164486b27beaSOscar Salvador 	present_pages += pgdat->node_zones[ZONE_HIGHMEM].present_pages;
164586b27beaSOscar Salvador 	if (zone_idx(zone) <= ZONE_HIGHMEM && nr_pages >= present_pages)
16466715ddf9SLai Jiangshan 		arg->status_change_nid_high = zone_to_nid(zone);
16476715ddf9SLai Jiangshan #endif
16486715ddf9SLai Jiangshan 
1649d9713679SLai Jiangshan 	/*
165086b27beaSOscar Salvador 	 * We have accounted the pages from [0..ZONE_NORMAL), and
165186b27beaSOscar Salvador 	 * in case of CONFIG_HIGHMEM the pages from ZONE_HIGHMEM
165286b27beaSOscar Salvador 	 * as well.
165386b27beaSOscar Salvador 	 * Here we count the possible pages from ZONE_MOVABLE.
165486b27beaSOscar Salvador 	 * If after having accounted all the pages, we see that the nr_pages
165586b27beaSOscar Salvador 	 * to be offlined is over or equal to the accounted pages,
165686b27beaSOscar Salvador 	 * we know that the node will become empty, and so, we can clear
165786b27beaSOscar Salvador 	 * it for N_MEMORY as well.
1658d9713679SLai Jiangshan 	 */
165986b27beaSOscar Salvador 	present_pages += pgdat->node_zones[ZONE_MOVABLE].present_pages;
1660d9713679SLai Jiangshan 
1661d9713679SLai Jiangshan 	if (nr_pages >= present_pages)
1662d9713679SLai Jiangshan 		arg->status_change_nid = zone_to_nid(zone);
1663d9713679SLai Jiangshan }
1664d9713679SLai Jiangshan 
1665d9713679SLai Jiangshan static void node_states_clear_node(int node, struct memory_notify *arg)
1666d9713679SLai Jiangshan {
1667d9713679SLai Jiangshan 	if (arg->status_change_nid_normal >= 0)
1668d9713679SLai Jiangshan 		node_clear_state(node, N_NORMAL_MEMORY);
1669d9713679SLai Jiangshan 
1670cf01f6f5SOscar Salvador 	if (arg->status_change_nid_high >= 0)
1671d9713679SLai Jiangshan 		node_clear_state(node, N_HIGH_MEMORY);
16726715ddf9SLai Jiangshan 
1673cf01f6f5SOscar Salvador 	if (arg->status_change_nid >= 0)
16746715ddf9SLai Jiangshan 		node_clear_state(node, N_MEMORY);
1675d9713679SLai Jiangshan }
1676d9713679SLai Jiangshan 
1677c5e79ef5SDavid Hildenbrand static int count_system_ram_pages_cb(unsigned long start_pfn,
1678c5e79ef5SDavid Hildenbrand 				     unsigned long nr_pages, void *data)
1679c5e79ef5SDavid Hildenbrand {
1680c5e79ef5SDavid Hildenbrand 	unsigned long *nr_system_ram_pages = data;
1681c5e79ef5SDavid Hildenbrand 
1682c5e79ef5SDavid Hildenbrand 	*nr_system_ram_pages += nr_pages;
1683c5e79ef5SDavid Hildenbrand 	return 0;
1684c5e79ef5SDavid Hildenbrand }
1685c5e79ef5SDavid Hildenbrand 
168673a11c96SDavid Hildenbrand int __ref offline_pages(unsigned long start_pfn, unsigned long nr_pages)
16870c0e6195SKAMEZAWA Hiroyuki {
168873a11c96SDavid Hildenbrand 	const unsigned long end_pfn = start_pfn + nr_pages;
16890a1a9a00SDavid Hildenbrand 	unsigned long pfn, system_ram_pages = 0;
1690d702909fSCody P Schafer 	unsigned long flags;
16910c0e6195SKAMEZAWA Hiroyuki 	struct zone *zone;
16927b78d335SYasunori Goto 	struct memory_notify arg;
1693ea15153cSDavid Hildenbrand 	int ret, node;
169479605093SMichal Hocko 	char *reason;
16950c0e6195SKAMEZAWA Hiroyuki 
1696dd8e2f23SOscar Salvador 	/*
1697dd8e2f23SOscar Salvador 	 * {on,off}lining is constrained to full memory sections (or more
1698dd8e2f23SOscar Salvador 	 * precisly to memory blocks from the user space POV).
1699dd8e2f23SOscar Salvador 	 * memmap_on_memory is an exception because it reserves initial part
1700dd8e2f23SOscar Salvador 	 * of the physical memory space for vmemmaps. That space is pageblock
1701dd8e2f23SOscar Salvador 	 * aligned.
1702dd8e2f23SOscar Salvador 	 */
17034986fac1SDavid Hildenbrand 	if (WARN_ON_ONCE(!nr_pages ||
1704dd8e2f23SOscar Salvador 			 !IS_ALIGNED(start_pfn, pageblock_nr_pages) ||
1705dd8e2f23SOscar Salvador 			 !IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION)))
17064986fac1SDavid Hildenbrand 		return -EINVAL;
17074986fac1SDavid Hildenbrand 
1708381eab4aSDavid Hildenbrand 	mem_hotplug_begin();
1709381eab4aSDavid Hildenbrand 
1710c5e79ef5SDavid Hildenbrand 	/*
1711c5e79ef5SDavid Hildenbrand 	 * Don't allow to offline memory blocks that contain holes.
1712c5e79ef5SDavid Hildenbrand 	 * Consequently, memory blocks with holes can never get onlined
1713c5e79ef5SDavid Hildenbrand 	 * via the hotplug path - online_pages() - as hotplugged memory has
1714c5e79ef5SDavid Hildenbrand 	 * no holes. This way, we e.g., don't have to worry about marking
1715c5e79ef5SDavid Hildenbrand 	 * memory holes PG_reserved, don't need pfn_valid() checks, and can
1716c5e79ef5SDavid Hildenbrand 	 * avoid using walk_system_ram_range() later.
1717c5e79ef5SDavid Hildenbrand 	 */
171873a11c96SDavid Hildenbrand 	walk_system_ram_range(start_pfn, nr_pages, &system_ram_pages,
1719c5e79ef5SDavid Hildenbrand 			      count_system_ram_pages_cb);
172073a11c96SDavid Hildenbrand 	if (system_ram_pages != nr_pages) {
1721c5e79ef5SDavid Hildenbrand 		ret = -EINVAL;
1722c5e79ef5SDavid Hildenbrand 		reason = "memory holes";
1723c5e79ef5SDavid Hildenbrand 		goto failed_removal;
1724c5e79ef5SDavid Hildenbrand 	}
1725c5e79ef5SDavid Hildenbrand 
17260c0e6195SKAMEZAWA Hiroyuki 	/* This makes hotplug much easier...and readable.
17270c0e6195SKAMEZAWA Hiroyuki 	   we assume this for now. .*/
172892917998SDavid Hildenbrand 	zone = test_pages_in_a_zone(start_pfn, end_pfn);
172992917998SDavid Hildenbrand 	if (!zone) {
173079605093SMichal Hocko 		ret = -EINVAL;
173179605093SMichal Hocko 		reason = "multizone range";
173279605093SMichal Hocko 		goto failed_removal;
1733381eab4aSDavid Hildenbrand 	}
17347b78d335SYasunori Goto 	node = zone_to_nid(zone);
17357b78d335SYasunori Goto 
1736ec6e8c7eSVlastimil Babka 	/*
1737ec6e8c7eSVlastimil Babka 	 * Disable pcplists so that page isolation cannot race with freeing
1738ec6e8c7eSVlastimil Babka 	 * in a way that pages from isolated pageblock are left on pcplists.
1739ec6e8c7eSVlastimil Babka 	 */
1740ec6e8c7eSVlastimil Babka 	zone_pcp_disable(zone);
1741d479960eSMinchan Kim 	lru_cache_disable();
1742ec6e8c7eSVlastimil Babka 
17430c0e6195SKAMEZAWA Hiroyuki 	/* set above range as isolated */
1744b023f468SWen Congyang 	ret = start_isolate_page_range(start_pfn, end_pfn,
1745d381c547SMichal Hocko 				       MIGRATE_MOVABLE,
1746756d25beSDavid Hildenbrand 				       MEMORY_OFFLINE | REPORT_FAILURE);
17473fa0c7c7SDavid Hildenbrand 	if (ret) {
174879605093SMichal Hocko 		reason = "failure to isolate range";
1749ec6e8c7eSVlastimil Babka 		goto failed_removal_pcplists_disabled;
1750381eab4aSDavid Hildenbrand 	}
17517b78d335SYasunori Goto 
17527b78d335SYasunori Goto 	arg.start_pfn = start_pfn;
17537b78d335SYasunori Goto 	arg.nr_pages = nr_pages;
1754d9713679SLai Jiangshan 	node_states_check_changes_offline(nr_pages, zone, &arg);
17557b78d335SYasunori Goto 
17567b78d335SYasunori Goto 	ret = memory_notify(MEM_GOING_OFFLINE, &arg);
17577b78d335SYasunori Goto 	ret = notifier_to_errno(ret);
175879605093SMichal Hocko 	if (ret) {
175979605093SMichal Hocko 		reason = "notifier failure";
176079605093SMichal Hocko 		goto failed_removal_isolated;
176179605093SMichal Hocko 	}
17627b78d335SYasunori Goto 
1763bb8965bdSMichal Hocko 	do {
1764aa218795SDavid Hildenbrand 		pfn = start_pfn;
1765aa218795SDavid Hildenbrand 		do {
176679605093SMichal Hocko 			if (signal_pending(current)) {
1767bb8965bdSMichal Hocko 				ret = -EINTR;
176879605093SMichal Hocko 				reason = "signal backoff";
176979605093SMichal Hocko 				goto failed_removal_isolated;
177079605093SMichal Hocko 			}
177172b39cfcSMichal Hocko 
17720c0e6195SKAMEZAWA Hiroyuki 			cond_resched();
17730c0e6195SKAMEZAWA Hiroyuki 
1774aa218795SDavid Hildenbrand 			ret = scan_movable_pages(pfn, end_pfn, &pfn);
1775aa218795SDavid Hildenbrand 			if (!ret) {
1776bb8965bdSMichal Hocko 				/*
1777bb8965bdSMichal Hocko 				 * TODO: fatal migration failures should bail
1778bb8965bdSMichal Hocko 				 * out
1779bb8965bdSMichal Hocko 				 */
1780bb8965bdSMichal Hocko 				do_migrate_range(pfn, end_pfn);
1781bb8965bdSMichal Hocko 			}
1782aa218795SDavid Hildenbrand 		} while (!ret);
1783aa218795SDavid Hildenbrand 
1784aa218795SDavid Hildenbrand 		if (ret != -ENOENT) {
1785aa218795SDavid Hildenbrand 			reason = "unmovable page";
1786aa218795SDavid Hildenbrand 			goto failed_removal_isolated;
17870c0e6195SKAMEZAWA Hiroyuki 		}
178872b39cfcSMichal Hocko 
1789c8721bbbSNaoya Horiguchi 		/*
1790bb8965bdSMichal Hocko 		 * Dissolve free hugepages in the memory block before doing
1791bb8965bdSMichal Hocko 		 * offlining actually in order to make hugetlbfs's object
1792bb8965bdSMichal Hocko 		 * counting consistent.
1793c8721bbbSNaoya Horiguchi 		 */
1794082d5b6bSGerald Schaefer 		ret = dissolve_free_huge_pages(start_pfn, end_pfn);
179579605093SMichal Hocko 		if (ret) {
179679605093SMichal Hocko 			reason = "failure to dissolve huge pages";
179779605093SMichal Hocko 			goto failed_removal_isolated;
179879605093SMichal Hocko 		}
17990a1a9a00SDavid Hildenbrand 
18000a1a9a00SDavid Hildenbrand 		ret = test_pages_isolated(start_pfn, end_pfn, MEMORY_OFFLINE);
1801ec6e8c7eSVlastimil Babka 
18025557c766SMichal Hocko 	} while (ret);
1803bb8965bdSMichal Hocko 
18040a1a9a00SDavid Hildenbrand 	/* Mark all sections offline and remove free pages from the buddy. */
18050a1a9a00SDavid Hildenbrand 	__offline_isolated_pages(start_pfn, end_pfn);
18067c33023aSLaurent Dufour 	pr_debug("Offlined Pages %ld\n", nr_pages);
18070a1a9a00SDavid Hildenbrand 
18089b7ea46aSQian Cai 	/*
1809b30c5927SDavid Hildenbrand 	 * The memory sections are marked offline, and the pageblock flags
1810b30c5927SDavid Hildenbrand 	 * effectively stale; nobody should be touching them. Fixup the number
1811b30c5927SDavid Hildenbrand 	 * of isolated pageblocks, memory onlining will properly revert this.
18129b7ea46aSQian Cai 	 */
18139b7ea46aSQian Cai 	spin_lock_irqsave(&zone->lock, flags);
1814ea15153cSDavid Hildenbrand 	zone->nr_isolate_pageblock -= nr_pages / pageblock_nr_pages;
18159b7ea46aSQian Cai 	spin_unlock_irqrestore(&zone->lock, flags);
18169b7ea46aSQian Cai 
1817d479960eSMinchan Kim 	lru_cache_enable();
1818ec6e8c7eSVlastimil Babka 	zone_pcp_enable(zone);
1819ec6e8c7eSVlastimil Babka 
18200c0e6195SKAMEZAWA Hiroyuki 	/* removal success */
18210a1a9a00SDavid Hildenbrand 	adjust_managed_page_count(pfn_to_page(start_pfn), -nr_pages);
1822f9901144SDavid Hildenbrand 	adjust_present_page_count(zone, -nr_pages);
18237b78d335SYasunori Goto 
18241b79acc9SKOSAKI Motohiro 	init_per_zone_wmark_min();
18251b79acc9SKOSAKI Motohiro 
18261e8537baSXishi Qiu 	if (!populated_zone(zone)) {
1827340175b7SJiang Liu 		zone_pcp_reset(zone);
182872675e13SMichal Hocko 		build_all_zonelists(NULL);
18291e8537baSXishi Qiu 	} else
18301e8537baSXishi Qiu 		zone_pcp_update(zone);
1831340175b7SJiang Liu 
1832d9713679SLai Jiangshan 	node_states_clear_node(node, &arg);
1833698b1b30SVlastimil Babka 	if (arg.status_change_nid >= 0) {
18348fe23e05SDavid Rientjes 		kswapd_stop(node);
1835698b1b30SVlastimil Babka 		kcompactd_stop(node);
1836698b1b30SVlastimil Babka 	}
1837bce7394aSMinchan Kim 
18380c0e6195SKAMEZAWA Hiroyuki 	writeback_set_ratelimit();
18397b78d335SYasunori Goto 
18407b78d335SYasunori Goto 	memory_notify(MEM_OFFLINE, &arg);
1841feee6b29SDavid Hildenbrand 	remove_pfn_range_from_zone(zone, start_pfn, nr_pages);
1842381eab4aSDavid Hildenbrand 	mem_hotplug_done();
18430c0e6195SKAMEZAWA Hiroyuki 	return 0;
18440c0e6195SKAMEZAWA Hiroyuki 
184579605093SMichal Hocko failed_removal_isolated:
184679605093SMichal Hocko 	undo_isolate_page_range(start_pfn, end_pfn, MIGRATE_MOVABLE);
1847c4efe484SQian Cai 	memory_notify(MEM_CANCEL_OFFLINE, &arg);
1848ec6e8c7eSVlastimil Babka failed_removal_pcplists_disabled:
1849ec6e8c7eSVlastimil Babka 	zone_pcp_enable(zone);
18500c0e6195SKAMEZAWA Hiroyuki failed_removal:
185179605093SMichal Hocko 	pr_debug("memory offlining [mem %#010llx-%#010llx] failed due to %s\n",
1852a62e2f4fSBjorn Helgaas 		 (unsigned long long) start_pfn << PAGE_SHIFT,
185379605093SMichal Hocko 		 ((unsigned long long) end_pfn << PAGE_SHIFT) - 1,
185479605093SMichal Hocko 		 reason);
18550c0e6195SKAMEZAWA Hiroyuki 	/* pushback to free area */
1856381eab4aSDavid Hildenbrand 	mem_hotplug_done();
18570c0e6195SKAMEZAWA Hiroyuki 	return ret;
18580c0e6195SKAMEZAWA Hiroyuki }
185971088785SBadari Pulavarty 
1860d6de9d53SXishi Qiu static int check_memblock_offlined_cb(struct memory_block *mem, void *arg)
1861bbc76be6SWen Congyang {
1862bbc76be6SWen Congyang 	int ret = !is_memblock_offlined(mem);
1863bbc76be6SWen Congyang 
1864349daa0fSRandy Dunlap 	if (unlikely(ret)) {
1865349daa0fSRandy Dunlap 		phys_addr_t beginpa, endpa;
1866349daa0fSRandy Dunlap 
1867349daa0fSRandy Dunlap 		beginpa = PFN_PHYS(section_nr_to_pfn(mem->start_section_nr));
1868b6c88d3bSDavid Hildenbrand 		endpa = beginpa + memory_block_size_bytes() - 1;
1869756a025fSJoe Perches 		pr_warn("removing memory fails, because memory [%pa-%pa] is onlined\n",
1870349daa0fSRandy Dunlap 			&beginpa, &endpa);
1871bbc76be6SWen Congyang 
1872eca499abSPavel Tatashin 		return -EBUSY;
1873eca499abSPavel Tatashin 	}
1874eca499abSPavel Tatashin 	return 0;
1875bbc76be6SWen Congyang }
1876bbc76be6SWen Congyang 
1877*a08a2ae3SOscar Salvador static int get_nr_vmemmap_pages_cb(struct memory_block *mem, void *arg)
1878*a08a2ae3SOscar Salvador {
1879*a08a2ae3SOscar Salvador 	/*
1880*a08a2ae3SOscar Salvador 	 * If not set, continue with the next block.
1881*a08a2ae3SOscar Salvador 	 */
1882*a08a2ae3SOscar Salvador 	return mem->nr_vmemmap_pages;
1883*a08a2ae3SOscar Salvador }
1884*a08a2ae3SOscar Salvador 
18850f1cfe9dSToshi Kani static int check_cpu_on_node(pg_data_t *pgdat)
188660a5a19eSTang Chen {
188760a5a19eSTang Chen 	int cpu;
188860a5a19eSTang Chen 
188960a5a19eSTang Chen 	for_each_present_cpu(cpu) {
189060a5a19eSTang Chen 		if (cpu_to_node(cpu) == pgdat->node_id)
189160a5a19eSTang Chen 			/*
189260a5a19eSTang Chen 			 * the cpu on this node isn't removed, and we can't
189360a5a19eSTang Chen 			 * offline this node.
189460a5a19eSTang Chen 			 */
189560a5a19eSTang Chen 			return -EBUSY;
189660a5a19eSTang Chen 	}
189760a5a19eSTang Chen 
189860a5a19eSTang Chen 	return 0;
189960a5a19eSTang Chen }
190060a5a19eSTang Chen 
19012c91f8fcSDavid Hildenbrand static int check_no_memblock_for_node_cb(struct memory_block *mem, void *arg)
19022c91f8fcSDavid Hildenbrand {
19032c91f8fcSDavid Hildenbrand 	int nid = *(int *)arg;
19042c91f8fcSDavid Hildenbrand 
19052c91f8fcSDavid Hildenbrand 	/*
19062c91f8fcSDavid Hildenbrand 	 * If a memory block belongs to multiple nodes, the stored nid is not
19072c91f8fcSDavid Hildenbrand 	 * reliable. However, such blocks are always online (e.g., cannot get
19082c91f8fcSDavid Hildenbrand 	 * offlined) and, therefore, are still spanned by the node.
19092c91f8fcSDavid Hildenbrand 	 */
19102c91f8fcSDavid Hildenbrand 	return mem->nid == nid ? -EEXIST : 0;
19112c91f8fcSDavid Hildenbrand }
19122c91f8fcSDavid Hildenbrand 
19130f1cfe9dSToshi Kani /**
19140f1cfe9dSToshi Kani  * try_offline_node
1915e8b098fcSMike Rapoport  * @nid: the node ID
19160f1cfe9dSToshi Kani  *
19170f1cfe9dSToshi Kani  * Offline a node if all memory sections and cpus of the node are removed.
19180f1cfe9dSToshi Kani  *
19190f1cfe9dSToshi Kani  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
19200f1cfe9dSToshi Kani  * and online/offline operations before this call.
19210f1cfe9dSToshi Kani  */
192290b30cdcSWen Congyang void try_offline_node(int nid)
192360a5a19eSTang Chen {
1924d822b86aSWen Congyang 	pg_data_t *pgdat = NODE_DATA(nid);
19252c91f8fcSDavid Hildenbrand 	int rc;
192660a5a19eSTang Chen 
192760a5a19eSTang Chen 	/*
19282c91f8fcSDavid Hildenbrand 	 * If the node still spans pages (especially ZONE_DEVICE), don't
19292c91f8fcSDavid Hildenbrand 	 * offline it. A node spans memory after move_pfn_range_to_zone(),
19302c91f8fcSDavid Hildenbrand 	 * e.g., after the memory block was onlined.
193160a5a19eSTang Chen 	 */
19322c91f8fcSDavid Hildenbrand 	if (pgdat->node_spanned_pages)
193360a5a19eSTang Chen 		return;
19342c91f8fcSDavid Hildenbrand 
19352c91f8fcSDavid Hildenbrand 	/*
19362c91f8fcSDavid Hildenbrand 	 * Especially offline memory blocks might not be spanned by the
19372c91f8fcSDavid Hildenbrand 	 * node. They will get spanned by the node once they get onlined.
19382c91f8fcSDavid Hildenbrand 	 * However, they link to the node in sysfs and can get onlined later.
19392c91f8fcSDavid Hildenbrand 	 */
19402c91f8fcSDavid Hildenbrand 	rc = for_each_memory_block(&nid, check_no_memblock_for_node_cb);
19412c91f8fcSDavid Hildenbrand 	if (rc)
19422c91f8fcSDavid Hildenbrand 		return;
194360a5a19eSTang Chen 
194446a3679bSMichal Hocko 	if (check_cpu_on_node(pgdat))
194560a5a19eSTang Chen 		return;
194660a5a19eSTang Chen 
194760a5a19eSTang Chen 	/*
194860a5a19eSTang Chen 	 * all memory/cpu of this node are removed, we can offline this
194960a5a19eSTang Chen 	 * node now.
195060a5a19eSTang Chen 	 */
195160a5a19eSTang Chen 	node_set_offline(nid);
195260a5a19eSTang Chen 	unregister_one_node(nid);
195360a5a19eSTang Chen }
195490b30cdcSWen Congyang EXPORT_SYMBOL(try_offline_node);
195560a5a19eSTang Chen 
1956eca499abSPavel Tatashin static int __ref try_remove_memory(int nid, u64 start, u64 size)
1957bbc76be6SWen Congyang {
1958eca499abSPavel Tatashin 	int rc = 0;
1959*a08a2ae3SOscar Salvador 	struct vmem_altmap mhp_altmap = {};
1960*a08a2ae3SOscar Salvador 	struct vmem_altmap *altmap = NULL;
1961*a08a2ae3SOscar Salvador 	unsigned long nr_vmemmap_pages;
1962993c1aadSWen Congyang 
196327356f54SToshi Kani 	BUG_ON(check_hotplug_memory_range(start, size));
196427356f54SToshi Kani 
19656677e3eaSYasuaki Ishimatsu 	/*
1966242831ebSRafael J. Wysocki 	 * All memory blocks must be offlined before removing memory.  Check
1967eca499abSPavel Tatashin 	 * whether all memory blocks in question are offline and return error
1968242831ebSRafael J. Wysocki 	 * if this is not the case.
19696677e3eaSYasuaki Ishimatsu 	 */
1970fbcf73ceSDavid Hildenbrand 	rc = walk_memory_blocks(start, size, NULL, check_memblock_offlined_cb);
1971eca499abSPavel Tatashin 	if (rc)
1972b4223a51SJia He 		return rc;
19736677e3eaSYasuaki Ishimatsu 
1974*a08a2ae3SOscar Salvador 	/*
1975*a08a2ae3SOscar Salvador 	 * We only support removing memory added with MHP_MEMMAP_ON_MEMORY in
1976*a08a2ae3SOscar Salvador 	 * the same granularity it was added - a single memory block.
1977*a08a2ae3SOscar Salvador 	 */
1978*a08a2ae3SOscar Salvador 	if (memmap_on_memory) {
1979*a08a2ae3SOscar Salvador 		nr_vmemmap_pages = walk_memory_blocks(start, size, NULL,
1980*a08a2ae3SOscar Salvador 						      get_nr_vmemmap_pages_cb);
1981*a08a2ae3SOscar Salvador 		if (nr_vmemmap_pages) {
1982*a08a2ae3SOscar Salvador 			if (size != memory_block_size_bytes()) {
1983*a08a2ae3SOscar Salvador 				pr_warn("Refuse to remove %#llx - %#llx,"
1984*a08a2ae3SOscar Salvador 					"wrong granularity\n",
1985*a08a2ae3SOscar Salvador 					start, start + size);
1986*a08a2ae3SOscar Salvador 				return -EINVAL;
1987*a08a2ae3SOscar Salvador 			}
1988*a08a2ae3SOscar Salvador 
1989*a08a2ae3SOscar Salvador 			/*
1990*a08a2ae3SOscar Salvador 			 * Let remove_pmd_table->free_hugepage_table do the
1991*a08a2ae3SOscar Salvador 			 * right thing if we used vmem_altmap when hot-adding
1992*a08a2ae3SOscar Salvador 			 * the range.
1993*a08a2ae3SOscar Salvador 			 */
1994*a08a2ae3SOscar Salvador 			mhp_altmap.alloc = nr_vmemmap_pages;
1995*a08a2ae3SOscar Salvador 			altmap = &mhp_altmap;
1996*a08a2ae3SOscar Salvador 		}
1997*a08a2ae3SOscar Salvador 	}
1998*a08a2ae3SOscar Salvador 
199946c66c4bSYasuaki Ishimatsu 	/* remove memmap entry */
200046c66c4bSYasuaki Ishimatsu 	firmware_map_remove(start, start + size, "System RAM");
200146c66c4bSYasuaki Ishimatsu 
2002f1037ec0SDan Williams 	/*
2003f1037ec0SDan Williams 	 * Memory block device removal under the device_hotplug_lock is
2004f1037ec0SDan Williams 	 * a barrier against racing online attempts.
2005f1037ec0SDan Williams 	 */
20064c4b7f9bSDavid Hildenbrand 	remove_memory_block_devices(start, size);
20074c4b7f9bSDavid Hildenbrand 
2008f1037ec0SDan Williams 	mem_hotplug_begin();
2009f1037ec0SDan Williams 
2010*a08a2ae3SOscar Salvador 	arch_remove_memory(nid, start, size, altmap);
201152219aeaSDavid Hildenbrand 
201252219aeaSDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK)) {
201332d1fe8fSAnshuman Khandual 		memblock_free(start, size);
201432d1fe8fSAnshuman Khandual 		memblock_remove(start, size);
201552219aeaSDavid Hildenbrand 	}
201652219aeaSDavid Hildenbrand 
2017cb8e3c8bSDavid Hildenbrand 	release_mem_region_adjustable(start, size);
201824d335caSWen Congyang 
201960a5a19eSTang Chen 	try_offline_node(nid);
202060a5a19eSTang Chen 
2021bfc8c901SVladimir Davydov 	mem_hotplug_done();
2022b4223a51SJia He 	return 0;
202371088785SBadari Pulavarty }
2024d15e5926SDavid Hildenbrand 
2025eca499abSPavel Tatashin /**
2026eca499abSPavel Tatashin  * remove_memory
2027eca499abSPavel Tatashin  * @nid: the node ID
2028eca499abSPavel Tatashin  * @start: physical address of the region to remove
2029eca499abSPavel Tatashin  * @size: size of the region to remove
2030eca499abSPavel Tatashin  *
2031eca499abSPavel Tatashin  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
2032eca499abSPavel Tatashin  * and online/offline operations before this call, as required by
2033eca499abSPavel Tatashin  * try_offline_node().
2034eca499abSPavel Tatashin  */
2035eca499abSPavel Tatashin void __remove_memory(int nid, u64 start, u64 size)
2036d15e5926SDavid Hildenbrand {
2037eca499abSPavel Tatashin 
2038eca499abSPavel Tatashin 	/*
203929a90db9SSouptick Joarder 	 * trigger BUG() if some memory is not offlined prior to calling this
2040eca499abSPavel Tatashin 	 * function
2041eca499abSPavel Tatashin 	 */
2042eca499abSPavel Tatashin 	if (try_remove_memory(nid, start, size))
2043eca499abSPavel Tatashin 		BUG();
2044eca499abSPavel Tatashin }
2045eca499abSPavel Tatashin 
2046eca499abSPavel Tatashin /*
2047eca499abSPavel Tatashin  * Remove memory if every memory block is offline, otherwise return -EBUSY is
2048eca499abSPavel Tatashin  * some memory is not offline
2049eca499abSPavel Tatashin  */
2050eca499abSPavel Tatashin int remove_memory(int nid, u64 start, u64 size)
2051eca499abSPavel Tatashin {
2052eca499abSPavel Tatashin 	int rc;
2053eca499abSPavel Tatashin 
2054d15e5926SDavid Hildenbrand 	lock_device_hotplug();
2055eca499abSPavel Tatashin 	rc  = try_remove_memory(nid, start, size);
2056d15e5926SDavid Hildenbrand 	unlock_device_hotplug();
2057eca499abSPavel Tatashin 
2058eca499abSPavel Tatashin 	return rc;
2059d15e5926SDavid Hildenbrand }
206071088785SBadari Pulavarty EXPORT_SYMBOL_GPL(remove_memory);
206108b3acd7SDavid Hildenbrand 
20628dc4bb58SDavid Hildenbrand static int try_offline_memory_block(struct memory_block *mem, void *arg)
20638dc4bb58SDavid Hildenbrand {
20648dc4bb58SDavid Hildenbrand 	uint8_t online_type = MMOP_ONLINE_KERNEL;
20658dc4bb58SDavid Hildenbrand 	uint8_t **online_types = arg;
20668dc4bb58SDavid Hildenbrand 	struct page *page;
20678dc4bb58SDavid Hildenbrand 	int rc;
20688dc4bb58SDavid Hildenbrand 
206908b3acd7SDavid Hildenbrand 	/*
20708dc4bb58SDavid Hildenbrand 	 * Sense the online_type via the zone of the memory block. Offlining
20718dc4bb58SDavid Hildenbrand 	 * with multiple zones within one memory block will be rejected
20728dc4bb58SDavid Hildenbrand 	 * by offlining code ... so we don't care about that.
20738dc4bb58SDavid Hildenbrand 	 */
20748dc4bb58SDavid Hildenbrand 	page = pfn_to_online_page(section_nr_to_pfn(mem->start_section_nr));
20758dc4bb58SDavid Hildenbrand 	if (page && zone_idx(page_zone(page)) == ZONE_MOVABLE)
20768dc4bb58SDavid Hildenbrand 		online_type = MMOP_ONLINE_MOVABLE;
20778dc4bb58SDavid Hildenbrand 
20788dc4bb58SDavid Hildenbrand 	rc = device_offline(&mem->dev);
20798dc4bb58SDavid Hildenbrand 	/*
20808dc4bb58SDavid Hildenbrand 	 * Default is MMOP_OFFLINE - change it only if offlining succeeded,
20818dc4bb58SDavid Hildenbrand 	 * so try_reonline_memory_block() can do the right thing.
20828dc4bb58SDavid Hildenbrand 	 */
20838dc4bb58SDavid Hildenbrand 	if (!rc)
20848dc4bb58SDavid Hildenbrand 		**online_types = online_type;
20858dc4bb58SDavid Hildenbrand 
20868dc4bb58SDavid Hildenbrand 	(*online_types)++;
20878dc4bb58SDavid Hildenbrand 	/* Ignore if already offline. */
20888dc4bb58SDavid Hildenbrand 	return rc < 0 ? rc : 0;
20898dc4bb58SDavid Hildenbrand }
20908dc4bb58SDavid Hildenbrand 
20918dc4bb58SDavid Hildenbrand static int try_reonline_memory_block(struct memory_block *mem, void *arg)
20928dc4bb58SDavid Hildenbrand {
20938dc4bb58SDavid Hildenbrand 	uint8_t **online_types = arg;
20948dc4bb58SDavid Hildenbrand 	int rc;
20958dc4bb58SDavid Hildenbrand 
20968dc4bb58SDavid Hildenbrand 	if (**online_types != MMOP_OFFLINE) {
20978dc4bb58SDavid Hildenbrand 		mem->online_type = **online_types;
20988dc4bb58SDavid Hildenbrand 		rc = device_online(&mem->dev);
20998dc4bb58SDavid Hildenbrand 		if (rc < 0)
21008dc4bb58SDavid Hildenbrand 			pr_warn("%s: Failed to re-online memory: %d",
21018dc4bb58SDavid Hildenbrand 				__func__, rc);
21028dc4bb58SDavid Hildenbrand 	}
21038dc4bb58SDavid Hildenbrand 
21048dc4bb58SDavid Hildenbrand 	/* Continue processing all remaining memory blocks. */
21058dc4bb58SDavid Hildenbrand 	(*online_types)++;
21068dc4bb58SDavid Hildenbrand 	return 0;
21078dc4bb58SDavid Hildenbrand }
21088dc4bb58SDavid Hildenbrand 
21098dc4bb58SDavid Hildenbrand /*
21108dc4bb58SDavid Hildenbrand  * Try to offline and remove memory. Might take a long time to finish in case
21118dc4bb58SDavid Hildenbrand  * memory is still in use. Primarily useful for memory devices that logically
21128dc4bb58SDavid Hildenbrand  * unplugged all memory (so it's no longer in use) and want to offline + remove
21138dc4bb58SDavid Hildenbrand  * that memory.
211408b3acd7SDavid Hildenbrand  */
211508b3acd7SDavid Hildenbrand int offline_and_remove_memory(int nid, u64 start, u64 size)
211608b3acd7SDavid Hildenbrand {
21178dc4bb58SDavid Hildenbrand 	const unsigned long mb_count = size / memory_block_size_bytes();
21188dc4bb58SDavid Hildenbrand 	uint8_t *online_types, *tmp;
21198dc4bb58SDavid Hildenbrand 	int rc;
212008b3acd7SDavid Hildenbrand 
212108b3acd7SDavid Hildenbrand 	if (!IS_ALIGNED(start, memory_block_size_bytes()) ||
21228dc4bb58SDavid Hildenbrand 	    !IS_ALIGNED(size, memory_block_size_bytes()) || !size)
21238dc4bb58SDavid Hildenbrand 		return -EINVAL;
212408b3acd7SDavid Hildenbrand 
212508b3acd7SDavid Hildenbrand 	/*
21268dc4bb58SDavid Hildenbrand 	 * We'll remember the old online type of each memory block, so we can
21278dc4bb58SDavid Hildenbrand 	 * try to revert whatever we did when offlining one memory block fails
21288dc4bb58SDavid Hildenbrand 	 * after offlining some others succeeded.
21298dc4bb58SDavid Hildenbrand 	 */
21308dc4bb58SDavid Hildenbrand 	online_types = kmalloc_array(mb_count, sizeof(*online_types),
21318dc4bb58SDavid Hildenbrand 				     GFP_KERNEL);
21328dc4bb58SDavid Hildenbrand 	if (!online_types)
21338dc4bb58SDavid Hildenbrand 		return -ENOMEM;
21348dc4bb58SDavid Hildenbrand 	/*
21358dc4bb58SDavid Hildenbrand 	 * Initialize all states to MMOP_OFFLINE, so when we abort processing in
21368dc4bb58SDavid Hildenbrand 	 * try_offline_memory_block(), we'll skip all unprocessed blocks in
21378dc4bb58SDavid Hildenbrand 	 * try_reonline_memory_block().
21388dc4bb58SDavid Hildenbrand 	 */
21398dc4bb58SDavid Hildenbrand 	memset(online_types, MMOP_OFFLINE, mb_count);
21408dc4bb58SDavid Hildenbrand 
21418dc4bb58SDavid Hildenbrand 	lock_device_hotplug();
21428dc4bb58SDavid Hildenbrand 
21438dc4bb58SDavid Hildenbrand 	tmp = online_types;
21448dc4bb58SDavid Hildenbrand 	rc = walk_memory_blocks(start, size, &tmp, try_offline_memory_block);
21458dc4bb58SDavid Hildenbrand 
21468dc4bb58SDavid Hildenbrand 	/*
21478dc4bb58SDavid Hildenbrand 	 * In case we succeeded to offline all memory, remove it.
214808b3acd7SDavid Hildenbrand 	 * This cannot fail as it cannot get onlined in the meantime.
214908b3acd7SDavid Hildenbrand 	 */
215008b3acd7SDavid Hildenbrand 	if (!rc) {
215108b3acd7SDavid Hildenbrand 		rc = try_remove_memory(nid, start, size);
21528dc4bb58SDavid Hildenbrand 		if (rc)
21538dc4bb58SDavid Hildenbrand 			pr_err("%s: Failed to remove memory: %d", __func__, rc);
21548dc4bb58SDavid Hildenbrand 	}
21558dc4bb58SDavid Hildenbrand 
21568dc4bb58SDavid Hildenbrand 	/*
21578dc4bb58SDavid Hildenbrand 	 * Rollback what we did. While memory onlining might theoretically fail
21588dc4bb58SDavid Hildenbrand 	 * (nacked by a notifier), it barely ever happens.
21598dc4bb58SDavid Hildenbrand 	 */
21608dc4bb58SDavid Hildenbrand 	if (rc) {
21618dc4bb58SDavid Hildenbrand 		tmp = online_types;
21628dc4bb58SDavid Hildenbrand 		walk_memory_blocks(start, size, &tmp,
21638dc4bb58SDavid Hildenbrand 				   try_reonline_memory_block);
216408b3acd7SDavid Hildenbrand 	}
216508b3acd7SDavid Hildenbrand 	unlock_device_hotplug();
216608b3acd7SDavid Hildenbrand 
21678dc4bb58SDavid Hildenbrand 	kfree(online_types);
216808b3acd7SDavid Hildenbrand 	return rc;
216908b3acd7SDavid Hildenbrand }
217008b3acd7SDavid Hildenbrand EXPORT_SYMBOL_GPL(offline_and_remove_memory);
2171aba6efc4SRafael J. Wysocki #endif /* CONFIG_MEMORY_HOTREMOVE */
2172