xref: /openbmc/linux/mm/memory_hotplug.c (revision 73a11c9658577d876d4c70730719feab3fa328b0)
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 
459d0ad8caSDaniel Kiper /*
469d0ad8caSDaniel Kiper  * online_page_callback contains pointer to current page onlining function.
479d0ad8caSDaniel Kiper  * Initially it is generic_online_page(). If it is required it could be
489d0ad8caSDaniel Kiper  * changed by calling set_online_page_callback() for callback registration
499d0ad8caSDaniel Kiper  * and restore_online_page_callback() for generic callback restore.
509d0ad8caSDaniel Kiper  */
519d0ad8caSDaniel Kiper 
529d0ad8caSDaniel Kiper static online_page_callback_t online_page_callback = generic_online_page;
53bfc8c901SVladimir Davydov static DEFINE_MUTEX(online_page_callback_lock);
549d0ad8caSDaniel Kiper 
553f906ba2SThomas Gleixner DEFINE_STATIC_PERCPU_RWSEM(mem_hotplug_lock);
5620d6c96bSKOSAKI Motohiro 
573f906ba2SThomas Gleixner void get_online_mems(void)
583f906ba2SThomas Gleixner {
593f906ba2SThomas Gleixner 	percpu_down_read(&mem_hotplug_lock);
603f906ba2SThomas Gleixner }
61bfc8c901SVladimir Davydov 
623f906ba2SThomas Gleixner void put_online_mems(void)
633f906ba2SThomas Gleixner {
643f906ba2SThomas Gleixner 	percpu_up_read(&mem_hotplug_lock);
653f906ba2SThomas Gleixner }
66bfc8c901SVladimir Davydov 
674932381eSMichal Hocko bool movable_node_enabled = false;
684932381eSMichal Hocko 
698604d9e5SVitaly Kuznetsov #ifndef CONFIG_MEMORY_HOTPLUG_DEFAULT_ONLINE
70862919e5SDavid Hildenbrand int memhp_default_online_type = MMOP_OFFLINE;
718604d9e5SVitaly Kuznetsov #else
72862919e5SDavid Hildenbrand int memhp_default_online_type = MMOP_ONLINE;
738604d9e5SVitaly Kuznetsov #endif
7431bc3858SVitaly Kuznetsov 
7586dd995dSVitaly Kuznetsov static int __init setup_memhp_default_state(char *str)
7686dd995dSVitaly Kuznetsov {
775f47adf7SDavid Hildenbrand 	const int online_type = memhp_online_type_from_str(str);
785f47adf7SDavid Hildenbrand 
795f47adf7SDavid Hildenbrand 	if (online_type >= 0)
805f47adf7SDavid Hildenbrand 		memhp_default_online_type = online_type;
8186dd995dSVitaly Kuznetsov 
8286dd995dSVitaly Kuznetsov 	return 1;
8386dd995dSVitaly Kuznetsov }
8486dd995dSVitaly Kuznetsov __setup("memhp_default_state=", setup_memhp_default_state);
8586dd995dSVitaly Kuznetsov 
8630467e0bSDavid Rientjes void mem_hotplug_begin(void)
87bfc8c901SVladimir Davydov {
883f906ba2SThomas Gleixner 	cpus_read_lock();
893f906ba2SThomas Gleixner 	percpu_down_write(&mem_hotplug_lock);
90bfc8c901SVladimir Davydov }
91bfc8c901SVladimir Davydov 
9230467e0bSDavid Rientjes void mem_hotplug_done(void)
93bfc8c901SVladimir Davydov {
943f906ba2SThomas Gleixner 	percpu_up_write(&mem_hotplug_lock);
953f906ba2SThomas Gleixner 	cpus_read_unlock();
96bfc8c901SVladimir Davydov }
9720d6c96bSKOSAKI Motohiro 
98357b4da5SJuergen Gross u64 max_mem_size = U64_MAX;
99357b4da5SJuergen Gross 
10045e0b78bSKeith Mannthey /* add this memory to iomem resource */
1017b7b2721SDavid Hildenbrand static struct resource *register_memory_resource(u64 start, u64 size,
1027b7b2721SDavid Hildenbrand 						 const char *resource_name)
10345e0b78bSKeith Mannthey {
1042794129eSDave Hansen 	struct resource *res;
1052794129eSDave Hansen 	unsigned long flags =  IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
1067b7b2721SDavid Hildenbrand 
1077b7b2721SDavid Hildenbrand 	if (strcmp(resource_name, "System RAM"))
1087b7b2721SDavid Hildenbrand 		flags |= IORESOURCE_MEM_DRIVER_MANAGED;
109357b4da5SJuergen Gross 
110f3cd4c86SBaoquan He 	/*
111f3cd4c86SBaoquan He 	 * Make sure value parsed from 'mem=' only restricts memory adding
112f3cd4c86SBaoquan He 	 * while booting, so that memory hotplug won't be impacted. Please
113f3cd4c86SBaoquan He 	 * refer to document of 'mem=' in kernel-parameters.txt for more
114f3cd4c86SBaoquan He 	 * details.
115f3cd4c86SBaoquan He 	 */
116f3cd4c86SBaoquan He 	if (start + size > max_mem_size && system_state < SYSTEM_RUNNING)
117357b4da5SJuergen Gross 		return ERR_PTR(-E2BIG);
118357b4da5SJuergen Gross 
1192794129eSDave Hansen 	/*
1202794129eSDave Hansen 	 * Request ownership of the new memory range.  This might be
1212794129eSDave Hansen 	 * a child of an existing resource that was present but
1222794129eSDave Hansen 	 * not marked as busy.
1232794129eSDave Hansen 	 */
1242794129eSDave Hansen 	res = __request_region(&iomem_resource, start, size,
1252794129eSDave Hansen 			       resource_name, flags);
12645e0b78bSKeith Mannthey 
1272794129eSDave Hansen 	if (!res) {
1282794129eSDave Hansen 		pr_debug("Unable to reserve System RAM region: %016llx->%016llx\n",
1292794129eSDave Hansen 				start, start + size);
1306f754ba4SVitaly Kuznetsov 		return ERR_PTR(-EEXIST);
13145e0b78bSKeith Mannthey 	}
13245e0b78bSKeith Mannthey 	return res;
13345e0b78bSKeith Mannthey }
13445e0b78bSKeith Mannthey 
13545e0b78bSKeith Mannthey static void release_memory_resource(struct resource *res)
13645e0b78bSKeith Mannthey {
13745e0b78bSKeith Mannthey 	if (!res)
13845e0b78bSKeith Mannthey 		return;
13945e0b78bSKeith Mannthey 	release_resource(res);
14045e0b78bSKeith Mannthey 	kfree(res);
14145e0b78bSKeith Mannthey }
14245e0b78bSKeith Mannthey 
14353947027SKeith Mannthey #ifdef CONFIG_MEMORY_HOTPLUG_SPARSE
14446723bfaSYasuaki Ishimatsu void get_page_bootmem(unsigned long info,  struct page *page,
1455f24ce5fSAndrea Arcangeli 		      unsigned long type)
14604753278SYasunori Goto {
147ddffe98dSYasuaki Ishimatsu 	page->freelist = (void *)type;
14804753278SYasunori Goto 	SetPagePrivate(page);
14904753278SYasunori Goto 	set_page_private(page, info);
150fe896d18SJoonsoo Kim 	page_ref_inc(page);
15104753278SYasunori Goto }
15204753278SYasunori Goto 
153170a5a7eSJiang Liu void put_page_bootmem(struct page *page)
15404753278SYasunori Goto {
1555f24ce5fSAndrea Arcangeli 	unsigned long type;
15604753278SYasunori Goto 
157ddffe98dSYasuaki Ishimatsu 	type = (unsigned long) page->freelist;
1585f24ce5fSAndrea Arcangeli 	BUG_ON(type < MEMORY_HOTPLUG_MIN_BOOTMEM_TYPE ||
1595f24ce5fSAndrea Arcangeli 	       type > MEMORY_HOTPLUG_MAX_BOOTMEM_TYPE);
16004753278SYasunori Goto 
161fe896d18SJoonsoo Kim 	if (page_ref_dec_return(page) == 1) {
162ddffe98dSYasuaki Ishimatsu 		page->freelist = NULL;
16304753278SYasunori Goto 		ClearPagePrivate(page);
16404753278SYasunori Goto 		set_page_private(page, 0);
1655f24ce5fSAndrea Arcangeli 		INIT_LIST_HEAD(&page->lru);
166170a5a7eSJiang Liu 		free_reserved_page(page);
16704753278SYasunori Goto 	}
16804753278SYasunori Goto }
16904753278SYasunori Goto 
17046723bfaSYasuaki Ishimatsu #ifdef CONFIG_HAVE_BOOTMEM_INFO_NODE
17146723bfaSYasuaki Ishimatsu #ifndef CONFIG_SPARSEMEM_VMEMMAP
172d92bc318SAdrian Bunk static void register_page_bootmem_info_section(unsigned long start_pfn)
17304753278SYasunori Goto {
174f1eca35aSDan Williams 	unsigned long mapsize, section_nr, i;
17504753278SYasunori Goto 	struct mem_section *ms;
17604753278SYasunori Goto 	struct page *page, *memmap;
177f1eca35aSDan Williams 	struct mem_section_usage *usage;
17804753278SYasunori Goto 
17904753278SYasunori Goto 	section_nr = pfn_to_section_nr(start_pfn);
18004753278SYasunori Goto 	ms = __nr_to_section(section_nr);
18104753278SYasunori Goto 
18204753278SYasunori Goto 	/* Get section's memmap address */
18304753278SYasunori Goto 	memmap = sparse_decode_mem_map(ms->section_mem_map, section_nr);
18404753278SYasunori Goto 
18504753278SYasunori Goto 	/*
18604753278SYasunori Goto 	 * Get page for the memmap's phys address
18704753278SYasunori Goto 	 * XXX: need more consideration for sparse_vmemmap...
18804753278SYasunori Goto 	 */
18904753278SYasunori Goto 	page = virt_to_page(memmap);
19004753278SYasunori Goto 	mapsize = sizeof(struct page) * PAGES_PER_SECTION;
19104753278SYasunori Goto 	mapsize = PAGE_ALIGN(mapsize) >> PAGE_SHIFT;
19204753278SYasunori Goto 
19304753278SYasunori Goto 	/* remember memmap's page */
19404753278SYasunori Goto 	for (i = 0; i < mapsize; i++, page++)
19504753278SYasunori Goto 		get_page_bootmem(section_nr, page, SECTION_INFO);
19604753278SYasunori Goto 
197f1eca35aSDan Williams 	usage = ms->usage;
198f1eca35aSDan Williams 	page = virt_to_page(usage);
19904753278SYasunori Goto 
200f1eca35aSDan Williams 	mapsize = PAGE_ALIGN(mem_section_usage_size()) >> PAGE_SHIFT;
20104753278SYasunori Goto 
20204753278SYasunori Goto 	for (i = 0; i < mapsize; i++, page++)
203af370fb8SYasunori Goto 		get_page_bootmem(section_nr, page, MIX_SECTION_INFO);
20404753278SYasunori Goto 
20504753278SYasunori Goto }
20646723bfaSYasuaki Ishimatsu #else /* CONFIG_SPARSEMEM_VMEMMAP */
20746723bfaSYasuaki Ishimatsu static void register_page_bootmem_info_section(unsigned long start_pfn)
20846723bfaSYasuaki Ishimatsu {
209f1eca35aSDan Williams 	unsigned long mapsize, section_nr, i;
21046723bfaSYasuaki Ishimatsu 	struct mem_section *ms;
21146723bfaSYasuaki Ishimatsu 	struct page *page, *memmap;
212f1eca35aSDan Williams 	struct mem_section_usage *usage;
21346723bfaSYasuaki Ishimatsu 
21446723bfaSYasuaki Ishimatsu 	section_nr = pfn_to_section_nr(start_pfn);
21546723bfaSYasuaki Ishimatsu 	ms = __nr_to_section(section_nr);
21646723bfaSYasuaki Ishimatsu 
21746723bfaSYasuaki Ishimatsu 	memmap = sparse_decode_mem_map(ms->section_mem_map, section_nr);
21846723bfaSYasuaki Ishimatsu 
21946723bfaSYasuaki Ishimatsu 	register_page_bootmem_memmap(section_nr, memmap, PAGES_PER_SECTION);
22046723bfaSYasuaki Ishimatsu 
221f1eca35aSDan Williams 	usage = ms->usage;
222f1eca35aSDan Williams 	page = virt_to_page(usage);
22346723bfaSYasuaki Ishimatsu 
224f1eca35aSDan Williams 	mapsize = PAGE_ALIGN(mem_section_usage_size()) >> PAGE_SHIFT;
22546723bfaSYasuaki Ishimatsu 
22646723bfaSYasuaki Ishimatsu 	for (i = 0; i < mapsize; i++, page++)
22746723bfaSYasuaki Ishimatsu 		get_page_bootmem(section_nr, page, MIX_SECTION_INFO);
22846723bfaSYasuaki Ishimatsu }
22946723bfaSYasuaki Ishimatsu #endif /* !CONFIG_SPARSEMEM_VMEMMAP */
23004753278SYasunori Goto 
2317ded384aSLinus Torvalds void __init register_page_bootmem_info_node(struct pglist_data *pgdat)
23204753278SYasunori Goto {
23304753278SYasunori Goto 	unsigned long i, pfn, end_pfn, nr_pages;
23404753278SYasunori Goto 	int node = pgdat->node_id;
23504753278SYasunori Goto 	struct page *page;
23604753278SYasunori Goto 
23704753278SYasunori Goto 	nr_pages = PAGE_ALIGN(sizeof(struct pglist_data)) >> PAGE_SHIFT;
23804753278SYasunori Goto 	page = virt_to_page(pgdat);
23904753278SYasunori Goto 
24004753278SYasunori Goto 	for (i = 0; i < nr_pages; i++, page++)
24104753278SYasunori Goto 		get_page_bootmem(node, page, NODE_INFO);
24204753278SYasunori Goto 
24304753278SYasunori Goto 	pfn = pgdat->node_start_pfn;
244c1f19495SCody P Schafer 	end_pfn = pgdat_end_pfn(pgdat);
24504753278SYasunori Goto 
2467e9f5eb0STang Chen 	/* register section info */
247f14851afSqiuxishi 	for (; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
248f14851afSqiuxishi 		/*
249f14851afSqiuxishi 		 * Some platforms can assign the same pfn to multiple nodes - on
250f14851afSqiuxishi 		 * node0 as well as nodeN.  To avoid registering a pfn against
251f14851afSqiuxishi 		 * multiple nodes we check that this pfn does not already
2527e9f5eb0STang Chen 		 * reside in some other nodes.
253f14851afSqiuxishi 		 */
254f65e91dfSYang Shi 		if (pfn_valid(pfn) && (early_pfn_to_nid(pfn) == node))
25504753278SYasunori Goto 			register_page_bootmem_info_section(pfn);
256f14851afSqiuxishi 	}
25704753278SYasunori Goto }
25846723bfaSYasuaki Ishimatsu #endif /* CONFIG_HAVE_BOOTMEM_INFO_NODE */
25904753278SYasunori Goto 
2607ea62160SDan Williams static int check_pfn_span(unsigned long pfn, unsigned long nr_pages,
2617ea62160SDan Williams 		const char *reason)
2627ea62160SDan Williams {
2637ea62160SDan Williams 	/*
2647ea62160SDan Williams 	 * Disallow all operations smaller than a sub-section and only
2657ea62160SDan Williams 	 * allow operations smaller than a section for
2667ea62160SDan Williams 	 * SPARSEMEM_VMEMMAP. Note that check_hotplug_memory_range()
2677ea62160SDan Williams 	 * enforces a larger memory_block_size_bytes() granularity for
2687ea62160SDan Williams 	 * memory that will be marked online, so this check should only
2697ea62160SDan Williams 	 * fire for direct arch_{add,remove}_memory() users outside of
2707ea62160SDan Williams 	 * add_memory_resource().
2717ea62160SDan Williams 	 */
2727ea62160SDan Williams 	unsigned long min_align;
2737ea62160SDan Williams 
2747ea62160SDan Williams 	if (IS_ENABLED(CONFIG_SPARSEMEM_VMEMMAP))
2757ea62160SDan Williams 		min_align = PAGES_PER_SUBSECTION;
2767ea62160SDan Williams 	else
2777ea62160SDan Williams 		min_align = PAGES_PER_SECTION;
2787ea62160SDan Williams 	if (!IS_ALIGNED(pfn, min_align)
2797ea62160SDan Williams 			|| !IS_ALIGNED(nr_pages, min_align)) {
2807ea62160SDan Williams 		WARN(1, "Misaligned __%s_pages start: %#lx end: #%lx\n",
2817ea62160SDan Williams 				reason, pfn, pfn + nr_pages - 1);
2827ea62160SDan Williams 		return -EINVAL;
2837ea62160SDan Williams 	}
2847ea62160SDan Williams 	return 0;
2857ea62160SDan Williams }
2867ea62160SDan Williams 
287dca4436dSAlastair D'Silva static int check_hotplug_memory_addressable(unsigned long pfn,
288dca4436dSAlastair D'Silva 					    unsigned long nr_pages)
289dca4436dSAlastair D'Silva {
290dca4436dSAlastair D'Silva 	const u64 max_addr = PFN_PHYS(pfn + nr_pages) - 1;
291dca4436dSAlastair D'Silva 
292dca4436dSAlastair D'Silva 	if (max_addr >> MAX_PHYSMEM_BITS) {
293dca4436dSAlastair D'Silva 		const u64 max_allowed = (1ull << (MAX_PHYSMEM_BITS + 1)) - 1;
294dca4436dSAlastair D'Silva 		WARN(1,
295dca4436dSAlastair D'Silva 		     "Hotplugged memory exceeds maximum addressable address, range=%#llx-%#llx, maximum=%#llx\n",
296dca4436dSAlastair D'Silva 		     (u64)PFN_PHYS(pfn), max_addr, max_allowed);
297dca4436dSAlastair D'Silva 		return -E2BIG;
298dca4436dSAlastair D'Silva 	}
299dca4436dSAlastair D'Silva 
300dca4436dSAlastair D'Silva 	return 0;
301dca4436dSAlastair D'Silva }
302dca4436dSAlastair D'Silva 
3034edd7cefSDavid Rientjes /*
3044edd7cefSDavid Rientjes  * Reasonably generic function for adding memory.  It is
3054edd7cefSDavid Rientjes  * expected that archs that support memory hotplug will
3064edd7cefSDavid Rientjes  * call this function after deciding the zone to which to
3074edd7cefSDavid Rientjes  * add the new pages.
3084edd7cefSDavid Rientjes  */
3097ea62160SDan Williams int __ref __add_pages(int nid, unsigned long pfn, unsigned long nr_pages,
310f5637d3bSLogan Gunthorpe 		struct mhp_params *params)
3114edd7cefSDavid Rientjes {
3126cdd0b30SDavid Hildenbrand 	const unsigned long end_pfn = pfn + nr_pages;
3136cdd0b30SDavid Hildenbrand 	unsigned long cur_nr_pages;
3149a845030SDan Williams 	int err;
315f5637d3bSLogan Gunthorpe 	struct vmem_altmap *altmap = params->altmap;
3164b94ffdcSDan Williams 
317bfeb022fSLogan Gunthorpe 	if (WARN_ON_ONCE(!params->pgprot.pgprot))
318bfeb022fSLogan Gunthorpe 		return -EINVAL;
319bfeb022fSLogan Gunthorpe 
320dca4436dSAlastair D'Silva 	err = check_hotplug_memory_addressable(pfn, nr_pages);
321dca4436dSAlastair D'Silva 	if (err)
322dca4436dSAlastair D'Silva 		return err;
323dca4436dSAlastair D'Silva 
3244b94ffdcSDan Williams 	if (altmap) {
3254b94ffdcSDan Williams 		/*
3264b94ffdcSDan Williams 		 * Validate altmap is within bounds of the total request
3274b94ffdcSDan Williams 		 */
3287ea62160SDan Williams 		if (altmap->base_pfn != pfn
3294b94ffdcSDan Williams 				|| vmem_altmap_offset(altmap) > nr_pages) {
3304b94ffdcSDan Williams 			pr_warn_once("memory add fail, invalid altmap\n");
3317ea62160SDan Williams 			return -EINVAL;
3324b94ffdcSDan Williams 		}
3334b94ffdcSDan Williams 		altmap->alloc = 0;
3344b94ffdcSDan Williams 	}
3354b94ffdcSDan Williams 
3367ea62160SDan Williams 	err = check_pfn_span(pfn, nr_pages, "add");
3377ea62160SDan Williams 	if (err)
3387ea62160SDan Williams 		return err;
3397ea62160SDan Williams 
3406cdd0b30SDavid Hildenbrand 	for (; pfn < end_pfn; pfn += cur_nr_pages) {
3416cdd0b30SDavid Hildenbrand 		/* Select all remaining pages up to the next section boundary */
3426cdd0b30SDavid Hildenbrand 		cur_nr_pages = min(end_pfn - pfn,
3436cdd0b30SDavid Hildenbrand 				   SECTION_ALIGN_UP(pfn + 1) - pfn);
3446cdd0b30SDavid Hildenbrand 		err = sparse_add_section(nid, pfn, cur_nr_pages, altmap);
345ba72b4c8SDan Williams 		if (err)
346ba72b4c8SDan Williams 			break;
347f64ac5e6SMichal Hocko 		cond_resched();
3484edd7cefSDavid Rientjes 	}
349c435a390SZhu Guihua 	vmemmap_populate_print_last();
3504edd7cefSDavid Rientjes 	return err;
3514edd7cefSDavid Rientjes }
3524edd7cefSDavid Rientjes 
353d622ececSJia He #ifdef CONFIG_NUMA
354d622ececSJia He int __weak memory_add_physaddr_to_nid(u64 start)
355d622ececSJia He {
356a035b6bfSDan Williams 	pr_info_once("Unknown online node for memory at 0x%llx, assuming node 0\n",
357d622ececSJia He 			start);
358d622ececSJia He 	return 0;
359d622ececSJia He }
360d622ececSJia He EXPORT_SYMBOL_GPL(memory_add_physaddr_to_nid);
361a035b6bfSDan Williams 
362a035b6bfSDan Williams int __weak phys_to_target_node(u64 start)
363a035b6bfSDan Williams {
364a035b6bfSDan Williams 	pr_info_once("Unknown target node for memory at 0x%llx, assuming node 0\n",
365a035b6bfSDan Williams 			start);
366a035b6bfSDan Williams 	return 0;
367a035b6bfSDan Williams }
368a035b6bfSDan Williams EXPORT_SYMBOL_GPL(phys_to_target_node);
369d622ececSJia He #endif
370d622ececSJia He 
371815121d2SYasuaki Ishimatsu /* find the smallest valid pfn in the range [start_pfn, end_pfn) */
372d09b0137SYASUAKI ISHIMATSU static unsigned long find_smallest_section_pfn(int nid, struct zone *zone,
373815121d2SYasuaki Ishimatsu 				     unsigned long start_pfn,
374815121d2SYasuaki Ishimatsu 				     unsigned long end_pfn)
375815121d2SYasuaki Ishimatsu {
37649ba3c6bSDan Williams 	for (; start_pfn < end_pfn; start_pfn += PAGES_PER_SUBSECTION) {
3777ce700bfSDavid Hildenbrand 		if (unlikely(!pfn_to_online_page(start_pfn)))
378815121d2SYasuaki Ishimatsu 			continue;
379815121d2SYasuaki Ishimatsu 
380815121d2SYasuaki Ishimatsu 		if (unlikely(pfn_to_nid(start_pfn) != nid))
381815121d2SYasuaki Ishimatsu 			continue;
382815121d2SYasuaki Ishimatsu 
3839b05158fSDavid Hildenbrand 		if (zone != page_zone(pfn_to_page(start_pfn)))
384815121d2SYasuaki Ishimatsu 			continue;
385815121d2SYasuaki Ishimatsu 
386815121d2SYasuaki Ishimatsu 		return start_pfn;
387815121d2SYasuaki Ishimatsu 	}
388815121d2SYasuaki Ishimatsu 
389815121d2SYasuaki Ishimatsu 	return 0;
390815121d2SYasuaki Ishimatsu }
391815121d2SYasuaki Ishimatsu 
392815121d2SYasuaki Ishimatsu /* find the biggest valid pfn in the range [start_pfn, end_pfn). */
393d09b0137SYASUAKI ISHIMATSU static unsigned long find_biggest_section_pfn(int nid, struct zone *zone,
394815121d2SYasuaki Ishimatsu 				    unsigned long start_pfn,
395815121d2SYasuaki Ishimatsu 				    unsigned long end_pfn)
396815121d2SYasuaki Ishimatsu {
397815121d2SYasuaki Ishimatsu 	unsigned long pfn;
398815121d2SYasuaki Ishimatsu 
399815121d2SYasuaki Ishimatsu 	/* pfn is the end pfn of a memory section. */
400815121d2SYasuaki Ishimatsu 	pfn = end_pfn - 1;
40149ba3c6bSDan Williams 	for (; pfn >= start_pfn; pfn -= PAGES_PER_SUBSECTION) {
4027ce700bfSDavid Hildenbrand 		if (unlikely(!pfn_to_online_page(pfn)))
403815121d2SYasuaki Ishimatsu 			continue;
404815121d2SYasuaki Ishimatsu 
405815121d2SYasuaki Ishimatsu 		if (unlikely(pfn_to_nid(pfn) != nid))
406815121d2SYasuaki Ishimatsu 			continue;
407815121d2SYasuaki Ishimatsu 
4089b05158fSDavid Hildenbrand 		if (zone != page_zone(pfn_to_page(pfn)))
409815121d2SYasuaki Ishimatsu 			continue;
410815121d2SYasuaki Ishimatsu 
411815121d2SYasuaki Ishimatsu 		return pfn;
412815121d2SYasuaki Ishimatsu 	}
413815121d2SYasuaki Ishimatsu 
414815121d2SYasuaki Ishimatsu 	return 0;
415815121d2SYasuaki Ishimatsu }
416815121d2SYasuaki Ishimatsu 
417815121d2SYasuaki Ishimatsu static void shrink_zone_span(struct zone *zone, unsigned long start_pfn,
418815121d2SYasuaki Ishimatsu 			     unsigned long end_pfn)
419815121d2SYasuaki Ishimatsu {
420815121d2SYasuaki Ishimatsu 	unsigned long pfn;
421815121d2SYasuaki Ishimatsu 	int nid = zone_to_nid(zone);
422815121d2SYasuaki Ishimatsu 
423815121d2SYasuaki Ishimatsu 	zone_span_writelock(zone);
4245d12071cSDavid Hildenbrand 	if (zone->zone_start_pfn == start_pfn) {
425815121d2SYasuaki Ishimatsu 		/*
426815121d2SYasuaki Ishimatsu 		 * If the section is smallest section in the zone, it need
427815121d2SYasuaki Ishimatsu 		 * shrink zone->zone_start_pfn and zone->zone_spanned_pages.
428815121d2SYasuaki Ishimatsu 		 * In this case, we find second smallest valid mem_section
429815121d2SYasuaki Ishimatsu 		 * for shrinking zone.
430815121d2SYasuaki Ishimatsu 		 */
431815121d2SYasuaki Ishimatsu 		pfn = find_smallest_section_pfn(nid, zone, end_pfn,
4325d12071cSDavid Hildenbrand 						zone_end_pfn(zone));
433815121d2SYasuaki Ishimatsu 		if (pfn) {
4345d12071cSDavid Hildenbrand 			zone->spanned_pages = zone_end_pfn(zone) - pfn;
435815121d2SYasuaki Ishimatsu 			zone->zone_start_pfn = pfn;
436950b68d9SDavid Hildenbrand 		} else {
437950b68d9SDavid Hildenbrand 			zone->zone_start_pfn = 0;
438950b68d9SDavid Hildenbrand 			zone->spanned_pages = 0;
439815121d2SYasuaki Ishimatsu 		}
4405d12071cSDavid Hildenbrand 	} else if (zone_end_pfn(zone) == end_pfn) {
441815121d2SYasuaki Ishimatsu 		/*
442815121d2SYasuaki Ishimatsu 		 * If the section is biggest section in the zone, it need
443815121d2SYasuaki Ishimatsu 		 * shrink zone->spanned_pages.
444815121d2SYasuaki Ishimatsu 		 * In this case, we find second biggest valid mem_section for
445815121d2SYasuaki Ishimatsu 		 * shrinking zone.
446815121d2SYasuaki Ishimatsu 		 */
4475d12071cSDavid Hildenbrand 		pfn = find_biggest_section_pfn(nid, zone, zone->zone_start_pfn,
448815121d2SYasuaki Ishimatsu 					       start_pfn);
449815121d2SYasuaki Ishimatsu 		if (pfn)
4505d12071cSDavid Hildenbrand 			zone->spanned_pages = pfn - zone->zone_start_pfn + 1;
451950b68d9SDavid Hildenbrand 		else {
452815121d2SYasuaki Ishimatsu 			zone->zone_start_pfn = 0;
453815121d2SYasuaki Ishimatsu 			zone->spanned_pages = 0;
454950b68d9SDavid Hildenbrand 		}
455950b68d9SDavid Hildenbrand 	}
456815121d2SYasuaki Ishimatsu 	zone_span_writeunlock(zone);
457815121d2SYasuaki Ishimatsu }
458815121d2SYasuaki Ishimatsu 
45900d6c019SDavid Hildenbrand static void update_pgdat_span(struct pglist_data *pgdat)
460815121d2SYasuaki Ishimatsu {
46100d6c019SDavid Hildenbrand 	unsigned long node_start_pfn = 0, node_end_pfn = 0;
46200d6c019SDavid Hildenbrand 	struct zone *zone;
463815121d2SYasuaki Ishimatsu 
46400d6c019SDavid Hildenbrand 	for (zone = pgdat->node_zones;
46500d6c019SDavid Hildenbrand 	     zone < pgdat->node_zones + MAX_NR_ZONES; zone++) {
46600d6c019SDavid Hildenbrand 		unsigned long zone_end_pfn = zone->zone_start_pfn +
46700d6c019SDavid Hildenbrand 					     zone->spanned_pages;
46800d6c019SDavid Hildenbrand 
46900d6c019SDavid Hildenbrand 		/* No need to lock the zones, they can't change. */
470656d5711SDavid Hildenbrand 		if (!zone->spanned_pages)
471656d5711SDavid Hildenbrand 			continue;
472656d5711SDavid Hildenbrand 		if (!node_end_pfn) {
473656d5711SDavid Hildenbrand 			node_start_pfn = zone->zone_start_pfn;
474656d5711SDavid Hildenbrand 			node_end_pfn = zone_end_pfn;
475656d5711SDavid Hildenbrand 			continue;
476656d5711SDavid Hildenbrand 		}
477656d5711SDavid Hildenbrand 
47800d6c019SDavid Hildenbrand 		if (zone_end_pfn > node_end_pfn)
47900d6c019SDavid Hildenbrand 			node_end_pfn = zone_end_pfn;
48000d6c019SDavid Hildenbrand 		if (zone->zone_start_pfn < node_start_pfn)
48100d6c019SDavid Hildenbrand 			node_start_pfn = zone->zone_start_pfn;
482815121d2SYasuaki Ishimatsu 	}
483815121d2SYasuaki Ishimatsu 
48400d6c019SDavid Hildenbrand 	pgdat->node_start_pfn = node_start_pfn;
48500d6c019SDavid Hildenbrand 	pgdat->node_spanned_pages = node_end_pfn - node_start_pfn;
486815121d2SYasuaki Ishimatsu }
487815121d2SYasuaki Ishimatsu 
488feee6b29SDavid Hildenbrand void __ref remove_pfn_range_from_zone(struct zone *zone,
489feee6b29SDavid Hildenbrand 				      unsigned long start_pfn,
4907ea62160SDan Williams 				      unsigned long nr_pages)
491815121d2SYasuaki Ishimatsu {
492b7e3debdSBen Widawsky 	const unsigned long end_pfn = start_pfn + nr_pages;
493815121d2SYasuaki Ishimatsu 	struct pglist_data *pgdat = zone->zone_pgdat;
494b7e3debdSBen Widawsky 	unsigned long pfn, cur_nr_pages, flags;
495815121d2SYasuaki Ishimatsu 
496d33695b1SDavid Hildenbrand 	/* Poison struct pages because they are now uninitialized again. */
497b7e3debdSBen Widawsky 	for (pfn = start_pfn; pfn < end_pfn; pfn += cur_nr_pages) {
498b7e3debdSBen Widawsky 		cond_resched();
499b7e3debdSBen Widawsky 
500b7e3debdSBen Widawsky 		/* Select all remaining pages up to the next section boundary */
501b7e3debdSBen Widawsky 		cur_nr_pages =
502b7e3debdSBen Widawsky 			min(end_pfn - pfn, SECTION_ALIGN_UP(pfn + 1) - pfn);
503b7e3debdSBen Widawsky 		page_init_poison(pfn_to_page(pfn),
504b7e3debdSBen Widawsky 				 sizeof(struct page) * cur_nr_pages);
505b7e3debdSBen Widawsky 	}
506d33695b1SDavid Hildenbrand 
5077ce700bfSDavid Hildenbrand #ifdef CONFIG_ZONE_DEVICE
5087ce700bfSDavid Hildenbrand 	/*
5097ce700bfSDavid Hildenbrand 	 * Zone shrinking code cannot properly deal with ZONE_DEVICE. So
5107ce700bfSDavid Hildenbrand 	 * we will not try to shrink the zones - which is okay as
5117ce700bfSDavid Hildenbrand 	 * set_zone_contiguous() cannot deal with ZONE_DEVICE either way.
5127ce700bfSDavid Hildenbrand 	 */
5137ce700bfSDavid Hildenbrand 	if (zone_idx(zone) == ZONE_DEVICE)
5147ce700bfSDavid Hildenbrand 		return;
5157ce700bfSDavid Hildenbrand #endif
5167ce700bfSDavid Hildenbrand 
517feee6b29SDavid Hildenbrand 	clear_zone_contiguous(zone);
518feee6b29SDavid Hildenbrand 
519815121d2SYasuaki Ishimatsu 	pgdat_resize_lock(zone->zone_pgdat, &flags);
520815121d2SYasuaki Ishimatsu 	shrink_zone_span(zone, start_pfn, start_pfn + nr_pages);
52100d6c019SDavid Hildenbrand 	update_pgdat_span(pgdat);
522815121d2SYasuaki Ishimatsu 	pgdat_resize_unlock(zone->zone_pgdat, &flags);
523feee6b29SDavid Hildenbrand 
524feee6b29SDavid Hildenbrand 	set_zone_contiguous(zone);
525815121d2SYasuaki Ishimatsu }
526815121d2SYasuaki Ishimatsu 
527feee6b29SDavid Hildenbrand static void __remove_section(unsigned long pfn, unsigned long nr_pages,
528feee6b29SDavid Hildenbrand 			     unsigned long map_offset,
5299d1d887dSDavid Hildenbrand 			     struct vmem_altmap *altmap)
530ea01ea93SBadari Pulavarty {
53110404901Schenqiwu 	struct mem_section *ms = __pfn_to_section(pfn);
532ea01ea93SBadari Pulavarty 
5339d1d887dSDavid Hildenbrand 	if (WARN_ON_ONCE(!valid_section(ms)))
5349d1d887dSDavid Hildenbrand 		return;
535ea01ea93SBadari Pulavarty 
536ba72b4c8SDan Williams 	sparse_remove_section(ms, pfn, nr_pages, map_offset, altmap);
537ea01ea93SBadari Pulavarty }
538ea01ea93SBadari Pulavarty 
539ea01ea93SBadari Pulavarty /**
540feee6b29SDavid Hildenbrand  * __remove_pages() - remove sections of pages
5417ea62160SDan Williams  * @pfn: starting pageframe (must be aligned to start of a section)
542ea01ea93SBadari Pulavarty  * @nr_pages: number of pages to remove (must be multiple of section size)
543e8b098fcSMike Rapoport  * @altmap: alternative device page map or %NULL if default memmap is used
544ea01ea93SBadari Pulavarty  *
545ea01ea93SBadari Pulavarty  * Generic helper function to remove section mappings and sysfs entries
546ea01ea93SBadari Pulavarty  * for the section of the memory we are removing. Caller needs to make
547ea01ea93SBadari Pulavarty  * sure that pages are marked reserved and zones are adjust properly by
548ea01ea93SBadari Pulavarty  * calling offline_pages().
549ea01ea93SBadari Pulavarty  */
550feee6b29SDavid Hildenbrand void __remove_pages(unsigned long pfn, unsigned long nr_pages,
551feee6b29SDavid Hildenbrand 		    struct vmem_altmap *altmap)
552ea01ea93SBadari Pulavarty {
55352fb87c8SDavid Hildenbrand 	const unsigned long end_pfn = pfn + nr_pages;
55452fb87c8SDavid Hildenbrand 	unsigned long cur_nr_pages;
5554b94ffdcSDan Williams 	unsigned long map_offset = 0;
5564b94ffdcSDan Williams 
5574b94ffdcSDan Williams 	map_offset = vmem_altmap_offset(altmap);
558ea01ea93SBadari Pulavarty 
5597ea62160SDan Williams 	if (check_pfn_span(pfn, nr_pages, "remove"))
5607ea62160SDan Williams 		return;
561ea01ea93SBadari Pulavarty 
56252fb87c8SDavid Hildenbrand 	for (; pfn < end_pfn; pfn += cur_nr_pages) {
563dd33ad7bSMichal Hocko 		cond_resched();
56452fb87c8SDavid Hildenbrand 		/* Select all remaining pages up to the next section boundary */
565a11b9419SDavid Hildenbrand 		cur_nr_pages = min(end_pfn - pfn,
566a11b9419SDavid Hildenbrand 				   SECTION_ALIGN_UP(pfn + 1) - pfn);
56752fb87c8SDavid Hildenbrand 		__remove_section(pfn, cur_nr_pages, map_offset, altmap);
5684b94ffdcSDan Williams 		map_offset = 0;
569ea01ea93SBadari Pulavarty 	}
570ea01ea93SBadari Pulavarty }
571ea01ea93SBadari Pulavarty 
5729d0ad8caSDaniel Kiper int set_online_page_callback(online_page_callback_t callback)
5739d0ad8caSDaniel Kiper {
5749d0ad8caSDaniel Kiper 	int rc = -EINVAL;
5759d0ad8caSDaniel Kiper 
576bfc8c901SVladimir Davydov 	get_online_mems();
577bfc8c901SVladimir Davydov 	mutex_lock(&online_page_callback_lock);
5789d0ad8caSDaniel Kiper 
5799d0ad8caSDaniel Kiper 	if (online_page_callback == generic_online_page) {
5809d0ad8caSDaniel Kiper 		online_page_callback = callback;
5819d0ad8caSDaniel Kiper 		rc = 0;
5829d0ad8caSDaniel Kiper 	}
5839d0ad8caSDaniel Kiper 
584bfc8c901SVladimir Davydov 	mutex_unlock(&online_page_callback_lock);
585bfc8c901SVladimir Davydov 	put_online_mems();
5869d0ad8caSDaniel Kiper 
5879d0ad8caSDaniel Kiper 	return rc;
5889d0ad8caSDaniel Kiper }
5899d0ad8caSDaniel Kiper EXPORT_SYMBOL_GPL(set_online_page_callback);
5909d0ad8caSDaniel Kiper 
5919d0ad8caSDaniel Kiper int restore_online_page_callback(online_page_callback_t callback)
5929d0ad8caSDaniel Kiper {
5939d0ad8caSDaniel Kiper 	int rc = -EINVAL;
5949d0ad8caSDaniel Kiper 
595bfc8c901SVladimir Davydov 	get_online_mems();
596bfc8c901SVladimir Davydov 	mutex_lock(&online_page_callback_lock);
5979d0ad8caSDaniel Kiper 
5989d0ad8caSDaniel Kiper 	if (online_page_callback == callback) {
5999d0ad8caSDaniel Kiper 		online_page_callback = generic_online_page;
6009d0ad8caSDaniel Kiper 		rc = 0;
6019d0ad8caSDaniel Kiper 	}
6029d0ad8caSDaniel Kiper 
603bfc8c901SVladimir Davydov 	mutex_unlock(&online_page_callback_lock);
604bfc8c901SVladimir Davydov 	put_online_mems();
6059d0ad8caSDaniel Kiper 
6069d0ad8caSDaniel Kiper 	return rc;
6079d0ad8caSDaniel Kiper }
6089d0ad8caSDaniel Kiper EXPORT_SYMBOL_GPL(restore_online_page_callback);
6099d0ad8caSDaniel Kiper 
61018db1491SDavid Hildenbrand void generic_online_page(struct page *page, unsigned int order)
6119d0ad8caSDaniel Kiper {
612c87cbc1fSVlastimil Babka 	/*
613c87cbc1fSVlastimil Babka 	 * Freeing the page with debug_pagealloc enabled will try to unmap it,
614c87cbc1fSVlastimil Babka 	 * so we should map it first. This is better than introducing a special
615c87cbc1fSVlastimil Babka 	 * case in page freeing fast path.
616c87cbc1fSVlastimil Babka 	 */
617c87cbc1fSVlastimil Babka 	if (debug_pagealloc_enabled_static())
618cd02cf1aSQian Cai 		kernel_map_pages(page, 1 << order, 1);
619a9cd410aSArun KS 	__free_pages_core(page, order);
620a9cd410aSArun KS 	totalram_pages_add(1UL << order);
621a9cd410aSArun KS #ifdef CONFIG_HIGHMEM
622a9cd410aSArun KS 	if (PageHighMem(page))
623a9cd410aSArun KS 		totalhigh_pages_add(1UL << order);
624a9cd410aSArun KS #endif
625a9cd410aSArun KS }
62618db1491SDavid Hildenbrand EXPORT_SYMBOL_GPL(generic_online_page);
627a9cd410aSArun KS 
62875884fb1SKAMEZAWA Hiroyuki static int online_pages_range(unsigned long start_pfn, unsigned long nr_pages,
62975884fb1SKAMEZAWA Hiroyuki 			void *arg)
6303947be19SDave Hansen {
631b2c2ab20SDavid Hildenbrand 	const unsigned long end_pfn = start_pfn + nr_pages;
632b2c2ab20SDavid Hildenbrand 	unsigned long pfn;
633b2c2ab20SDavid Hildenbrand 	int order;
6342d070eabSMichal Hocko 
635b2c2ab20SDavid Hildenbrand 	/*
636b2c2ab20SDavid Hildenbrand 	 * Online the pages. The callback might decide to keep some pages
637b2c2ab20SDavid Hildenbrand 	 * PG_reserved (to add them to the buddy later), but we still account
638b2c2ab20SDavid Hildenbrand 	 * them as being online/belonging to this zone ("present").
639b2c2ab20SDavid Hildenbrand 	 */
640b2c2ab20SDavid Hildenbrand 	for (pfn = start_pfn; pfn < end_pfn; pfn += 1ul << order) {
641b2c2ab20SDavid Hildenbrand 		order = min(MAX_ORDER - 1, get_order(PFN_PHYS(end_pfn - pfn)));
642bd02cc01SDavid Hildenbrand 		/* __free_pages_core() wants pfns to be aligned to the order */
643bd02cc01SDavid Hildenbrand 		if (WARN_ON_ONCE(!IS_ALIGNED(pfn, 1ul << order)))
644bd02cc01SDavid Hildenbrand 			order = 0;
645b2c2ab20SDavid Hildenbrand 		(*online_page_callback)(pfn_to_page(pfn), order);
646b2c2ab20SDavid Hildenbrand 	}
6472d070eabSMichal Hocko 
648b2c2ab20SDavid Hildenbrand 	/* mark all involved sections as online */
649b2c2ab20SDavid Hildenbrand 	online_mem_sections(start_pfn, end_pfn);
650b2c2ab20SDavid Hildenbrand 
651b2c2ab20SDavid Hildenbrand 	*(unsigned long *)arg += nr_pages;
65275884fb1SKAMEZAWA Hiroyuki 	return 0;
65375884fb1SKAMEZAWA Hiroyuki }
65475884fb1SKAMEZAWA Hiroyuki 
655d9713679SLai Jiangshan /* check which state of node_states will be changed when online memory */
656d9713679SLai Jiangshan static void node_states_check_changes_online(unsigned long nr_pages,
657d9713679SLai Jiangshan 	struct zone *zone, struct memory_notify *arg)
658d9713679SLai Jiangshan {
659d9713679SLai Jiangshan 	int nid = zone_to_nid(zone);
660d9713679SLai Jiangshan 
66198fa15f3SAnshuman Khandual 	arg->status_change_nid = NUMA_NO_NODE;
66298fa15f3SAnshuman Khandual 	arg->status_change_nid_normal = NUMA_NO_NODE;
66398fa15f3SAnshuman Khandual 	arg->status_change_nid_high = NUMA_NO_NODE;
6646715ddf9SLai Jiangshan 
6656715ddf9SLai Jiangshan 	if (!node_state(nid, N_MEMORY))
666d9713679SLai Jiangshan 		arg->status_change_nid = nid;
6678efe33f4SOscar Salvador 	if (zone_idx(zone) <= ZONE_NORMAL && !node_state(nid, N_NORMAL_MEMORY))
6688efe33f4SOscar Salvador 		arg->status_change_nid_normal = nid;
6698efe33f4SOscar Salvador #ifdef CONFIG_HIGHMEM
670d3ba3ae1SBaoquan He 	if (zone_idx(zone) <= ZONE_HIGHMEM && !node_state(nid, N_HIGH_MEMORY))
6718efe33f4SOscar Salvador 		arg->status_change_nid_high = nid;
6728efe33f4SOscar Salvador #endif
673d9713679SLai Jiangshan }
674d9713679SLai Jiangshan 
675d9713679SLai Jiangshan static void node_states_set_node(int node, struct memory_notify *arg)
676d9713679SLai Jiangshan {
677d9713679SLai Jiangshan 	if (arg->status_change_nid_normal >= 0)
678d9713679SLai Jiangshan 		node_set_state(node, N_NORMAL_MEMORY);
679d9713679SLai Jiangshan 
6806715ddf9SLai Jiangshan 	if (arg->status_change_nid_high >= 0)
681d9713679SLai Jiangshan 		node_set_state(node, N_HIGH_MEMORY);
6826715ddf9SLai Jiangshan 
68383d83612SOscar Salvador 	if (arg->status_change_nid >= 0)
6846715ddf9SLai Jiangshan 		node_set_state(node, N_MEMORY);
685d9713679SLai Jiangshan }
686d9713679SLai Jiangshan 
687f1dd2cd1SMichal Hocko static void __meminit resize_zone_range(struct zone *zone, unsigned long start_pfn,
688f1dd2cd1SMichal Hocko 		unsigned long nr_pages)
689f1dd2cd1SMichal Hocko {
690f1dd2cd1SMichal Hocko 	unsigned long old_end_pfn = zone_end_pfn(zone);
691f1dd2cd1SMichal Hocko 
692f1dd2cd1SMichal Hocko 	if (zone_is_empty(zone) || start_pfn < zone->zone_start_pfn)
693f1dd2cd1SMichal Hocko 		zone->zone_start_pfn = start_pfn;
694f1dd2cd1SMichal Hocko 
695f1dd2cd1SMichal Hocko 	zone->spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - zone->zone_start_pfn;
696f1dd2cd1SMichal Hocko }
697f1dd2cd1SMichal Hocko 
698f1dd2cd1SMichal Hocko static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned long start_pfn,
699f1dd2cd1SMichal Hocko                                      unsigned long nr_pages)
700f1dd2cd1SMichal Hocko {
701f1dd2cd1SMichal Hocko 	unsigned long old_end_pfn = pgdat_end_pfn(pgdat);
702f1dd2cd1SMichal Hocko 
703f1dd2cd1SMichal Hocko 	if (!pgdat->node_spanned_pages || start_pfn < pgdat->node_start_pfn)
704f1dd2cd1SMichal Hocko 		pgdat->node_start_pfn = start_pfn;
705f1dd2cd1SMichal Hocko 
706f1dd2cd1SMichal Hocko 	pgdat->node_spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - pgdat->node_start_pfn;
707f1dd2cd1SMichal Hocko 
7083fccb74cSDavid Hildenbrand }
7093fccb74cSDavid Hildenbrand /*
7103fccb74cSDavid Hildenbrand  * Associate the pfn range with the given zone, initializing the memmaps
7113fccb74cSDavid Hildenbrand  * and resizing the pgdat/zone data to span the added pages. After this
7123fccb74cSDavid Hildenbrand  * call, all affected pages are PG_reserved.
7133fccb74cSDavid Hildenbrand  */
714a99583e7SChristoph Hellwig void __ref move_pfn_range_to_zone(struct zone *zone, unsigned long start_pfn,
715a99583e7SChristoph Hellwig 		unsigned long nr_pages, struct vmem_altmap *altmap)
716f1dd2cd1SMichal Hocko {
717f1dd2cd1SMichal Hocko 	struct pglist_data *pgdat = zone->zone_pgdat;
718f1dd2cd1SMichal Hocko 	int nid = pgdat->node_id;
719f1dd2cd1SMichal Hocko 	unsigned long flags;
720f1dd2cd1SMichal Hocko 
721f1dd2cd1SMichal Hocko 	clear_zone_contiguous(zone);
722f1dd2cd1SMichal Hocko 
723f1dd2cd1SMichal Hocko 	/* TODO Huh pgdat is irqsave while zone is not. It used to be like that before */
724f1dd2cd1SMichal Hocko 	pgdat_resize_lock(pgdat, &flags);
725f1dd2cd1SMichal Hocko 	zone_span_writelock(zone);
726fa004ab7SWei Yang 	if (zone_is_empty(zone))
727fa004ab7SWei Yang 		init_currently_empty_zone(zone, start_pfn, nr_pages);
728f1dd2cd1SMichal Hocko 	resize_zone_range(zone, start_pfn, nr_pages);
729f1dd2cd1SMichal Hocko 	zone_span_writeunlock(zone);
730f1dd2cd1SMichal Hocko 	resize_pgdat_range(pgdat, start_pfn, nr_pages);
731f1dd2cd1SMichal Hocko 	pgdat_resize_unlock(pgdat, &flags);
732f1dd2cd1SMichal Hocko 
733f1dd2cd1SMichal Hocko 	/*
734f1dd2cd1SMichal Hocko 	 * TODO now we have a visible range of pages which are not associated
735f1dd2cd1SMichal Hocko 	 * with their zone properly. Not nice but set_pfnblock_flags_mask
736f1dd2cd1SMichal Hocko 	 * expects the zone spans the pfn range. All the pages in the range
737f1dd2cd1SMichal Hocko 	 * are reserved so nobody should be touching them so we should be safe
738f1dd2cd1SMichal Hocko 	 */
739a99583e7SChristoph Hellwig 	memmap_init_zone(nr_pages, nid, zone_idx(zone), start_pfn,
740c1d0da83SLaurent Dufour 			 MEMINIT_HOTPLUG, altmap);
741f1dd2cd1SMichal Hocko 
742f1dd2cd1SMichal Hocko 	set_zone_contiguous(zone);
743f1dd2cd1SMichal Hocko }
744f1dd2cd1SMichal Hocko 
745f1dd2cd1SMichal Hocko /*
746c246a213SMichal Hocko  * Returns a default kernel memory zone for the given pfn range.
747c246a213SMichal Hocko  * If no kernel zone covers this pfn range it will automatically go
748c246a213SMichal Hocko  * to the ZONE_NORMAL.
749c246a213SMichal Hocko  */
750c6f03e29SMichal Hocko static struct zone *default_kernel_zone_for_pfn(int nid, unsigned long start_pfn,
751c246a213SMichal Hocko 		unsigned long nr_pages)
752c246a213SMichal Hocko {
753c246a213SMichal Hocko 	struct pglist_data *pgdat = NODE_DATA(nid);
754c246a213SMichal Hocko 	int zid;
755c246a213SMichal Hocko 
756c246a213SMichal Hocko 	for (zid = 0; zid <= ZONE_NORMAL; zid++) {
757c246a213SMichal Hocko 		struct zone *zone = &pgdat->node_zones[zid];
758c246a213SMichal Hocko 
759c246a213SMichal Hocko 		if (zone_intersects(zone, start_pfn, nr_pages))
760c246a213SMichal Hocko 			return zone;
761c246a213SMichal Hocko 	}
762c246a213SMichal Hocko 
763c246a213SMichal Hocko 	return &pgdat->node_zones[ZONE_NORMAL];
764c246a213SMichal Hocko }
765c246a213SMichal Hocko 
766c6f03e29SMichal Hocko static inline struct zone *default_zone_for_pfn(int nid, unsigned long start_pfn,
767c6f03e29SMichal Hocko 		unsigned long nr_pages)
768e5e68930SMichal Hocko {
769c6f03e29SMichal Hocko 	struct zone *kernel_zone = default_kernel_zone_for_pfn(nid, start_pfn,
770c6f03e29SMichal Hocko 			nr_pages);
771c6f03e29SMichal Hocko 	struct zone *movable_zone = &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
772c6f03e29SMichal Hocko 	bool in_kernel = zone_intersects(kernel_zone, start_pfn, nr_pages);
773c6f03e29SMichal Hocko 	bool in_movable = zone_intersects(movable_zone, start_pfn, nr_pages);
774e5e68930SMichal Hocko 
775e5e68930SMichal Hocko 	/*
776c6f03e29SMichal Hocko 	 * We inherit the existing zone in a simple case where zones do not
777c6f03e29SMichal Hocko 	 * overlap in the given range
778e5e68930SMichal Hocko 	 */
779c6f03e29SMichal Hocko 	if (in_kernel ^ in_movable)
780c6f03e29SMichal Hocko 		return (in_kernel) ? kernel_zone : movable_zone;
781e5e68930SMichal Hocko 
782c6f03e29SMichal Hocko 	/*
783c6f03e29SMichal Hocko 	 * If the range doesn't belong to any zone or two zones overlap in the
784c6f03e29SMichal Hocko 	 * given range then we use movable zone only if movable_node is
785c6f03e29SMichal Hocko 	 * enabled because we always online to a kernel zone by default.
786c6f03e29SMichal Hocko 	 */
787c6f03e29SMichal Hocko 	return movable_node_enabled ? movable_zone : kernel_zone;
7889f123ab5SMichal Hocko }
7899f123ab5SMichal Hocko 
790e5e68930SMichal Hocko struct zone * zone_for_pfn_range(int online_type, int nid, unsigned start_pfn,
791e5e68930SMichal Hocko 		unsigned long nr_pages)
792f1dd2cd1SMichal Hocko {
793c6f03e29SMichal Hocko 	if (online_type == MMOP_ONLINE_KERNEL)
794c6f03e29SMichal Hocko 		return default_kernel_zone_for_pfn(nid, start_pfn, nr_pages);
795f1dd2cd1SMichal Hocko 
796c6f03e29SMichal Hocko 	if (online_type == MMOP_ONLINE_MOVABLE)
797c6f03e29SMichal Hocko 		return &NODE_DATA(nid)->node_zones[ZONE_MOVABLE];
798f1dd2cd1SMichal Hocko 
799c6f03e29SMichal Hocko 	return default_zone_for_pfn(nid, start_pfn, nr_pages);
800e5e68930SMichal Hocko }
801e5e68930SMichal Hocko 
802bd5c2344SDavid Hildenbrand int __ref online_pages(unsigned long pfn, unsigned long nr_pages,
803bd5c2344SDavid Hildenbrand 		       int online_type, int nid)
80475884fb1SKAMEZAWA Hiroyuki {
805aa47228aSCody P Schafer 	unsigned long flags;
8063947be19SDave Hansen 	unsigned long onlined_pages = 0;
8073947be19SDave Hansen 	struct zone *zone;
8086811378eSYasunori Goto 	int need_zonelists_rebuild = 0;
8097b78d335SYasunori Goto 	int ret;
8107b78d335SYasunori Goto 	struct memory_notify arg;
8113947be19SDave Hansen 
812381eab4aSDavid Hildenbrand 	mem_hotplug_begin();
813381eab4aSDavid Hildenbrand 
814f1dd2cd1SMichal Hocko 	/* associate pfn range with the zone */
8153fccb74cSDavid Hildenbrand 	zone = zone_for_pfn_range(online_type, nid, pfn, nr_pages);
8163fccb74cSDavid Hildenbrand 	move_pfn_range_to_zone(zone, pfn, nr_pages, NULL);
817511c2abaSLai Jiangshan 
8187b78d335SYasunori Goto 	arg.start_pfn = pfn;
8197b78d335SYasunori Goto 	arg.nr_pages = nr_pages;
820d9713679SLai Jiangshan 	node_states_check_changes_online(nr_pages, zone, &arg);
8217b78d335SYasunori Goto 
8227b78d335SYasunori Goto 	ret = memory_notify(MEM_GOING_ONLINE, &arg);
8237b78d335SYasunori Goto 	ret = notifier_to_errno(ret);
824e33e33b4SChen Yucong 	if (ret)
825e33e33b4SChen Yucong 		goto failed_addition;
826e33e33b4SChen Yucong 
8273947be19SDave Hansen 	/*
8286811378eSYasunori Goto 	 * If this zone is not populated, then it is not in zonelist.
8296811378eSYasunori Goto 	 * This means the page allocator ignores this zone.
8306811378eSYasunori Goto 	 * So, zonelist must be updated after online.
8316811378eSYasunori Goto 	 */
8326dcd73d7SWen Congyang 	if (!populated_zone(zone)) {
8336811378eSYasunori Goto 		need_zonelists_rebuild = 1;
83472675e13SMichal Hocko 		setup_zone_pageset(zone);
8356dcd73d7SWen Congyang 	}
8366811378eSYasunori Goto 
837908eedc6SKAMEZAWA Hiroyuki 	ret = walk_system_ram_range(pfn, nr_pages, &onlined_pages,
83875884fb1SKAMEZAWA Hiroyuki 		online_pages_range);
839fd8a4221SGeoff Levand 	if (ret) {
840ca9a46f8SDavid Hildenbrand 		/* not a single memory resource was applicable */
8416dcd73d7SWen Congyang 		if (need_zonelists_rebuild)
8426dcd73d7SWen Congyang 			zone_pcp_reset(zone);
843e33e33b4SChen Yucong 		goto failed_addition;
844fd8a4221SGeoff Levand 	}
845fd8a4221SGeoff Levand 
8463947be19SDave Hansen 	zone->present_pages += onlined_pages;
847aa47228aSCody P Schafer 
848aa47228aSCody P Schafer 	pgdat_resize_lock(zone->zone_pgdat, &flags);
849f2937be5SYasunori Goto 	zone->zone_pgdat->node_present_pages += onlined_pages;
850aa47228aSCody P Schafer 	pgdat_resize_unlock(zone->zone_pgdat, &flags);
851aa47228aSCody P Schafer 
85293146d98SDavid Hildenbrand 	/*
85393146d98SDavid Hildenbrand 	 * When exposing larger, physically contiguous memory areas to the
85493146d98SDavid Hildenbrand 	 * buddy, shuffling in the buddy (when freeing onlined pages, putting
85593146d98SDavid Hildenbrand 	 * them either to the head or the tail of the freelist) is only helpful
85693146d98SDavid Hildenbrand 	 * for maintaining the shuffle, but not for creating the initial
85793146d98SDavid Hildenbrand 	 * shuffle. Shuffle the whole zone to make sure the just onlined pages
85893146d98SDavid Hildenbrand 	 * are properly distributed across the whole freelist.
85993146d98SDavid Hildenbrand 	 */
860e900a918SDan Williams 	shuffle_zone(zone);
861e900a918SDan Williams 
862e888ca35SVlastimil Babka 	node_states_set_node(nid, &arg);
8631f522509SHaicheng Li 	if (need_zonelists_rebuild)
86472675e13SMichal Hocko 		build_all_zonelists(NULL);
865112067f0SShaohua Li 	zone_pcp_update(zone);
8661f522509SHaicheng Li 
8671b79acc9SKOSAKI Motohiro 	init_per_zone_wmark_min();
8681b79acc9SKOSAKI Motohiro 
869e888ca35SVlastimil Babka 	kswapd_run(nid);
870698b1b30SVlastimil Babka 	kcompactd_run(nid);
87161b13993SDave Hansen 
8722d1d43f6SChandra Seetharaman 	writeback_set_ratelimit();
8737b78d335SYasunori Goto 
8747b78d335SYasunori Goto 	memory_notify(MEM_ONLINE, &arg);
875381eab4aSDavid Hildenbrand 	mem_hotplug_done();
87630467e0bSDavid Rientjes 	return 0;
877e33e33b4SChen Yucong 
878e33e33b4SChen Yucong failed_addition:
879e33e33b4SChen Yucong 	pr_debug("online_pages [mem %#010llx-%#010llx] failed\n",
880e33e33b4SChen Yucong 		 (unsigned long long) pfn << PAGE_SHIFT,
881e33e33b4SChen Yucong 		 (((unsigned long long) pfn + nr_pages) << PAGE_SHIFT) - 1);
882e33e33b4SChen Yucong 	memory_notify(MEM_CANCEL_ONLINE, &arg);
883feee6b29SDavid Hildenbrand 	remove_pfn_range_from_zone(zone, pfn, nr_pages);
884381eab4aSDavid Hildenbrand 	mem_hotplug_done();
885e33e33b4SChen Yucong 	return ret;
8863947be19SDave Hansen }
88753947027SKeith Mannthey #endif /* CONFIG_MEMORY_HOTPLUG_SPARSE */
888bc02af93SYasunori Goto 
8890bd85420STang Chen static void reset_node_present_pages(pg_data_t *pgdat)
8900bd85420STang Chen {
8910bd85420STang Chen 	struct zone *z;
8920bd85420STang Chen 
8930bd85420STang Chen 	for (z = pgdat->node_zones; z < pgdat->node_zones + MAX_NR_ZONES; z++)
8940bd85420STang Chen 		z->present_pages = 0;
8950bd85420STang Chen 
8960bd85420STang Chen 	pgdat->node_present_pages = 0;
8970bd85420STang Chen }
8980bd85420STang Chen 
899e1319331SHidetoshi Seto /* we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG */
900c68ab18cSDavid Hildenbrand static pg_data_t __ref *hotadd_new_pgdat(int nid)
9019af3c2deSYasunori Goto {
9029af3c2deSYasunori Goto 	struct pglist_data *pgdat;
9039af3c2deSYasunori Goto 
904a1e565aaSTang Chen 	pgdat = NODE_DATA(nid);
905a1e565aaSTang Chen 	if (!pgdat) {
9069af3c2deSYasunori Goto 		pgdat = arch_alloc_nodedata(nid);
9079af3c2deSYasunori Goto 		if (!pgdat)
9089af3c2deSYasunori Goto 			return NULL;
9099af3c2deSYasunori Goto 
91033fce011SWei Yang 		pgdat->per_cpu_nodestats =
91133fce011SWei Yang 			alloc_percpu(struct per_cpu_nodestat);
9129af3c2deSYasunori Goto 		arch_refresh_nodedata(nid, pgdat);
913b0dc3a34SGu Zheng 	} else {
91433fce011SWei Yang 		int cpu;
915e716f2ebSMel Gorman 		/*
91697a225e6SJoonsoo Kim 		 * Reset the nr_zones, order and highest_zoneidx before reuse.
91797a225e6SJoonsoo Kim 		 * Note that kswapd will init kswapd_highest_zoneidx properly
918e716f2ebSMel Gorman 		 * when it starts in the near future.
919e716f2ebSMel Gorman 		 */
920b0dc3a34SGu Zheng 		pgdat->nr_zones = 0;
92138087d9bSMel Gorman 		pgdat->kswapd_order = 0;
92297a225e6SJoonsoo Kim 		pgdat->kswapd_highest_zoneidx = 0;
92333fce011SWei Yang 		for_each_online_cpu(cpu) {
92433fce011SWei Yang 			struct per_cpu_nodestat *p;
92533fce011SWei Yang 
92633fce011SWei Yang 			p = per_cpu_ptr(pgdat->per_cpu_nodestats, cpu);
92733fce011SWei Yang 			memset(p, 0, sizeof(*p));
92833fce011SWei Yang 		}
929a1e565aaSTang Chen 	}
9309af3c2deSYasunori Goto 
9319af3c2deSYasunori Goto 	/* we can use NODE_DATA(nid) from here */
93203e85f9dSOscar Salvador 	pgdat->node_id = nid;
933c68ab18cSDavid Hildenbrand 	pgdat->node_start_pfn = 0;
93403e85f9dSOscar Salvador 
9359af3c2deSYasunori Goto 	/* init node's zones as empty zones, we don't have any present pages.*/
93603e85f9dSOscar Salvador 	free_area_init_core_hotplug(nid);
9379af3c2deSYasunori Goto 
938959ecc48SKAMEZAWA Hiroyuki 	/*
939959ecc48SKAMEZAWA Hiroyuki 	 * The node we allocated has no zone fallback lists. For avoiding
940959ecc48SKAMEZAWA Hiroyuki 	 * to access not-initialized zonelist, build here.
941959ecc48SKAMEZAWA Hiroyuki 	 */
94272675e13SMichal Hocko 	build_all_zonelists(pgdat);
943959ecc48SKAMEZAWA Hiroyuki 
944f784a3f1STang Chen 	/*
9450bd85420STang Chen 	 * When memory is hot-added, all the memory is in offline state. So
9460bd85420STang Chen 	 * clear all zones' present_pages because they will be updated in
9470bd85420STang Chen 	 * online_pages() and offline_pages().
9480bd85420STang Chen 	 */
94903e85f9dSOscar Salvador 	reset_node_managed_pages(pgdat);
9500bd85420STang Chen 	reset_node_present_pages(pgdat);
9510bd85420STang Chen 
9529af3c2deSYasunori Goto 	return pgdat;
9539af3c2deSYasunori Goto }
9549af3c2deSYasunori Goto 
955b9ff0360SOscar Salvador static void rollback_node_hotadd(int nid)
9569af3c2deSYasunori Goto {
957b9ff0360SOscar Salvador 	pg_data_t *pgdat = NODE_DATA(nid);
958b9ff0360SOscar Salvador 
9599af3c2deSYasunori Goto 	arch_refresh_nodedata(nid, NULL);
9605830169fSReza Arbab 	free_percpu(pgdat->per_cpu_nodestats);
9619af3c2deSYasunori Goto 	arch_free_nodedata(pgdat);
9629af3c2deSYasunori Goto }
9639af3c2deSYasunori Goto 
9640a547039SKAMEZAWA Hiroyuki 
96501b0f197SToshi Kani /**
96601b0f197SToshi Kani  * try_online_node - online a node if offlined
967e8b098fcSMike Rapoport  * @nid: the node ID
968b9ff0360SOscar Salvador  * @set_node_online: Whether we want to online the node
969cf23422bSminskey guo  * called by cpu_up() to online a node without onlined memory.
970b9ff0360SOscar Salvador  *
971b9ff0360SOscar Salvador  * Returns:
972b9ff0360SOscar Salvador  * 1 -> a new node has been allocated
973b9ff0360SOscar Salvador  * 0 -> the node is already online
974b9ff0360SOscar Salvador  * -ENOMEM -> the node could not be allocated
975cf23422bSminskey guo  */
976c68ab18cSDavid Hildenbrand static int __try_online_node(int nid, bool set_node_online)
977cf23422bSminskey guo {
978cf23422bSminskey guo 	pg_data_t *pgdat;
979b9ff0360SOscar Salvador 	int ret = 1;
980cf23422bSminskey guo 
98101b0f197SToshi Kani 	if (node_online(nid))
98201b0f197SToshi Kani 		return 0;
98301b0f197SToshi Kani 
984c68ab18cSDavid Hildenbrand 	pgdat = hotadd_new_pgdat(nid);
9857553e8f2SDavid Rientjes 	if (!pgdat) {
98601b0f197SToshi Kani 		pr_err("Cannot online node %d due to NULL pgdat\n", nid);
987cf23422bSminskey guo 		ret = -ENOMEM;
988cf23422bSminskey guo 		goto out;
989cf23422bSminskey guo 	}
990b9ff0360SOscar Salvador 
991b9ff0360SOscar Salvador 	if (set_node_online) {
992cf23422bSminskey guo 		node_set_online(nid);
993cf23422bSminskey guo 		ret = register_one_node(nid);
994cf23422bSminskey guo 		BUG_ON(ret);
995b9ff0360SOscar Salvador 	}
996cf23422bSminskey guo out:
997b9ff0360SOscar Salvador 	return ret;
998b9ff0360SOscar Salvador }
999b9ff0360SOscar Salvador 
1000b9ff0360SOscar Salvador /*
1001b9ff0360SOscar Salvador  * Users of this function always want to online/register the node
1002b9ff0360SOscar Salvador  */
1003b9ff0360SOscar Salvador int try_online_node(int nid)
1004b9ff0360SOscar Salvador {
1005b9ff0360SOscar Salvador 	int ret;
1006b9ff0360SOscar Salvador 
1007b9ff0360SOscar Salvador 	mem_hotplug_begin();
1008c68ab18cSDavid Hildenbrand 	ret =  __try_online_node(nid, true);
1009bfc8c901SVladimir Davydov 	mem_hotplug_done();
1010cf23422bSminskey guo 	return ret;
1011cf23422bSminskey guo }
1012cf23422bSminskey guo 
101327356f54SToshi Kani static int check_hotplug_memory_range(u64 start, u64 size)
101427356f54SToshi Kani {
1015ba325585SPavel Tatashin 	/* memory range must be block size aligned */
1016cec3ebd0SDavid Hildenbrand 	if (!size || !IS_ALIGNED(start, memory_block_size_bytes()) ||
1017cec3ebd0SDavid Hildenbrand 	    !IS_ALIGNED(size, memory_block_size_bytes())) {
1018ba325585SPavel Tatashin 		pr_err("Block size [%#lx] unaligned hotplug range: start %#llx, size %#llx",
1019cec3ebd0SDavid Hildenbrand 		       memory_block_size_bytes(), start, size);
102027356f54SToshi Kani 		return -EINVAL;
102127356f54SToshi Kani 	}
102227356f54SToshi Kani 
102327356f54SToshi Kani 	return 0;
102427356f54SToshi Kani }
102527356f54SToshi Kani 
102631bc3858SVitaly Kuznetsov static int online_memory_block(struct memory_block *mem, void *arg)
102731bc3858SVitaly Kuznetsov {
1028862919e5SDavid Hildenbrand 	mem->online_type = memhp_default_online_type;
1029dc18d706SNathan Fontenot 	return device_online(&mem->dev);
103031bc3858SVitaly Kuznetsov }
103131bc3858SVitaly Kuznetsov 
10328df1d0e4SDavid Hildenbrand /*
10338df1d0e4SDavid Hildenbrand  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
10348df1d0e4SDavid Hildenbrand  * and online/offline operations (triggered e.g. by sysfs).
10358df1d0e4SDavid Hildenbrand  *
10368df1d0e4SDavid Hildenbrand  * we are OK calling __meminit stuff here - we have CONFIG_MEMORY_HOTPLUG
10378df1d0e4SDavid Hildenbrand  */
1038f29d8e9cSDavid Hildenbrand int __ref add_memory_resource(int nid, struct resource *res)
1039bc02af93SYasunori Goto {
1040bfeb022fSLogan Gunthorpe 	struct mhp_params params = { .pgprot = PAGE_KERNEL };
104162cedb9fSDavid Vrabel 	u64 start, size;
1042b9ff0360SOscar Salvador 	bool new_node = false;
1043bc02af93SYasunori Goto 	int ret;
1044bc02af93SYasunori Goto 
104562cedb9fSDavid Vrabel 	start = res->start;
104662cedb9fSDavid Vrabel 	size = resource_size(res);
104762cedb9fSDavid Vrabel 
104827356f54SToshi Kani 	ret = check_hotplug_memory_range(start, size);
104927356f54SToshi Kani 	if (ret)
105027356f54SToshi Kani 		return ret;
105127356f54SToshi Kani 
1052fa6d9ec7SVishal Verma 	if (!node_possible(nid)) {
1053fa6d9ec7SVishal Verma 		WARN(1, "node %d was absent from the node_possible_map\n", nid);
1054fa6d9ec7SVishal Verma 		return -EINVAL;
1055fa6d9ec7SVishal Verma 	}
1056fa6d9ec7SVishal Verma 
1057bfc8c901SVladimir Davydov 	mem_hotplug_begin();
1058ac13c462SNathan Zimmer 
105952219aeaSDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
10607f36e3e5STang Chen 		memblock_add_node(start, size, nid);
10617f36e3e5STang Chen 
1062c68ab18cSDavid Hildenbrand 	ret = __try_online_node(nid, false);
1063b9ff0360SOscar Salvador 	if (ret < 0)
106441b9e2d7SWen Congyang 		goto error;
1065b9ff0360SOscar Salvador 	new_node = ret;
10669af3c2deSYasunori Goto 
1067bc02af93SYasunori Goto 	/* call arch's memory hotadd */
1068f5637d3bSLogan Gunthorpe 	ret = arch_add_memory(nid, start, size, &params);
10699af3c2deSYasunori Goto 	if (ret < 0)
10709af3c2deSYasunori Goto 		goto error;
10719af3c2deSYasunori Goto 
1072db051a0dSDavid Hildenbrand 	/* create memory block devices after memory was added */
1073db051a0dSDavid Hildenbrand 	ret = create_memory_block_devices(start, size);
1074db051a0dSDavid Hildenbrand 	if (ret) {
1075db051a0dSDavid Hildenbrand 		arch_remove_memory(nid, start, size, NULL);
1076db051a0dSDavid Hildenbrand 		goto error;
1077db051a0dSDavid Hildenbrand 	}
1078db051a0dSDavid Hildenbrand 
1079a1e565aaSTang Chen 	if (new_node) {
1080d5b6f6a3SOscar Salvador 		/* If sysfs file of new node can't be created, cpu on the node
10810fc44159SYasunori Goto 		 * can't be hot-added. There is no rollback way now.
10820fc44159SYasunori Goto 		 * So, check by BUG_ON() to catch it reluctantly..
1083d5b6f6a3SOscar Salvador 		 * We online node here. We can't roll back from here.
10840fc44159SYasunori Goto 		 */
1085d5b6f6a3SOscar Salvador 		node_set_online(nid);
1086d5b6f6a3SOscar Salvador 		ret = __register_one_node(nid);
10870fc44159SYasunori Goto 		BUG_ON(ret);
10880fc44159SYasunori Goto 	}
10890fc44159SYasunori Goto 
1090d5b6f6a3SOscar Salvador 	/* link memory sections under this node.*/
1091f85086f9SLaurent Dufour 	ret = link_mem_sections(nid, PFN_DOWN(start), PFN_UP(start + size - 1),
1092f85086f9SLaurent Dufour 				MEMINIT_HOTPLUG);
1093d5b6f6a3SOscar Salvador 	BUG_ON(ret);
1094d5b6f6a3SOscar Salvador 
1095d96ae530Sakpm@linux-foundation.org 	/* create new memmap entry */
10967b7b2721SDavid Hildenbrand 	if (!strcmp(res->name, "System RAM"))
1097d96ae530Sakpm@linux-foundation.org 		firmware_map_add_hotplug(start, start + size, "System RAM");
1098d96ae530Sakpm@linux-foundation.org 
1099381eab4aSDavid Hildenbrand 	/* device_online() will take the lock when calling online_pages() */
1100381eab4aSDavid Hildenbrand 	mem_hotplug_done();
1101381eab4aSDavid Hildenbrand 
110231bc3858SVitaly Kuznetsov 	/* online pages if requested */
1103862919e5SDavid Hildenbrand 	if (memhp_default_online_type != MMOP_OFFLINE)
1104fbcf73ceSDavid Hildenbrand 		walk_memory_blocks(start, size, NULL, online_memory_block);
110531bc3858SVitaly Kuznetsov 
1106381eab4aSDavid Hildenbrand 	return ret;
11079af3c2deSYasunori Goto error:
11089af3c2deSYasunori Goto 	/* rollback pgdat allocation and others */
1109b9ff0360SOscar Salvador 	if (new_node)
1110b9ff0360SOscar Salvador 		rollback_node_hotadd(nid);
111152219aeaSDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK))
11127f36e3e5STang Chen 		memblock_remove(start, size);
1113bfc8c901SVladimir Davydov 	mem_hotplug_done();
1114bc02af93SYasunori Goto 	return ret;
1115bc02af93SYasunori Goto }
111662cedb9fSDavid Vrabel 
11178df1d0e4SDavid Hildenbrand /* requires device_hotplug_lock, see add_memory_resource() */
11188df1d0e4SDavid Hildenbrand int __ref __add_memory(int nid, u64 start, u64 size)
111962cedb9fSDavid Vrabel {
112062cedb9fSDavid Vrabel 	struct resource *res;
112162cedb9fSDavid Vrabel 	int ret;
112262cedb9fSDavid Vrabel 
11237b7b2721SDavid Hildenbrand 	res = register_memory_resource(start, size, "System RAM");
11246f754ba4SVitaly Kuznetsov 	if (IS_ERR(res))
11256f754ba4SVitaly Kuznetsov 		return PTR_ERR(res);
112662cedb9fSDavid Vrabel 
1127f29d8e9cSDavid Hildenbrand 	ret = add_memory_resource(nid, res);
112862cedb9fSDavid Vrabel 	if (ret < 0)
112962cedb9fSDavid Vrabel 		release_memory_resource(res);
113062cedb9fSDavid Vrabel 	return ret;
113162cedb9fSDavid Vrabel }
11328df1d0e4SDavid Hildenbrand 
11338df1d0e4SDavid Hildenbrand int add_memory(int nid, u64 start, u64 size)
11348df1d0e4SDavid Hildenbrand {
11358df1d0e4SDavid Hildenbrand 	int rc;
11368df1d0e4SDavid Hildenbrand 
11378df1d0e4SDavid Hildenbrand 	lock_device_hotplug();
11388df1d0e4SDavid Hildenbrand 	rc = __add_memory(nid, start, size);
11398df1d0e4SDavid Hildenbrand 	unlock_device_hotplug();
11408df1d0e4SDavid Hildenbrand 
11418df1d0e4SDavid Hildenbrand 	return rc;
11428df1d0e4SDavid Hildenbrand }
1143bc02af93SYasunori Goto EXPORT_SYMBOL_GPL(add_memory);
11440c0e6195SKAMEZAWA Hiroyuki 
11457b7b2721SDavid Hildenbrand /*
11467b7b2721SDavid Hildenbrand  * Add special, driver-managed memory to the system as system RAM. Such
11477b7b2721SDavid Hildenbrand  * memory is not exposed via the raw firmware-provided memmap as system
11487b7b2721SDavid Hildenbrand  * RAM, instead, it is detected and added by a driver - during cold boot,
11497b7b2721SDavid Hildenbrand  * after a reboot, and after kexec.
11507b7b2721SDavid Hildenbrand  *
11517b7b2721SDavid Hildenbrand  * Reasons why this memory should not be used for the initial memmap of a
11527b7b2721SDavid Hildenbrand  * kexec kernel or for placing kexec images:
11537b7b2721SDavid Hildenbrand  * - The booting kernel is in charge of determining how this memory will be
11547b7b2721SDavid Hildenbrand  *   used (e.g., use persistent memory as system RAM)
11557b7b2721SDavid Hildenbrand  * - Coordination with a hypervisor is required before this memory
11567b7b2721SDavid Hildenbrand  *   can be used (e.g., inaccessible parts).
11577b7b2721SDavid Hildenbrand  *
11587b7b2721SDavid Hildenbrand  * For this memory, no entries in /sys/firmware/memmap ("raw firmware-provided
11597b7b2721SDavid Hildenbrand  * memory map") are created. Also, the created memory resource is flagged
11607b7b2721SDavid Hildenbrand  * with IORESOURCE_MEM_DRIVER_MANAGED, so in-kernel users can special-case
11617b7b2721SDavid Hildenbrand  * this memory as well (esp., not place kexec images onto it).
11627b7b2721SDavid Hildenbrand  *
11637b7b2721SDavid Hildenbrand  * The resource_name (visible via /proc/iomem) has to have the format
11647b7b2721SDavid Hildenbrand  * "System RAM ($DRIVER)".
11657b7b2721SDavid Hildenbrand  */
11667b7b2721SDavid Hildenbrand int add_memory_driver_managed(int nid, u64 start, u64 size,
11677b7b2721SDavid Hildenbrand 			      const char *resource_name)
11687b7b2721SDavid Hildenbrand {
11697b7b2721SDavid Hildenbrand 	struct resource *res;
11707b7b2721SDavid Hildenbrand 	int rc;
11717b7b2721SDavid Hildenbrand 
11727b7b2721SDavid Hildenbrand 	if (!resource_name ||
11737b7b2721SDavid Hildenbrand 	    strstr(resource_name, "System RAM (") != resource_name ||
11747b7b2721SDavid Hildenbrand 	    resource_name[strlen(resource_name) - 1] != ')')
11757b7b2721SDavid Hildenbrand 		return -EINVAL;
11767b7b2721SDavid Hildenbrand 
11777b7b2721SDavid Hildenbrand 	lock_device_hotplug();
11787b7b2721SDavid Hildenbrand 
11797b7b2721SDavid Hildenbrand 	res = register_memory_resource(start, size, resource_name);
11807b7b2721SDavid Hildenbrand 	if (IS_ERR(res)) {
11817b7b2721SDavid Hildenbrand 		rc = PTR_ERR(res);
11827b7b2721SDavid Hildenbrand 		goto out_unlock;
11837b7b2721SDavid Hildenbrand 	}
11847b7b2721SDavid Hildenbrand 
11857b7b2721SDavid Hildenbrand 	rc = add_memory_resource(nid, res);
11867b7b2721SDavid Hildenbrand 	if (rc < 0)
11877b7b2721SDavid Hildenbrand 		release_memory_resource(res);
11887b7b2721SDavid Hildenbrand 
11897b7b2721SDavid Hildenbrand out_unlock:
11907b7b2721SDavid Hildenbrand 	unlock_device_hotplug();
11917b7b2721SDavid Hildenbrand 	return rc;
11927b7b2721SDavid Hildenbrand }
11937b7b2721SDavid Hildenbrand EXPORT_SYMBOL_GPL(add_memory_driver_managed);
11947b7b2721SDavid Hildenbrand 
11950c0e6195SKAMEZAWA Hiroyuki #ifdef CONFIG_MEMORY_HOTREMOVE
11960c0e6195SKAMEZAWA Hiroyuki /*
119792917998SDavid Hildenbrand  * Confirm all pages in a range [start, end) belong to the same zone (skipping
119892917998SDavid Hildenbrand  * memory holes). When true, return the zone.
11990c0e6195SKAMEZAWA Hiroyuki  */
120092917998SDavid Hildenbrand struct zone *test_pages_in_a_zone(unsigned long start_pfn,
120192917998SDavid Hildenbrand 				  unsigned long end_pfn)
12020c0e6195SKAMEZAWA Hiroyuki {
12035f0f2887SAndrew Banman 	unsigned long pfn, sec_end_pfn;
12040c0e6195SKAMEZAWA Hiroyuki 	struct zone *zone = NULL;
12050c0e6195SKAMEZAWA Hiroyuki 	struct page *page;
12060c0e6195SKAMEZAWA Hiroyuki 	int i;
1207deb88a2aSToshi Kani 	for (pfn = start_pfn, sec_end_pfn = SECTION_ALIGN_UP(start_pfn + 1);
12080c0e6195SKAMEZAWA Hiroyuki 	     pfn < end_pfn;
1209deb88a2aSToshi Kani 	     pfn = sec_end_pfn, sec_end_pfn += PAGES_PER_SECTION) {
12105f0f2887SAndrew Banman 		/* Make sure the memory section is present first */
12115f0f2887SAndrew Banman 		if (!present_section_nr(pfn_to_section_nr(pfn)))
12125f0f2887SAndrew Banman 			continue;
12135f0f2887SAndrew Banman 		for (; pfn < sec_end_pfn && pfn < end_pfn;
12140c0e6195SKAMEZAWA Hiroyuki 		     pfn += MAX_ORDER_NR_PAGES) {
12150c0e6195SKAMEZAWA Hiroyuki 			i = 0;
12160c0e6195SKAMEZAWA Hiroyuki 			/* This is just a CONFIG_HOLES_IN_ZONE check.*/
12175f0f2887SAndrew Banman 			while ((i < MAX_ORDER_NR_PAGES) &&
12185f0f2887SAndrew Banman 				!pfn_valid_within(pfn + i))
12190c0e6195SKAMEZAWA Hiroyuki 				i++;
1220d6d8c8a4Szhong jiang 			if (i == MAX_ORDER_NR_PAGES || pfn + i >= end_pfn)
12210c0e6195SKAMEZAWA Hiroyuki 				continue;
122224feb47cSMikhail Zaslonko 			/* Check if we got outside of the zone */
122324feb47cSMikhail Zaslonko 			if (zone && !zone_spans_pfn(zone, pfn + i))
122492917998SDavid Hildenbrand 				return NULL;
12250c0e6195SKAMEZAWA Hiroyuki 			page = pfn_to_page(pfn + i);
12260c0e6195SKAMEZAWA Hiroyuki 			if (zone && page_zone(page) != zone)
122792917998SDavid Hildenbrand 				return NULL;
12280c0e6195SKAMEZAWA Hiroyuki 			zone = page_zone(page);
12290c0e6195SKAMEZAWA Hiroyuki 		}
12305f0f2887SAndrew Banman 	}
1231deb88a2aSToshi Kani 
123292917998SDavid Hildenbrand 	return zone;
1233a96dfddbSToshi Kani }
12340c0e6195SKAMEZAWA Hiroyuki 
12350c0e6195SKAMEZAWA Hiroyuki /*
12360efadf48SYisheng Xie  * Scan pfn range [start,end) to find movable/migratable pages (LRU pages,
1237aa218795SDavid Hildenbrand  * non-lru movable pages and hugepages). Will skip over most unmovable
1238aa218795SDavid Hildenbrand  * pages (esp., pages that can be skipped when offlining), but bail out on
1239aa218795SDavid Hildenbrand  * definitely unmovable pages.
1240aa218795SDavid Hildenbrand  *
1241aa218795SDavid Hildenbrand  * Returns:
1242aa218795SDavid Hildenbrand  *	0 in case a movable page is found and movable_pfn was updated.
1243aa218795SDavid Hildenbrand  *	-ENOENT in case no movable page was found.
1244aa218795SDavid Hildenbrand  *	-EBUSY in case a definitely unmovable page was found.
12450c0e6195SKAMEZAWA Hiroyuki  */
1246aa218795SDavid Hildenbrand static int scan_movable_pages(unsigned long start, unsigned long end,
1247aa218795SDavid Hildenbrand 			      unsigned long *movable_pfn)
12480c0e6195SKAMEZAWA Hiroyuki {
12490c0e6195SKAMEZAWA Hiroyuki 	unsigned long pfn;
1250eeb0efd0SOscar Salvador 
12510c0e6195SKAMEZAWA Hiroyuki 	for (pfn = start; pfn < end; pfn++) {
1252eeb0efd0SOscar Salvador 		struct page *page, *head;
1253eeb0efd0SOscar Salvador 		unsigned long skip;
1254eeb0efd0SOscar Salvador 
1255eeb0efd0SOscar Salvador 		if (!pfn_valid(pfn))
1256eeb0efd0SOscar Salvador 			continue;
12570c0e6195SKAMEZAWA Hiroyuki 		page = pfn_to_page(pfn);
12580c0e6195SKAMEZAWA Hiroyuki 		if (PageLRU(page))
1259aa218795SDavid Hildenbrand 			goto found;
12600efadf48SYisheng Xie 		if (__PageMovable(page))
1261aa218795SDavid Hildenbrand 			goto found;
1262aa218795SDavid Hildenbrand 
1263aa218795SDavid Hildenbrand 		/*
1264aa218795SDavid Hildenbrand 		 * PageOffline() pages that are not marked __PageMovable() and
1265aa218795SDavid Hildenbrand 		 * have a reference count > 0 (after MEM_GOING_OFFLINE) are
1266aa218795SDavid Hildenbrand 		 * definitely unmovable. If their reference count would be 0,
1267aa218795SDavid Hildenbrand 		 * they could at least be skipped when offlining memory.
1268aa218795SDavid Hildenbrand 		 */
1269aa218795SDavid Hildenbrand 		if (PageOffline(page) && page_count(page))
1270aa218795SDavid Hildenbrand 			return -EBUSY;
1271eeb0efd0SOscar Salvador 
1272eeb0efd0SOscar Salvador 		if (!PageHuge(page))
1273eeb0efd0SOscar Salvador 			continue;
1274eeb0efd0SOscar Salvador 		head = compound_head(page);
127539186cbeSOscar Salvador 		if (page_huge_active(head))
1276aa218795SDavid Hildenbrand 			goto found;
1277d8c6546bSMatthew Wilcox (Oracle) 		skip = compound_nr(head) - (page - head);
1278eeb0efd0SOscar Salvador 		pfn += skip - 1;
12790c0e6195SKAMEZAWA Hiroyuki 	}
1280aa218795SDavid Hildenbrand 	return -ENOENT;
1281aa218795SDavid Hildenbrand found:
1282aa218795SDavid Hildenbrand 	*movable_pfn = pfn;
12830c0e6195SKAMEZAWA Hiroyuki 	return 0;
12840c0e6195SKAMEZAWA Hiroyuki }
12850c0e6195SKAMEZAWA Hiroyuki 
1286666feb21SMichal Hocko static struct page *new_node_page(struct page *page, unsigned long private)
1287394e31d2SXishi Qiu {
1288231e97e2SLi Zhong 	nodemask_t nmask = node_states[N_MEMORY];
128919fc7bedSJoonsoo Kim 	struct migration_target_control mtc = {
129019fc7bedSJoonsoo Kim 		.nid = page_to_nid(page),
129119fc7bedSJoonsoo Kim 		.nmask = &nmask,
129219fc7bedSJoonsoo Kim 		.gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
129319fc7bedSJoonsoo Kim 	};
12947f252f27SMichal Hocko 
12957f252f27SMichal Hocko 	/*
12967f252f27SMichal Hocko 	 * try to allocate from a different node but reuse this node if there
12977f252f27SMichal Hocko 	 * are no other online nodes to be used (e.g. we are offlining a part
12987f252f27SMichal Hocko 	 * of the only existing node)
12997f252f27SMichal Hocko 	 */
130019fc7bedSJoonsoo Kim 	node_clear(mtc.nid, nmask);
13017f252f27SMichal Hocko 	if (nodes_empty(nmask))
130219fc7bedSJoonsoo Kim 		node_set(mtc.nid, nmask);
1303394e31d2SXishi Qiu 
130419fc7bedSJoonsoo Kim 	return alloc_migration_target(page, (unsigned long)&mtc);
1305394e31d2SXishi Qiu }
1306394e31d2SXishi Qiu 
13070c0e6195SKAMEZAWA Hiroyuki static int
13080c0e6195SKAMEZAWA Hiroyuki do_migrate_range(unsigned long start_pfn, unsigned long end_pfn)
13090c0e6195SKAMEZAWA Hiroyuki {
13100c0e6195SKAMEZAWA Hiroyuki 	unsigned long pfn;
13116c357848SMatthew Wilcox (Oracle) 	struct page *page, *head;
13120c0e6195SKAMEZAWA Hiroyuki 	int ret = 0;
13130c0e6195SKAMEZAWA Hiroyuki 	LIST_HEAD(source);
13140c0e6195SKAMEZAWA Hiroyuki 
1315a85009c3SMichal Hocko 	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
13160c0e6195SKAMEZAWA Hiroyuki 		if (!pfn_valid(pfn))
13170c0e6195SKAMEZAWA Hiroyuki 			continue;
13180c0e6195SKAMEZAWA Hiroyuki 		page = pfn_to_page(pfn);
13196c357848SMatthew Wilcox (Oracle) 		head = compound_head(page);
1320c8721bbbSNaoya Horiguchi 
1321c8721bbbSNaoya Horiguchi 		if (PageHuge(page)) {
1322d8c6546bSMatthew Wilcox (Oracle) 			pfn = page_to_pfn(head) + compound_nr(head) - 1;
1323daf3538aSOscar Salvador 			isolate_huge_page(head, &source);
1324c8721bbbSNaoya Horiguchi 			continue;
132594723aafSMichal Hocko 		} else if (PageTransHuge(page))
13266c357848SMatthew Wilcox (Oracle) 			pfn = page_to_pfn(head) + thp_nr_pages(page) - 1;
1327c8721bbbSNaoya Horiguchi 
1328b15c8726SMichal Hocko 		/*
1329b15c8726SMichal Hocko 		 * HWPoison pages have elevated reference counts so the migration would
1330b15c8726SMichal Hocko 		 * fail on them. It also doesn't make any sense to migrate them in the
1331b15c8726SMichal Hocko 		 * first place. Still try to unmap such a page in case it is still mapped
1332b15c8726SMichal Hocko 		 * (e.g. current hwpoison implementation doesn't unmap KSM pages but keep
1333b15c8726SMichal Hocko 		 * the unmap as the catch all safety net).
1334b15c8726SMichal Hocko 		 */
1335b15c8726SMichal Hocko 		if (PageHWPoison(page)) {
1336b15c8726SMichal Hocko 			if (WARN_ON(PageLRU(page)))
1337b15c8726SMichal Hocko 				isolate_lru_page(page);
1338b15c8726SMichal Hocko 			if (page_mapped(page))
1339b15c8726SMichal Hocko 				try_to_unmap(page, TTU_IGNORE_MLOCK | TTU_IGNORE_ACCESS);
1340b15c8726SMichal Hocko 			continue;
1341b15c8726SMichal Hocko 		}
1342b15c8726SMichal Hocko 
1343700c2a46SKonstantin Khlebnikov 		if (!get_page_unless_zero(page))
13440c0e6195SKAMEZAWA Hiroyuki 			continue;
13450c0e6195SKAMEZAWA Hiroyuki 		/*
13460efadf48SYisheng Xie 		 * We can skip free pages. And we can deal with pages on
13470efadf48SYisheng Xie 		 * LRU and non-lru movable pages.
13480c0e6195SKAMEZAWA Hiroyuki 		 */
13490efadf48SYisheng Xie 		if (PageLRU(page))
135062695a84SNick Piggin 			ret = isolate_lru_page(page);
13510efadf48SYisheng Xie 		else
13520efadf48SYisheng Xie 			ret = isolate_movable_page(page, ISOLATE_UNEVICTABLE);
13530c0e6195SKAMEZAWA Hiroyuki 		if (!ret) { /* Success */
135462695a84SNick Piggin 			list_add_tail(&page->lru, &source);
13550efadf48SYisheng Xie 			if (!__PageMovable(page))
1356599d0c95SMel Gorman 				inc_node_page_state(page, NR_ISOLATED_ANON +
13579de4f22aSHuang Ying 						    page_is_file_lru(page));
13586d9c285aSKOSAKI Motohiro 
13590c0e6195SKAMEZAWA Hiroyuki 		} else {
13602932c8b0SMichal Hocko 			pr_warn("failed to isolate pfn %lx\n", pfn);
13610efadf48SYisheng Xie 			dump_page(page, "isolation failed");
13621723058eSOscar Salvador 		}
1363700c2a46SKonstantin Khlebnikov 		put_page(page);
13640c0e6195SKAMEZAWA Hiroyuki 	}
1365f3ab2636SBob Liu 	if (!list_empty(&source)) {
1366394e31d2SXishi Qiu 		/* Allocate a new page from the nearest neighbor node */
1367394e31d2SXishi Qiu 		ret = migrate_pages(&source, new_node_page, NULL, 0,
13689c620e2bSHugh Dickins 					MIGRATE_SYNC, MR_MEMORY_HOTPLUG);
13692932c8b0SMichal Hocko 		if (ret) {
13702932c8b0SMichal Hocko 			list_for_each_entry(page, &source, lru) {
13712932c8b0SMichal Hocko 				pr_warn("migrating pfn %lx failed ret:%d ",
13722932c8b0SMichal Hocko 				       page_to_pfn(page), ret);
13732932c8b0SMichal Hocko 				dump_page(page, "migration failure");
13742932c8b0SMichal Hocko 			}
1375c8721bbbSNaoya Horiguchi 			putback_movable_pages(&source);
1376f3ab2636SBob Liu 		}
13772932c8b0SMichal Hocko 	}
13781723058eSOscar Salvador 
13790c0e6195SKAMEZAWA Hiroyuki 	return ret;
13800c0e6195SKAMEZAWA Hiroyuki }
13810c0e6195SKAMEZAWA Hiroyuki 
13820ee5f4f3SDavid Hildenbrand /* Mark all sections offline and remove all free pages from the buddy. */
13830c0e6195SKAMEZAWA Hiroyuki static int
13840c0e6195SKAMEZAWA Hiroyuki offline_isolated_pages_cb(unsigned long start, unsigned long nr_pages,
13850c0e6195SKAMEZAWA Hiroyuki 			void *data)
13860c0e6195SKAMEZAWA Hiroyuki {
13875557c766SMichal Hocko 	unsigned long *offlined_pages = (unsigned long *)data;
13880c0e6195SKAMEZAWA Hiroyuki 
13895557c766SMichal Hocko 	*offlined_pages += __offline_isolated_pages(start, start + nr_pages);
13905557c766SMichal Hocko 	return 0;
13910c0e6195SKAMEZAWA Hiroyuki }
13920c0e6195SKAMEZAWA Hiroyuki 
13930c0e6195SKAMEZAWA Hiroyuki /*
139452cfc245SEthon Paul  * Check all pages in range, recorded as memory resource, are isolated.
13950c0e6195SKAMEZAWA Hiroyuki  */
13960c0e6195SKAMEZAWA Hiroyuki static int
13970c0e6195SKAMEZAWA Hiroyuki check_pages_isolated_cb(unsigned long start_pfn, unsigned long nr_pages,
13980c0e6195SKAMEZAWA Hiroyuki 			void *data)
13990c0e6195SKAMEZAWA Hiroyuki {
1400756d25beSDavid Hildenbrand 	return test_pages_isolated(start_pfn, start_pfn + nr_pages,
1401756d25beSDavid Hildenbrand 				   MEMORY_OFFLINE);
14020c0e6195SKAMEZAWA Hiroyuki }
14030c0e6195SKAMEZAWA Hiroyuki 
1404c5320926STang Chen static int __init cmdline_parse_movable_node(char *p)
1405c5320926STang Chen {
140655ac590cSTang Chen 	movable_node_enabled = true;
1407c5320926STang Chen 	return 0;
1408c5320926STang Chen }
1409c5320926STang Chen early_param("movable_node", cmdline_parse_movable_node);
1410c5320926STang Chen 
1411d9713679SLai Jiangshan /* check which state of node_states will be changed when offline memory */
1412d9713679SLai Jiangshan static void node_states_check_changes_offline(unsigned long nr_pages,
1413d9713679SLai Jiangshan 		struct zone *zone, struct memory_notify *arg)
1414d9713679SLai Jiangshan {
1415d9713679SLai Jiangshan 	struct pglist_data *pgdat = zone->zone_pgdat;
1416d9713679SLai Jiangshan 	unsigned long present_pages = 0;
141786b27beaSOscar Salvador 	enum zone_type zt;
1418d9713679SLai Jiangshan 
141998fa15f3SAnshuman Khandual 	arg->status_change_nid = NUMA_NO_NODE;
142098fa15f3SAnshuman Khandual 	arg->status_change_nid_normal = NUMA_NO_NODE;
142198fa15f3SAnshuman Khandual 	arg->status_change_nid_high = NUMA_NO_NODE;
142286b27beaSOscar Salvador 
142386b27beaSOscar Salvador 	/*
142486b27beaSOscar Salvador 	 * Check whether node_states[N_NORMAL_MEMORY] will be changed.
142586b27beaSOscar Salvador 	 * If the memory to be offline is within the range
142686b27beaSOscar Salvador 	 * [0..ZONE_NORMAL], and it is the last present memory there,
142786b27beaSOscar Salvador 	 * the zones in that range will become empty after the offlining,
142886b27beaSOscar Salvador 	 * thus we can determine that we need to clear the node from
142986b27beaSOscar Salvador 	 * node_states[N_NORMAL_MEMORY].
143086b27beaSOscar Salvador 	 */
143186b27beaSOscar Salvador 	for (zt = 0; zt <= ZONE_NORMAL; zt++)
143286b27beaSOscar Salvador 		present_pages += pgdat->node_zones[zt].present_pages;
143386b27beaSOscar Salvador 	if (zone_idx(zone) <= ZONE_NORMAL && nr_pages >= present_pages)
143486b27beaSOscar Salvador 		arg->status_change_nid_normal = zone_to_nid(zone);
1435d9713679SLai Jiangshan 
14366715ddf9SLai Jiangshan #ifdef CONFIG_HIGHMEM
14376715ddf9SLai Jiangshan 	/*
143886b27beaSOscar Salvador 	 * node_states[N_HIGH_MEMORY] contains nodes which
143986b27beaSOscar Salvador 	 * have normal memory or high memory.
144086b27beaSOscar Salvador 	 * Here we add the present_pages belonging to ZONE_HIGHMEM.
144186b27beaSOscar Salvador 	 * If the zone is within the range of [0..ZONE_HIGHMEM), and
144286b27beaSOscar Salvador 	 * we determine that the zones in that range become empty,
144386b27beaSOscar Salvador 	 * we need to clear the node for N_HIGH_MEMORY.
14446715ddf9SLai Jiangshan 	 */
144586b27beaSOscar Salvador 	present_pages += pgdat->node_zones[ZONE_HIGHMEM].present_pages;
144686b27beaSOscar Salvador 	if (zone_idx(zone) <= ZONE_HIGHMEM && nr_pages >= present_pages)
14476715ddf9SLai Jiangshan 		arg->status_change_nid_high = zone_to_nid(zone);
14486715ddf9SLai Jiangshan #endif
14496715ddf9SLai Jiangshan 
1450d9713679SLai Jiangshan 	/*
145186b27beaSOscar Salvador 	 * We have accounted the pages from [0..ZONE_NORMAL), and
145286b27beaSOscar Salvador 	 * in case of CONFIG_HIGHMEM the pages from ZONE_HIGHMEM
145386b27beaSOscar Salvador 	 * as well.
145486b27beaSOscar Salvador 	 * Here we count the possible pages from ZONE_MOVABLE.
145586b27beaSOscar Salvador 	 * If after having accounted all the pages, we see that the nr_pages
145686b27beaSOscar Salvador 	 * to be offlined is over or equal to the accounted pages,
145786b27beaSOscar Salvador 	 * we know that the node will become empty, and so, we can clear
145886b27beaSOscar Salvador 	 * it for N_MEMORY as well.
1459d9713679SLai Jiangshan 	 */
146086b27beaSOscar Salvador 	present_pages += pgdat->node_zones[ZONE_MOVABLE].present_pages;
1461d9713679SLai Jiangshan 
1462d9713679SLai Jiangshan 	if (nr_pages >= present_pages)
1463d9713679SLai Jiangshan 		arg->status_change_nid = zone_to_nid(zone);
1464d9713679SLai Jiangshan }
1465d9713679SLai Jiangshan 
1466d9713679SLai Jiangshan static void node_states_clear_node(int node, struct memory_notify *arg)
1467d9713679SLai Jiangshan {
1468d9713679SLai Jiangshan 	if (arg->status_change_nid_normal >= 0)
1469d9713679SLai Jiangshan 		node_clear_state(node, N_NORMAL_MEMORY);
1470d9713679SLai Jiangshan 
1471cf01f6f5SOscar Salvador 	if (arg->status_change_nid_high >= 0)
1472d9713679SLai Jiangshan 		node_clear_state(node, N_HIGH_MEMORY);
14736715ddf9SLai Jiangshan 
1474cf01f6f5SOscar Salvador 	if (arg->status_change_nid >= 0)
14756715ddf9SLai Jiangshan 		node_clear_state(node, N_MEMORY);
1476d9713679SLai Jiangshan }
1477d9713679SLai Jiangshan 
1478c5e79ef5SDavid Hildenbrand static int count_system_ram_pages_cb(unsigned long start_pfn,
1479c5e79ef5SDavid Hildenbrand 				     unsigned long nr_pages, void *data)
1480c5e79ef5SDavid Hildenbrand {
1481c5e79ef5SDavid Hildenbrand 	unsigned long *nr_system_ram_pages = data;
1482c5e79ef5SDavid Hildenbrand 
1483c5e79ef5SDavid Hildenbrand 	*nr_system_ram_pages += nr_pages;
1484c5e79ef5SDavid Hildenbrand 	return 0;
1485c5e79ef5SDavid Hildenbrand }
1486c5e79ef5SDavid Hildenbrand 
1487*73a11c96SDavid Hildenbrand int __ref offline_pages(unsigned long start_pfn, unsigned long nr_pages)
14880c0e6195SKAMEZAWA Hiroyuki {
1489*73a11c96SDavid Hildenbrand 	const unsigned long end_pfn = start_pfn + nr_pages;
1490*73a11c96SDavid Hildenbrand 	unsigned long pfn, system_ram_pages = 0, offlined_pages = 0;
14919b7ea46aSQian Cai 	int ret, node, nr_isolate_pageblock;
1492d702909fSCody P Schafer 	unsigned long flags;
14930c0e6195SKAMEZAWA Hiroyuki 	struct zone *zone;
14947b78d335SYasunori Goto 	struct memory_notify arg;
149579605093SMichal Hocko 	char *reason;
14960c0e6195SKAMEZAWA Hiroyuki 
1497381eab4aSDavid Hildenbrand 	mem_hotplug_begin();
1498381eab4aSDavid Hildenbrand 
1499c5e79ef5SDavid Hildenbrand 	/*
1500c5e79ef5SDavid Hildenbrand 	 * Don't allow to offline memory blocks that contain holes.
1501c5e79ef5SDavid Hildenbrand 	 * Consequently, memory blocks with holes can never get onlined
1502c5e79ef5SDavid Hildenbrand 	 * via the hotplug path - online_pages() - as hotplugged memory has
1503c5e79ef5SDavid Hildenbrand 	 * no holes. This way, we e.g., don't have to worry about marking
1504c5e79ef5SDavid Hildenbrand 	 * memory holes PG_reserved, don't need pfn_valid() checks, and can
1505c5e79ef5SDavid Hildenbrand 	 * avoid using walk_system_ram_range() later.
1506c5e79ef5SDavid Hildenbrand 	 */
1507*73a11c96SDavid Hildenbrand 	walk_system_ram_range(start_pfn, nr_pages, &system_ram_pages,
1508c5e79ef5SDavid Hildenbrand 			      count_system_ram_pages_cb);
1509*73a11c96SDavid Hildenbrand 	if (system_ram_pages != nr_pages) {
1510c5e79ef5SDavid Hildenbrand 		ret = -EINVAL;
1511c5e79ef5SDavid Hildenbrand 		reason = "memory holes";
1512c5e79ef5SDavid Hildenbrand 		goto failed_removal;
1513c5e79ef5SDavid Hildenbrand 	}
1514c5e79ef5SDavid Hildenbrand 
15150c0e6195SKAMEZAWA Hiroyuki 	/* This makes hotplug much easier...and readable.
15160c0e6195SKAMEZAWA Hiroyuki 	   we assume this for now. .*/
151792917998SDavid Hildenbrand 	zone = test_pages_in_a_zone(start_pfn, end_pfn);
151892917998SDavid Hildenbrand 	if (!zone) {
151979605093SMichal Hocko 		ret = -EINVAL;
152079605093SMichal Hocko 		reason = "multizone range";
152179605093SMichal Hocko 		goto failed_removal;
1522381eab4aSDavid Hildenbrand 	}
15237b78d335SYasunori Goto 	node = zone_to_nid(zone);
15247b78d335SYasunori Goto 
15250c0e6195SKAMEZAWA Hiroyuki 	/* set above range as isolated */
1526b023f468SWen Congyang 	ret = start_isolate_page_range(start_pfn, end_pfn,
1527d381c547SMichal Hocko 				       MIGRATE_MOVABLE,
1528756d25beSDavid Hildenbrand 				       MEMORY_OFFLINE | REPORT_FAILURE);
15299b7ea46aSQian Cai 	if (ret < 0) {
153079605093SMichal Hocko 		reason = "failure to isolate range";
153179605093SMichal Hocko 		goto failed_removal;
1532381eab4aSDavid Hildenbrand 	}
15339b7ea46aSQian Cai 	nr_isolate_pageblock = ret;
15347b78d335SYasunori Goto 
15357b78d335SYasunori Goto 	arg.start_pfn = start_pfn;
15367b78d335SYasunori Goto 	arg.nr_pages = nr_pages;
1537d9713679SLai Jiangshan 	node_states_check_changes_offline(nr_pages, zone, &arg);
15387b78d335SYasunori Goto 
15397b78d335SYasunori Goto 	ret = memory_notify(MEM_GOING_OFFLINE, &arg);
15407b78d335SYasunori Goto 	ret = notifier_to_errno(ret);
154179605093SMichal Hocko 	if (ret) {
154279605093SMichal Hocko 		reason = "notifier failure";
154379605093SMichal Hocko 		goto failed_removal_isolated;
154479605093SMichal Hocko 	}
15457b78d335SYasunori Goto 
1546bb8965bdSMichal Hocko 	do {
1547aa218795SDavid Hildenbrand 		pfn = start_pfn;
1548aa218795SDavid Hildenbrand 		do {
154979605093SMichal Hocko 			if (signal_pending(current)) {
1550bb8965bdSMichal Hocko 				ret = -EINTR;
155179605093SMichal Hocko 				reason = "signal backoff";
155279605093SMichal Hocko 				goto failed_removal_isolated;
155379605093SMichal Hocko 			}
155472b39cfcSMichal Hocko 
15550c0e6195SKAMEZAWA Hiroyuki 			cond_resched();
15569852a721SMichal Hocko 			lru_add_drain_all();
15570c0e6195SKAMEZAWA Hiroyuki 
1558aa218795SDavid Hildenbrand 			ret = scan_movable_pages(pfn, end_pfn, &pfn);
1559aa218795SDavid Hildenbrand 			if (!ret) {
1560bb8965bdSMichal Hocko 				/*
1561bb8965bdSMichal Hocko 				 * TODO: fatal migration failures should bail
1562bb8965bdSMichal Hocko 				 * out
1563bb8965bdSMichal Hocko 				 */
1564bb8965bdSMichal Hocko 				do_migrate_range(pfn, end_pfn);
1565bb8965bdSMichal Hocko 			}
1566aa218795SDavid Hildenbrand 		} while (!ret);
1567aa218795SDavid Hildenbrand 
1568aa218795SDavid Hildenbrand 		if (ret != -ENOENT) {
1569aa218795SDavid Hildenbrand 			reason = "unmovable page";
1570aa218795SDavid Hildenbrand 			goto failed_removal_isolated;
15710c0e6195SKAMEZAWA Hiroyuki 		}
157272b39cfcSMichal Hocko 
1573c8721bbbSNaoya Horiguchi 		/*
1574bb8965bdSMichal Hocko 		 * Dissolve free hugepages in the memory block before doing
1575bb8965bdSMichal Hocko 		 * offlining actually in order to make hugetlbfs's object
1576bb8965bdSMichal Hocko 		 * counting consistent.
1577c8721bbbSNaoya Horiguchi 		 */
1578082d5b6bSGerald Schaefer 		ret = dissolve_free_huge_pages(start_pfn, end_pfn);
157979605093SMichal Hocko 		if (ret) {
158079605093SMichal Hocko 			reason = "failure to dissolve huge pages";
158179605093SMichal Hocko 			goto failed_removal_isolated;
158279605093SMichal Hocko 		}
15830c0e6195SKAMEZAWA Hiroyuki 		/* check again */
15845557c766SMichal Hocko 		ret = walk_system_ram_range(start_pfn, end_pfn - start_pfn,
15855557c766SMichal Hocko 					    NULL, check_pages_isolated_cb);
158696831826SPavel Tatashin 		/*
158796831826SPavel Tatashin 		 * per-cpu pages are drained in start_isolate_page_range, but if
158896831826SPavel Tatashin 		 * there are still pages that are not free, make sure that we
158996831826SPavel Tatashin 		 * drain again, because when we isolated range we might
159096831826SPavel Tatashin 		 * have raced with another thread that was adding pages to pcp
159196831826SPavel Tatashin 		 * list.
159296831826SPavel Tatashin 		 *
159396831826SPavel Tatashin 		 * Forward progress should be still guaranteed because
159496831826SPavel Tatashin 		 * pages on the pcp list can only belong to MOVABLE_ZONE
159596831826SPavel Tatashin 		 * because has_unmovable_pages explicitly checks for
159696831826SPavel Tatashin 		 * PageBuddy on freed pages on other zones.
159796831826SPavel Tatashin 		 */
159896831826SPavel Tatashin 		if (ret)
159996831826SPavel Tatashin 			drain_all_pages(zone);
16005557c766SMichal Hocko 	} while (ret);
1601bb8965bdSMichal Hocko 
1602b3834be5SAdam Buchbinder 	/* Ok, all of our target is isolated.
16030c0e6195SKAMEZAWA Hiroyuki 	   We cannot do rollback at this point. */
16045557c766SMichal Hocko 	walk_system_ram_range(start_pfn, end_pfn - start_pfn,
16055557c766SMichal Hocko 			      &offlined_pages, offline_isolated_pages_cb);
16065557c766SMichal Hocko 	pr_info("Offlined Pages %ld\n", offlined_pages);
16079b7ea46aSQian Cai 	/*
16089b7ea46aSQian Cai 	 * Onlining will reset pagetype flags and makes migrate type
16099b7ea46aSQian Cai 	 * MOVABLE, so just need to decrease the number of isolated
16109b7ea46aSQian Cai 	 * pageblocks zone counter here.
16119b7ea46aSQian Cai 	 */
16129b7ea46aSQian Cai 	spin_lock_irqsave(&zone->lock, flags);
16139b7ea46aSQian Cai 	zone->nr_isolate_pageblock -= nr_isolate_pageblock;
16149b7ea46aSQian Cai 	spin_unlock_irqrestore(&zone->lock, flags);
16159b7ea46aSQian Cai 
16160c0e6195SKAMEZAWA Hiroyuki 	/* removal success */
16173dcc0571SJiang Liu 	adjust_managed_page_count(pfn_to_page(start_pfn), -offlined_pages);
16180c0e6195SKAMEZAWA Hiroyuki 	zone->present_pages -= offlined_pages;
1619d702909fSCody P Schafer 
1620d702909fSCody P Schafer 	pgdat_resize_lock(zone->zone_pgdat, &flags);
16210c0e6195SKAMEZAWA Hiroyuki 	zone->zone_pgdat->node_present_pages -= offlined_pages;
1622d702909fSCody P Schafer 	pgdat_resize_unlock(zone->zone_pgdat, &flags);
16237b78d335SYasunori Goto 
16241b79acc9SKOSAKI Motohiro 	init_per_zone_wmark_min();
16251b79acc9SKOSAKI Motohiro 
16261e8537baSXishi Qiu 	if (!populated_zone(zone)) {
1627340175b7SJiang Liu 		zone_pcp_reset(zone);
162872675e13SMichal Hocko 		build_all_zonelists(NULL);
16291e8537baSXishi Qiu 	} else
16301e8537baSXishi Qiu 		zone_pcp_update(zone);
1631340175b7SJiang Liu 
1632d9713679SLai Jiangshan 	node_states_clear_node(node, &arg);
1633698b1b30SVlastimil Babka 	if (arg.status_change_nid >= 0) {
16348fe23e05SDavid Rientjes 		kswapd_stop(node);
1635698b1b30SVlastimil Babka 		kcompactd_stop(node);
1636698b1b30SVlastimil Babka 	}
1637bce7394aSMinchan Kim 
16380c0e6195SKAMEZAWA Hiroyuki 	writeback_set_ratelimit();
16397b78d335SYasunori Goto 
16407b78d335SYasunori Goto 	memory_notify(MEM_OFFLINE, &arg);
1641feee6b29SDavid Hildenbrand 	remove_pfn_range_from_zone(zone, start_pfn, nr_pages);
1642381eab4aSDavid Hildenbrand 	mem_hotplug_done();
16430c0e6195SKAMEZAWA Hiroyuki 	return 0;
16440c0e6195SKAMEZAWA Hiroyuki 
164579605093SMichal Hocko failed_removal_isolated:
164679605093SMichal Hocko 	undo_isolate_page_range(start_pfn, end_pfn, MIGRATE_MOVABLE);
1647c4efe484SQian Cai 	memory_notify(MEM_CANCEL_OFFLINE, &arg);
16480c0e6195SKAMEZAWA Hiroyuki failed_removal:
164979605093SMichal Hocko 	pr_debug("memory offlining [mem %#010llx-%#010llx] failed due to %s\n",
1650a62e2f4fSBjorn Helgaas 		 (unsigned long long) start_pfn << PAGE_SHIFT,
165179605093SMichal Hocko 		 ((unsigned long long) end_pfn << PAGE_SHIFT) - 1,
165279605093SMichal Hocko 		 reason);
16530c0e6195SKAMEZAWA Hiroyuki 	/* pushback to free area */
1654381eab4aSDavid Hildenbrand 	mem_hotplug_done();
16550c0e6195SKAMEZAWA Hiroyuki 	return ret;
16560c0e6195SKAMEZAWA Hiroyuki }
165771088785SBadari Pulavarty 
1658d6de9d53SXishi Qiu static int check_memblock_offlined_cb(struct memory_block *mem, void *arg)
1659bbc76be6SWen Congyang {
1660bbc76be6SWen Congyang 	int ret = !is_memblock_offlined(mem);
1661bbc76be6SWen Congyang 
1662349daa0fSRandy Dunlap 	if (unlikely(ret)) {
1663349daa0fSRandy Dunlap 		phys_addr_t beginpa, endpa;
1664349daa0fSRandy Dunlap 
1665349daa0fSRandy Dunlap 		beginpa = PFN_PHYS(section_nr_to_pfn(mem->start_section_nr));
1666b6c88d3bSDavid Hildenbrand 		endpa = beginpa + memory_block_size_bytes() - 1;
1667756a025fSJoe Perches 		pr_warn("removing memory fails, because memory [%pa-%pa] is onlined\n",
1668349daa0fSRandy Dunlap 			&beginpa, &endpa);
1669bbc76be6SWen Congyang 
1670eca499abSPavel Tatashin 		return -EBUSY;
1671eca499abSPavel Tatashin 	}
1672eca499abSPavel Tatashin 	return 0;
1673bbc76be6SWen Congyang }
1674bbc76be6SWen Congyang 
16750f1cfe9dSToshi Kani static int check_cpu_on_node(pg_data_t *pgdat)
167660a5a19eSTang Chen {
167760a5a19eSTang Chen 	int cpu;
167860a5a19eSTang Chen 
167960a5a19eSTang Chen 	for_each_present_cpu(cpu) {
168060a5a19eSTang Chen 		if (cpu_to_node(cpu) == pgdat->node_id)
168160a5a19eSTang Chen 			/*
168260a5a19eSTang Chen 			 * the cpu on this node isn't removed, and we can't
168360a5a19eSTang Chen 			 * offline this node.
168460a5a19eSTang Chen 			 */
168560a5a19eSTang Chen 			return -EBUSY;
168660a5a19eSTang Chen 	}
168760a5a19eSTang Chen 
168860a5a19eSTang Chen 	return 0;
168960a5a19eSTang Chen }
169060a5a19eSTang Chen 
16912c91f8fcSDavid Hildenbrand static int check_no_memblock_for_node_cb(struct memory_block *mem, void *arg)
16922c91f8fcSDavid Hildenbrand {
16932c91f8fcSDavid Hildenbrand 	int nid = *(int *)arg;
16942c91f8fcSDavid Hildenbrand 
16952c91f8fcSDavid Hildenbrand 	/*
16962c91f8fcSDavid Hildenbrand 	 * If a memory block belongs to multiple nodes, the stored nid is not
16972c91f8fcSDavid Hildenbrand 	 * reliable. However, such blocks are always online (e.g., cannot get
16982c91f8fcSDavid Hildenbrand 	 * offlined) and, therefore, are still spanned by the node.
16992c91f8fcSDavid Hildenbrand 	 */
17002c91f8fcSDavid Hildenbrand 	return mem->nid == nid ? -EEXIST : 0;
17012c91f8fcSDavid Hildenbrand }
17022c91f8fcSDavid Hildenbrand 
17030f1cfe9dSToshi Kani /**
17040f1cfe9dSToshi Kani  * try_offline_node
1705e8b098fcSMike Rapoport  * @nid: the node ID
17060f1cfe9dSToshi Kani  *
17070f1cfe9dSToshi Kani  * Offline a node if all memory sections and cpus of the node are removed.
17080f1cfe9dSToshi Kani  *
17090f1cfe9dSToshi Kani  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
17100f1cfe9dSToshi Kani  * and online/offline operations before this call.
17110f1cfe9dSToshi Kani  */
171290b30cdcSWen Congyang void try_offline_node(int nid)
171360a5a19eSTang Chen {
1714d822b86aSWen Congyang 	pg_data_t *pgdat = NODE_DATA(nid);
17152c91f8fcSDavid Hildenbrand 	int rc;
171660a5a19eSTang Chen 
171760a5a19eSTang Chen 	/*
17182c91f8fcSDavid Hildenbrand 	 * If the node still spans pages (especially ZONE_DEVICE), don't
17192c91f8fcSDavid Hildenbrand 	 * offline it. A node spans memory after move_pfn_range_to_zone(),
17202c91f8fcSDavid Hildenbrand 	 * e.g., after the memory block was onlined.
172160a5a19eSTang Chen 	 */
17222c91f8fcSDavid Hildenbrand 	if (pgdat->node_spanned_pages)
172360a5a19eSTang Chen 		return;
17242c91f8fcSDavid Hildenbrand 
17252c91f8fcSDavid Hildenbrand 	/*
17262c91f8fcSDavid Hildenbrand 	 * Especially offline memory blocks might not be spanned by the
17272c91f8fcSDavid Hildenbrand 	 * node. They will get spanned by the node once they get onlined.
17282c91f8fcSDavid Hildenbrand 	 * However, they link to the node in sysfs and can get onlined later.
17292c91f8fcSDavid Hildenbrand 	 */
17302c91f8fcSDavid Hildenbrand 	rc = for_each_memory_block(&nid, check_no_memblock_for_node_cb);
17312c91f8fcSDavid Hildenbrand 	if (rc)
17322c91f8fcSDavid Hildenbrand 		return;
173360a5a19eSTang Chen 
173446a3679bSMichal Hocko 	if (check_cpu_on_node(pgdat))
173560a5a19eSTang Chen 		return;
173660a5a19eSTang Chen 
173760a5a19eSTang Chen 	/*
173860a5a19eSTang Chen 	 * all memory/cpu of this node are removed, we can offline this
173960a5a19eSTang Chen 	 * node now.
174060a5a19eSTang Chen 	 */
174160a5a19eSTang Chen 	node_set_offline(nid);
174260a5a19eSTang Chen 	unregister_one_node(nid);
174360a5a19eSTang Chen }
174490b30cdcSWen Congyang EXPORT_SYMBOL(try_offline_node);
174560a5a19eSTang Chen 
1746d9eb1417SDavid Hildenbrand static void __release_memory_resource(resource_size_t start,
1747d9eb1417SDavid Hildenbrand 				      resource_size_t size)
1748d9eb1417SDavid Hildenbrand {
1749d9eb1417SDavid Hildenbrand 	int ret;
1750d9eb1417SDavid Hildenbrand 
1751d9eb1417SDavid Hildenbrand 	/*
1752d9eb1417SDavid Hildenbrand 	 * When removing memory in the same granularity as it was added,
1753d9eb1417SDavid Hildenbrand 	 * this function never fails. It might only fail if resources
1754d9eb1417SDavid Hildenbrand 	 * have to be adjusted or split. We'll ignore the error, as
1755d9eb1417SDavid Hildenbrand 	 * removing of memory cannot fail.
1756d9eb1417SDavid Hildenbrand 	 */
1757d9eb1417SDavid Hildenbrand 	ret = release_mem_region_adjustable(&iomem_resource, start, size);
1758d9eb1417SDavid Hildenbrand 	if (ret) {
1759d9eb1417SDavid Hildenbrand 		resource_size_t endres = start + size - 1;
1760d9eb1417SDavid Hildenbrand 
1761d9eb1417SDavid Hildenbrand 		pr_warn("Unable to release resource <%pa-%pa> (%d)\n",
1762d9eb1417SDavid Hildenbrand 			&start, &endres, ret);
1763d9eb1417SDavid Hildenbrand 	}
1764d9eb1417SDavid Hildenbrand }
1765d9eb1417SDavid Hildenbrand 
1766eca499abSPavel Tatashin static int __ref try_remove_memory(int nid, u64 start, u64 size)
1767bbc76be6SWen Congyang {
1768eca499abSPavel Tatashin 	int rc = 0;
1769993c1aadSWen Congyang 
177027356f54SToshi Kani 	BUG_ON(check_hotplug_memory_range(start, size));
177127356f54SToshi Kani 
17726677e3eaSYasuaki Ishimatsu 	/*
1773242831ebSRafael J. Wysocki 	 * All memory blocks must be offlined before removing memory.  Check
1774eca499abSPavel Tatashin 	 * whether all memory blocks in question are offline and return error
1775242831ebSRafael J. Wysocki 	 * if this is not the case.
17766677e3eaSYasuaki Ishimatsu 	 */
1777fbcf73ceSDavid Hildenbrand 	rc = walk_memory_blocks(start, size, NULL, check_memblock_offlined_cb);
1778eca499abSPavel Tatashin 	if (rc)
1779b4223a51SJia He 		return rc;
17806677e3eaSYasuaki Ishimatsu 
178146c66c4bSYasuaki Ishimatsu 	/* remove memmap entry */
178246c66c4bSYasuaki Ishimatsu 	firmware_map_remove(start, start + size, "System RAM");
178346c66c4bSYasuaki Ishimatsu 
1784f1037ec0SDan Williams 	/*
1785f1037ec0SDan Williams 	 * Memory block device removal under the device_hotplug_lock is
1786f1037ec0SDan Williams 	 * a barrier against racing online attempts.
1787f1037ec0SDan Williams 	 */
17884c4b7f9bSDavid Hildenbrand 	remove_memory_block_devices(start, size);
17894c4b7f9bSDavid Hildenbrand 
1790f1037ec0SDan Williams 	mem_hotplug_begin();
1791f1037ec0SDan Williams 
17922c2a5af6SOscar Salvador 	arch_remove_memory(nid, start, size, NULL);
179352219aeaSDavid Hildenbrand 
179452219aeaSDavid Hildenbrand 	if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK)) {
179532d1fe8fSAnshuman Khandual 		memblock_free(start, size);
179632d1fe8fSAnshuman Khandual 		memblock_remove(start, size);
179752219aeaSDavid Hildenbrand 	}
179852219aeaSDavid Hildenbrand 
1799d9eb1417SDavid Hildenbrand 	__release_memory_resource(start, size);
180024d335caSWen Congyang 
180160a5a19eSTang Chen 	try_offline_node(nid);
180260a5a19eSTang Chen 
1803bfc8c901SVladimir Davydov 	mem_hotplug_done();
1804b4223a51SJia He 	return 0;
180571088785SBadari Pulavarty }
1806d15e5926SDavid Hildenbrand 
1807eca499abSPavel Tatashin /**
1808eca499abSPavel Tatashin  * remove_memory
1809eca499abSPavel Tatashin  * @nid: the node ID
1810eca499abSPavel Tatashin  * @start: physical address of the region to remove
1811eca499abSPavel Tatashin  * @size: size of the region to remove
1812eca499abSPavel Tatashin  *
1813eca499abSPavel Tatashin  * NOTE: The caller must call lock_device_hotplug() to serialize hotplug
1814eca499abSPavel Tatashin  * and online/offline operations before this call, as required by
1815eca499abSPavel Tatashin  * try_offline_node().
1816eca499abSPavel Tatashin  */
1817eca499abSPavel Tatashin void __remove_memory(int nid, u64 start, u64 size)
1818d15e5926SDavid Hildenbrand {
1819eca499abSPavel Tatashin 
1820eca499abSPavel Tatashin 	/*
182129a90db9SSouptick Joarder 	 * trigger BUG() if some memory is not offlined prior to calling this
1822eca499abSPavel Tatashin 	 * function
1823eca499abSPavel Tatashin 	 */
1824eca499abSPavel Tatashin 	if (try_remove_memory(nid, start, size))
1825eca499abSPavel Tatashin 		BUG();
1826eca499abSPavel Tatashin }
1827eca499abSPavel Tatashin 
1828eca499abSPavel Tatashin /*
1829eca499abSPavel Tatashin  * Remove memory if every memory block is offline, otherwise return -EBUSY is
1830eca499abSPavel Tatashin  * some memory is not offline
1831eca499abSPavel Tatashin  */
1832eca499abSPavel Tatashin int remove_memory(int nid, u64 start, u64 size)
1833eca499abSPavel Tatashin {
1834eca499abSPavel Tatashin 	int rc;
1835eca499abSPavel Tatashin 
1836d15e5926SDavid Hildenbrand 	lock_device_hotplug();
1837eca499abSPavel Tatashin 	rc  = try_remove_memory(nid, start, size);
1838d15e5926SDavid Hildenbrand 	unlock_device_hotplug();
1839eca499abSPavel Tatashin 
1840eca499abSPavel Tatashin 	return rc;
1841d15e5926SDavid Hildenbrand }
184271088785SBadari Pulavarty EXPORT_SYMBOL_GPL(remove_memory);
184308b3acd7SDavid Hildenbrand 
184408b3acd7SDavid Hildenbrand /*
184508b3acd7SDavid Hildenbrand  * Try to offline and remove a memory block. Might take a long time to
184608b3acd7SDavid Hildenbrand  * finish in case memory is still in use. Primarily useful for memory devices
184708b3acd7SDavid Hildenbrand  * that logically unplugged all memory (so it's no longer in use) and want to
184808b3acd7SDavid Hildenbrand  * offline + remove the memory block.
184908b3acd7SDavid Hildenbrand  */
185008b3acd7SDavid Hildenbrand int offline_and_remove_memory(int nid, u64 start, u64 size)
185108b3acd7SDavid Hildenbrand {
185208b3acd7SDavid Hildenbrand 	struct memory_block *mem;
185308b3acd7SDavid Hildenbrand 	int rc = -EINVAL;
185408b3acd7SDavid Hildenbrand 
185508b3acd7SDavid Hildenbrand 	if (!IS_ALIGNED(start, memory_block_size_bytes()) ||
185608b3acd7SDavid Hildenbrand 	    size != memory_block_size_bytes())
185708b3acd7SDavid Hildenbrand 		return rc;
185808b3acd7SDavid Hildenbrand 
185908b3acd7SDavid Hildenbrand 	lock_device_hotplug();
186008b3acd7SDavid Hildenbrand 	mem = find_memory_block(__pfn_to_section(PFN_DOWN(start)));
186108b3acd7SDavid Hildenbrand 	if (mem)
186208b3acd7SDavid Hildenbrand 		rc = device_offline(&mem->dev);
186308b3acd7SDavid Hildenbrand 	/* Ignore if the device is already offline. */
186408b3acd7SDavid Hildenbrand 	if (rc > 0)
186508b3acd7SDavid Hildenbrand 		rc = 0;
186608b3acd7SDavid Hildenbrand 
186708b3acd7SDavid Hildenbrand 	/*
186808b3acd7SDavid Hildenbrand 	 * In case we succeeded to offline the memory block, remove it.
186908b3acd7SDavid Hildenbrand 	 * This cannot fail as it cannot get onlined in the meantime.
187008b3acd7SDavid Hildenbrand 	 */
187108b3acd7SDavid Hildenbrand 	if (!rc) {
187208b3acd7SDavid Hildenbrand 		rc = try_remove_memory(nid, start, size);
187308b3acd7SDavid Hildenbrand 		WARN_ON_ONCE(rc);
187408b3acd7SDavid Hildenbrand 	}
187508b3acd7SDavid Hildenbrand 	unlock_device_hotplug();
187608b3acd7SDavid Hildenbrand 
187708b3acd7SDavid Hildenbrand 	return rc;
187808b3acd7SDavid Hildenbrand }
187908b3acd7SDavid Hildenbrand EXPORT_SYMBOL_GPL(offline_and_remove_memory);
1880aba6efc4SRafael J. Wysocki #endif /* CONFIG_MEMORY_HOTREMOVE */
1881