GNU Linux-libre 5.4.257-gnu1
[releases.git] / mm / memblock.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Procedures for maintaining information about logical memory blocks.
4  *
5  * Peter Bergner, IBM Corp.     June 2001.
6  * Copyright (C) 2001 Peter Bergner.
7  */
8
9 #include <linux/kernel.h>
10 #include <linux/slab.h>
11 #include <linux/init.h>
12 #include <linux/bitops.h>
13 #include <linux/poison.h>
14 #include <linux/pfn.h>
15 #include <linux/debugfs.h>
16 #include <linux/kmemleak.h>
17 #include <linux/seq_file.h>
18 #include <linux/memblock.h>
19
20 #include <asm/sections.h>
21 #include <linux/io.h>
22
23 #include "internal.h"
24
25 #define INIT_MEMBLOCK_REGIONS                   128
26 #define INIT_PHYSMEM_REGIONS                    4
27
28 #ifndef INIT_MEMBLOCK_RESERVED_REGIONS
29 # define INIT_MEMBLOCK_RESERVED_REGIONS         INIT_MEMBLOCK_REGIONS
30 #endif
31
32 /**
33  * DOC: memblock overview
34  *
35  * Memblock is a method of managing memory regions during the early
36  * boot period when the usual kernel memory allocators are not up and
37  * running.
38  *
39  * Memblock views the system memory as collections of contiguous
40  * regions. There are several types of these collections:
41  *
42  * * ``memory`` - describes the physical memory available to the
43  *   kernel; this may differ from the actual physical memory installed
44  *   in the system, for instance when the memory is restricted with
45  *   ``mem=`` command line parameter
46  * * ``reserved`` - describes the regions that were allocated
47  * * ``physmap`` - describes the actual physical memory regardless of
48  *   the possible restrictions; the ``physmap`` type is only available
49  *   on some architectures.
50  *
51  * Each region is represented by :c:type:`struct memblock_region` that
52  * defines the region extents, its attributes and NUMA node id on NUMA
53  * systems. Every memory type is described by the :c:type:`struct
54  * memblock_type` which contains an array of memory regions along with
55  * the allocator metadata. The memory types are nicely wrapped with
56  * :c:type:`struct memblock`. This structure is statically initialzed
57  * at build time. The region arrays for the "memory" and "reserved"
58  * types are initially sized to %INIT_MEMBLOCK_REGIONS and for the
59  * "physmap" type to %INIT_PHYSMEM_REGIONS.
60  * The :c:func:`memblock_allow_resize` enables automatic resizing of
61  * the region arrays during addition of new regions. This feature
62  * should be used with care so that memory allocated for the region
63  * array will not overlap with areas that should be reserved, for
64  * example initrd.
65  *
66  * The early architecture setup should tell memblock what the physical
67  * memory layout is by using :c:func:`memblock_add` or
68  * :c:func:`memblock_add_node` functions. The first function does not
69  * assign the region to a NUMA node and it is appropriate for UMA
70  * systems. Yet, it is possible to use it on NUMA systems as well and
71  * assign the region to a NUMA node later in the setup process using
72  * :c:func:`memblock_set_node`. The :c:func:`memblock_add_node`
73  * performs such an assignment directly.
74  *
75  * Once memblock is setup the memory can be allocated using one of the
76  * API variants:
77  *
78  * * :c:func:`memblock_phys_alloc*` - these functions return the
79  *   **physical** address of the allocated memory
80  * * :c:func:`memblock_alloc*` - these functions return the **virtual**
81  *   address of the allocated memory.
82  *
83  * Note, that both API variants use implict assumptions about allowed
84  * memory ranges and the fallback methods. Consult the documentation
85  * of :c:func:`memblock_alloc_internal` and
86  * :c:func:`memblock_alloc_range_nid` functions for more elaboarte
87  * description.
88  *
89  * As the system boot progresses, the architecture specific
90  * :c:func:`mem_init` function frees all the memory to the buddy page
91  * allocator.
92  *
93  * Unless an architecure enables %CONFIG_ARCH_KEEP_MEMBLOCK, the
94  * memblock data structures will be discarded after the system
95  * initialization compltes.
96  */
97
98 #ifndef CONFIG_NEED_MULTIPLE_NODES
99 struct pglist_data __refdata contig_page_data;
100 EXPORT_SYMBOL(contig_page_data);
101 #endif
102
103 unsigned long max_low_pfn;
104 unsigned long min_low_pfn;
105 unsigned long max_pfn;
106 unsigned long long max_possible_pfn;
107
108 static struct memblock_region memblock_memory_init_regions[INIT_MEMBLOCK_REGIONS] __initdata_memblock;
109 static struct memblock_region memblock_reserved_init_regions[INIT_MEMBLOCK_RESERVED_REGIONS] __initdata_memblock;
110 #ifdef CONFIG_HAVE_MEMBLOCK_PHYS_MAP
111 static struct memblock_region memblock_physmem_init_regions[INIT_PHYSMEM_REGIONS] __initdata_memblock;
112 #endif
113
114 struct memblock memblock __initdata_memblock = {
115         .memory.regions         = memblock_memory_init_regions,
116         .memory.cnt             = 1,    /* empty dummy entry */
117         .memory.max             = INIT_MEMBLOCK_REGIONS,
118         .memory.name            = "memory",
119
120         .reserved.regions       = memblock_reserved_init_regions,
121         .reserved.cnt           = 1,    /* empty dummy entry */
122         .reserved.max           = INIT_MEMBLOCK_RESERVED_REGIONS,
123         .reserved.name          = "reserved",
124
125 #ifdef CONFIG_HAVE_MEMBLOCK_PHYS_MAP
126         .physmem.regions        = memblock_physmem_init_regions,
127         .physmem.cnt            = 1,    /* empty dummy entry */
128         .physmem.max            = INIT_PHYSMEM_REGIONS,
129         .physmem.name           = "physmem",
130 #endif
131
132         .bottom_up              = false,
133         .current_limit          = MEMBLOCK_ALLOC_ANYWHERE,
134 };
135
136 int memblock_debug __initdata_memblock;
137 static bool system_has_some_mirror __initdata_memblock = false;
138 static int memblock_can_resize __initdata_memblock;
139 static int memblock_memory_in_slab __initdata_memblock = 0;
140 static int memblock_reserved_in_slab __initdata_memblock = 0;
141
142 static enum memblock_flags __init_memblock choose_memblock_flags(void)
143 {
144         return system_has_some_mirror ? MEMBLOCK_MIRROR : MEMBLOCK_NONE;
145 }
146
147 /* adjust *@size so that (@base + *@size) doesn't overflow, return new size */
148 static inline phys_addr_t memblock_cap_size(phys_addr_t base, phys_addr_t *size)
149 {
150         return *size = min(*size, PHYS_ADDR_MAX - base);
151 }
152
153 /*
154  * Address comparison utilities
155  */
156 static unsigned long __init_memblock memblock_addrs_overlap(phys_addr_t base1, phys_addr_t size1,
157                                        phys_addr_t base2, phys_addr_t size2)
158 {
159         return ((base1 < (base2 + size2)) && (base2 < (base1 + size1)));
160 }
161
162 bool __init_memblock memblock_overlaps_region(struct memblock_type *type,
163                                         phys_addr_t base, phys_addr_t size)
164 {
165         unsigned long i;
166
167         memblock_cap_size(base, &size);
168
169         for (i = 0; i < type->cnt; i++)
170                 if (memblock_addrs_overlap(base, size, type->regions[i].base,
171                                            type->regions[i].size))
172                         break;
173         return i < type->cnt;
174 }
175
176 /**
177  * __memblock_find_range_bottom_up - find free area utility in bottom-up
178  * @start: start of candidate range
179  * @end: end of candidate range, can be %MEMBLOCK_ALLOC_ANYWHERE or
180  *       %MEMBLOCK_ALLOC_ACCESSIBLE
181  * @size: size of free area to find
182  * @align: alignment of free area to find
183  * @nid: nid of the free area to find, %NUMA_NO_NODE for any node
184  * @flags: pick from blocks based on memory attributes
185  *
186  * Utility called from memblock_find_in_range_node(), find free area bottom-up.
187  *
188  * Return:
189  * Found address on success, 0 on failure.
190  */
191 static phys_addr_t __init_memblock
192 __memblock_find_range_bottom_up(phys_addr_t start, phys_addr_t end,
193                                 phys_addr_t size, phys_addr_t align, int nid,
194                                 enum memblock_flags flags)
195 {
196         phys_addr_t this_start, this_end, cand;
197         u64 i;
198
199         for_each_free_mem_range(i, nid, flags, &this_start, &this_end, NULL) {
200                 this_start = clamp(this_start, start, end);
201                 this_end = clamp(this_end, start, end);
202
203                 cand = round_up(this_start, align);
204                 if (cand < this_end && this_end - cand >= size)
205                         return cand;
206         }
207
208         return 0;
209 }
210
211 /**
212  * __memblock_find_range_top_down - find free area utility, in top-down
213  * @start: start of candidate range
214  * @end: end of candidate range, can be %MEMBLOCK_ALLOC_ANYWHERE or
215  *       %MEMBLOCK_ALLOC_ACCESSIBLE
216  * @size: size of free area to find
217  * @align: alignment of free area to find
218  * @nid: nid of the free area to find, %NUMA_NO_NODE for any node
219  * @flags: pick from blocks based on memory attributes
220  *
221  * Utility called from memblock_find_in_range_node(), find free area top-down.
222  *
223  * Return:
224  * Found address on success, 0 on failure.
225  */
226 static phys_addr_t __init_memblock
227 __memblock_find_range_top_down(phys_addr_t start, phys_addr_t end,
228                                phys_addr_t size, phys_addr_t align, int nid,
229                                enum memblock_flags flags)
230 {
231         phys_addr_t this_start, this_end, cand;
232         u64 i;
233
234         for_each_free_mem_range_reverse(i, nid, flags, &this_start, &this_end,
235                                         NULL) {
236                 this_start = clamp(this_start, start, end);
237                 this_end = clamp(this_end, start, end);
238
239                 if (this_end < size)
240                         continue;
241
242                 cand = round_down(this_end - size, align);
243                 if (cand >= this_start)
244                         return cand;
245         }
246
247         return 0;
248 }
249
250 /**
251  * memblock_find_in_range_node - find free area in given range and node
252  * @size: size of free area to find
253  * @align: alignment of free area to find
254  * @start: start of candidate range
255  * @end: end of candidate range, can be %MEMBLOCK_ALLOC_ANYWHERE or
256  *       %MEMBLOCK_ALLOC_ACCESSIBLE
257  * @nid: nid of the free area to find, %NUMA_NO_NODE for any node
258  * @flags: pick from blocks based on memory attributes
259  *
260  * Find @size free area aligned to @align in the specified range and node.
261  *
262  * Return:
263  * Found address on success, 0 on failure.
264  */
265 static phys_addr_t __init_memblock memblock_find_in_range_node(phys_addr_t size,
266                                         phys_addr_t align, phys_addr_t start,
267                                         phys_addr_t end, int nid,
268                                         enum memblock_flags flags)
269 {
270         /* pump up @end */
271         if (end == MEMBLOCK_ALLOC_ACCESSIBLE ||
272             end == MEMBLOCK_ALLOC_KASAN)
273                 end = memblock.current_limit;
274
275         /* avoid allocating the first page */
276         start = max_t(phys_addr_t, start, PAGE_SIZE);
277         end = max(start, end);
278
279         if (memblock_bottom_up())
280                 return __memblock_find_range_bottom_up(start, end, size, align,
281                                                        nid, flags);
282         else
283                 return __memblock_find_range_top_down(start, end, size, align,
284                                                       nid, flags);
285 }
286
287 /**
288  * memblock_find_in_range - find free area in given range
289  * @start: start of candidate range
290  * @end: end of candidate range, can be %MEMBLOCK_ALLOC_ANYWHERE or
291  *       %MEMBLOCK_ALLOC_ACCESSIBLE
292  * @size: size of free area to find
293  * @align: alignment of free area to find
294  *
295  * Find @size free area aligned to @align in the specified range.
296  *
297  * Return:
298  * Found address on success, 0 on failure.
299  */
300 phys_addr_t __init_memblock memblock_find_in_range(phys_addr_t start,
301                                         phys_addr_t end, phys_addr_t size,
302                                         phys_addr_t align)
303 {
304         phys_addr_t ret;
305         enum memblock_flags flags = choose_memblock_flags();
306
307 again:
308         ret = memblock_find_in_range_node(size, align, start, end,
309                                             NUMA_NO_NODE, flags);
310
311         if (!ret && (flags & MEMBLOCK_MIRROR)) {
312                 pr_warn("Could not allocate %pap bytes of mirrored memory\n",
313                         &size);
314                 flags &= ~MEMBLOCK_MIRROR;
315                 goto again;
316         }
317
318         return ret;
319 }
320
321 static void __init_memblock memblock_remove_region(struct memblock_type *type, unsigned long r)
322 {
323         type->total_size -= type->regions[r].size;
324         memmove(&type->regions[r], &type->regions[r + 1],
325                 (type->cnt - (r + 1)) * sizeof(type->regions[r]));
326         type->cnt--;
327
328         /* Special case for empty arrays */
329         if (type->cnt == 0) {
330                 WARN_ON(type->total_size != 0);
331                 type->cnt = 1;
332                 type->regions[0].base = 0;
333                 type->regions[0].size = 0;
334                 type->regions[0].flags = 0;
335                 memblock_set_region_node(&type->regions[0], MAX_NUMNODES);
336         }
337 }
338
339 #ifndef CONFIG_ARCH_KEEP_MEMBLOCK
340 /**
341  * memblock_discard - discard memory and reserved arrays if they were allocated
342  */
343 void __init memblock_discard(void)
344 {
345         phys_addr_t addr, size;
346
347         if (memblock.reserved.regions != memblock_reserved_init_regions) {
348                 addr = __pa(memblock.reserved.regions);
349                 size = PAGE_ALIGN(sizeof(struct memblock_region) *
350                                   memblock.reserved.max);
351                 if (memblock_reserved_in_slab)
352                         kfree(memblock.reserved.regions);
353                 else
354                         __memblock_free_late(addr, size);
355         }
356
357         if (memblock.memory.regions != memblock_memory_init_regions) {
358                 addr = __pa(memblock.memory.regions);
359                 size = PAGE_ALIGN(sizeof(struct memblock_region) *
360                                   memblock.memory.max);
361                 if (memblock_memory_in_slab)
362                         kfree(memblock.memory.regions);
363                 else
364                         __memblock_free_late(addr, size);
365         }
366 }
367 #endif
368
369 /**
370  * memblock_double_array - double the size of the memblock regions array
371  * @type: memblock type of the regions array being doubled
372  * @new_area_start: starting address of memory range to avoid overlap with
373  * @new_area_size: size of memory range to avoid overlap with
374  *
375  * Double the size of the @type regions array. If memblock is being used to
376  * allocate memory for a new reserved regions array and there is a previously
377  * allocated memory range [@new_area_start, @new_area_start + @new_area_size]
378  * waiting to be reserved, ensure the memory used by the new array does
379  * not overlap.
380  *
381  * Return:
382  * 0 on success, -1 on failure.
383  */
384 static int __init_memblock memblock_double_array(struct memblock_type *type,
385                                                 phys_addr_t new_area_start,
386                                                 phys_addr_t new_area_size)
387 {
388         struct memblock_region *new_array, *old_array;
389         phys_addr_t old_alloc_size, new_alloc_size;
390         phys_addr_t old_size, new_size, addr, new_end;
391         int use_slab = slab_is_available();
392         int *in_slab;
393
394         /* We don't allow resizing until we know about the reserved regions
395          * of memory that aren't suitable for allocation
396          */
397         if (!memblock_can_resize)
398                 return -1;
399
400         /* Calculate new doubled size */
401         old_size = type->max * sizeof(struct memblock_region);
402         new_size = old_size << 1;
403         /*
404          * We need to allocated new one align to PAGE_SIZE,
405          *   so we can free them completely later.
406          */
407         old_alloc_size = PAGE_ALIGN(old_size);
408         new_alloc_size = PAGE_ALIGN(new_size);
409
410         /* Retrieve the slab flag */
411         if (type == &memblock.memory)
412                 in_slab = &memblock_memory_in_slab;
413         else
414                 in_slab = &memblock_reserved_in_slab;
415
416         /* Try to find some space for it */
417         if (use_slab) {
418                 new_array = kmalloc(new_size, GFP_KERNEL);
419                 addr = new_array ? __pa(new_array) : 0;
420         } else {
421                 /* only exclude range when trying to double reserved.regions */
422                 if (type != &memblock.reserved)
423                         new_area_start = new_area_size = 0;
424
425                 addr = memblock_find_in_range(new_area_start + new_area_size,
426                                                 memblock.current_limit,
427                                                 new_alloc_size, PAGE_SIZE);
428                 if (!addr && new_area_size)
429                         addr = memblock_find_in_range(0,
430                                 min(new_area_start, memblock.current_limit),
431                                 new_alloc_size, PAGE_SIZE);
432
433                 new_array = addr ? __va(addr) : NULL;
434         }
435         if (!addr) {
436                 pr_err("memblock: Failed to double %s array from %ld to %ld entries !\n",
437                        type->name, type->max, type->max * 2);
438                 return -1;
439         }
440
441         new_end = addr + new_size - 1;
442         memblock_dbg("memblock: %s is doubled to %ld at [%pa-%pa]",
443                         type->name, type->max * 2, &addr, &new_end);
444
445         /*
446          * Found space, we now need to move the array over before we add the
447          * reserved region since it may be our reserved array itself that is
448          * full.
449          */
450         memcpy(new_array, type->regions, old_size);
451         memset(new_array + type->max, 0, old_size);
452         old_array = type->regions;
453         type->regions = new_array;
454         type->max <<= 1;
455
456         /* Free old array. We needn't free it if the array is the static one */
457         if (*in_slab)
458                 kfree(old_array);
459         else if (old_array != memblock_memory_init_regions &&
460                  old_array != memblock_reserved_init_regions)
461                 memblock_free(__pa(old_array), old_alloc_size);
462
463         /*
464          * Reserve the new array if that comes from the memblock.  Otherwise, we
465          * needn't do it
466          */
467         if (!use_slab)
468                 BUG_ON(memblock_reserve(addr, new_alloc_size));
469
470         /* Update slab flag */
471         *in_slab = use_slab;
472
473         return 0;
474 }
475
476 /**
477  * memblock_merge_regions - merge neighboring compatible regions
478  * @type: memblock type to scan
479  *
480  * Scan @type and merge neighboring compatible regions.
481  */
482 static void __init_memblock memblock_merge_regions(struct memblock_type *type)
483 {
484         int i = 0;
485
486         /* cnt never goes below 1 */
487         while (i < type->cnt - 1) {
488                 struct memblock_region *this = &type->regions[i];
489                 struct memblock_region *next = &type->regions[i + 1];
490
491                 if (this->base + this->size != next->base ||
492                     memblock_get_region_node(this) !=
493                     memblock_get_region_node(next) ||
494                     this->flags != next->flags) {
495                         BUG_ON(this->base + this->size > next->base);
496                         i++;
497                         continue;
498                 }
499
500                 this->size += next->size;
501                 /* move forward from next + 1, index of which is i + 2 */
502                 memmove(next, next + 1, (type->cnt - (i + 2)) * sizeof(*next));
503                 type->cnt--;
504         }
505 }
506
507 /**
508  * memblock_insert_region - insert new memblock region
509  * @type:       memblock type to insert into
510  * @idx:        index for the insertion point
511  * @base:       base address of the new region
512  * @size:       size of the new region
513  * @nid:        node id of the new region
514  * @flags:      flags of the new region
515  *
516  * Insert new memblock region [@base, @base + @size) into @type at @idx.
517  * @type must already have extra room to accommodate the new region.
518  */
519 static void __init_memblock memblock_insert_region(struct memblock_type *type,
520                                                    int idx, phys_addr_t base,
521                                                    phys_addr_t size,
522                                                    int nid,
523                                                    enum memblock_flags flags)
524 {
525         struct memblock_region *rgn = &type->regions[idx];
526
527         BUG_ON(type->cnt >= type->max);
528         memmove(rgn + 1, rgn, (type->cnt - idx) * sizeof(*rgn));
529         rgn->base = base;
530         rgn->size = size;
531         rgn->flags = flags;
532         memblock_set_region_node(rgn, nid);
533         type->cnt++;
534         type->total_size += size;
535 }
536
537 /**
538  * memblock_add_range - add new memblock region
539  * @type: memblock type to add new region into
540  * @base: base address of the new region
541  * @size: size of the new region
542  * @nid: nid of the new region
543  * @flags: flags of the new region
544  *
545  * Add new memblock region [@base, @base + @size) into @type.  The new region
546  * is allowed to overlap with existing ones - overlaps don't affect already
547  * existing regions.  @type is guaranteed to be minimal (all neighbouring
548  * compatible regions are merged) after the addition.
549  *
550  * Return:
551  * 0 on success, -errno on failure.
552  */
553 int __init_memblock memblock_add_range(struct memblock_type *type,
554                                 phys_addr_t base, phys_addr_t size,
555                                 int nid, enum memblock_flags flags)
556 {
557         bool insert = false;
558         phys_addr_t obase = base;
559         phys_addr_t end = base + memblock_cap_size(base, &size);
560         int idx, nr_new;
561         struct memblock_region *rgn;
562
563         if (!size)
564                 return 0;
565
566         /* special case for empty array */
567         if (type->regions[0].size == 0) {
568                 WARN_ON(type->cnt != 1 || type->total_size);
569                 type->regions[0].base = base;
570                 type->regions[0].size = size;
571                 type->regions[0].flags = flags;
572                 memblock_set_region_node(&type->regions[0], nid);
573                 type->total_size = size;
574                 return 0;
575         }
576 repeat:
577         /*
578          * The following is executed twice.  Once with %false @insert and
579          * then with %true.  The first counts the number of regions needed
580          * to accommodate the new area.  The second actually inserts them.
581          */
582         base = obase;
583         nr_new = 0;
584
585         for_each_memblock_type(idx, type, rgn) {
586                 phys_addr_t rbase = rgn->base;
587                 phys_addr_t rend = rbase + rgn->size;
588
589                 if (rbase >= end)
590                         break;
591                 if (rend <= base)
592                         continue;
593                 /*
594                  * @rgn overlaps.  If it separates the lower part of new
595                  * area, insert that portion.
596                  */
597                 if (rbase > base) {
598 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
599                         WARN_ON(nid != memblock_get_region_node(rgn));
600 #endif
601                         WARN_ON(flags != rgn->flags);
602                         nr_new++;
603                         if (insert)
604                                 memblock_insert_region(type, idx++, base,
605                                                        rbase - base, nid,
606                                                        flags);
607                 }
608                 /* area below @rend is dealt with, forget about it */
609                 base = min(rend, end);
610         }
611
612         /* insert the remaining portion */
613         if (base < end) {
614                 nr_new++;
615                 if (insert)
616                         memblock_insert_region(type, idx, base, end - base,
617                                                nid, flags);
618         }
619
620         if (!nr_new)
621                 return 0;
622
623         /*
624          * If this was the first round, resize array and repeat for actual
625          * insertions; otherwise, merge and return.
626          */
627         if (!insert) {
628                 while (type->cnt + nr_new > type->max)
629                         if (memblock_double_array(type, obase, size) < 0)
630                                 return -ENOMEM;
631                 insert = true;
632                 goto repeat;
633         } else {
634                 memblock_merge_regions(type);
635                 return 0;
636         }
637 }
638
639 /**
640  * memblock_add_node - add new memblock region within a NUMA node
641  * @base: base address of the new region
642  * @size: size of the new region
643  * @nid: nid of the new region
644  *
645  * Add new memblock region [@base, @base + @size) to the "memory"
646  * type. See memblock_add_range() description for mode details
647  *
648  * Return:
649  * 0 on success, -errno on failure.
650  */
651 int __init_memblock memblock_add_node(phys_addr_t base, phys_addr_t size,
652                                        int nid)
653 {
654         return memblock_add_range(&memblock.memory, base, size, nid, 0);
655 }
656
657 /**
658  * memblock_add - add new memblock region
659  * @base: base address of the new region
660  * @size: size of the new region
661  *
662  * Add new memblock region [@base, @base + @size) to the "memory"
663  * type. See memblock_add_range() description for mode details
664  *
665  * Return:
666  * 0 on success, -errno on failure.
667  */
668 int __init_memblock memblock_add(phys_addr_t base, phys_addr_t size)
669 {
670         phys_addr_t end = base + size - 1;
671
672         memblock_dbg("memblock_add: [%pa-%pa] %pS\n",
673                      &base, &end, (void *)_RET_IP_);
674
675         return memblock_add_range(&memblock.memory, base, size, MAX_NUMNODES, 0);
676 }
677
678 /**
679  * memblock_isolate_range - isolate given range into disjoint memblocks
680  * @type: memblock type to isolate range for
681  * @base: base of range to isolate
682  * @size: size of range to isolate
683  * @start_rgn: out parameter for the start of isolated region
684  * @end_rgn: out parameter for the end of isolated region
685  *
686  * Walk @type and ensure that regions don't cross the boundaries defined by
687  * [@base, @base + @size).  Crossing regions are split at the boundaries,
688  * which may create at most two more regions.  The index of the first
689  * region inside the range is returned in *@start_rgn and end in *@end_rgn.
690  *
691  * Return:
692  * 0 on success, -errno on failure.
693  */
694 static int __init_memblock memblock_isolate_range(struct memblock_type *type,
695                                         phys_addr_t base, phys_addr_t size,
696                                         int *start_rgn, int *end_rgn)
697 {
698         phys_addr_t end = base + memblock_cap_size(base, &size);
699         int idx;
700         struct memblock_region *rgn;
701
702         *start_rgn = *end_rgn = 0;
703
704         if (!size)
705                 return 0;
706
707         /* we'll create at most two more regions */
708         while (type->cnt + 2 > type->max)
709                 if (memblock_double_array(type, base, size) < 0)
710                         return -ENOMEM;
711
712         for_each_memblock_type(idx, type, rgn) {
713                 phys_addr_t rbase = rgn->base;
714                 phys_addr_t rend = rbase + rgn->size;
715
716                 if (rbase >= end)
717                         break;
718                 if (rend <= base)
719                         continue;
720
721                 if (rbase < base) {
722                         /*
723                          * @rgn intersects from below.  Split and continue
724                          * to process the next region - the new top half.
725                          */
726                         rgn->base = base;
727                         rgn->size -= base - rbase;
728                         type->total_size -= base - rbase;
729                         memblock_insert_region(type, idx, rbase, base - rbase,
730                                                memblock_get_region_node(rgn),
731                                                rgn->flags);
732                 } else if (rend > end) {
733                         /*
734                          * @rgn intersects from above.  Split and redo the
735                          * current region - the new bottom half.
736                          */
737                         rgn->base = end;
738                         rgn->size -= end - rbase;
739                         type->total_size -= end - rbase;
740                         memblock_insert_region(type, idx--, rbase, end - rbase,
741                                                memblock_get_region_node(rgn),
742                                                rgn->flags);
743                 } else {
744                         /* @rgn is fully contained, record it */
745                         if (!*end_rgn)
746                                 *start_rgn = idx;
747                         *end_rgn = idx + 1;
748                 }
749         }
750
751         return 0;
752 }
753
754 static int __init_memblock memblock_remove_range(struct memblock_type *type,
755                                           phys_addr_t base, phys_addr_t size)
756 {
757         int start_rgn, end_rgn;
758         int i, ret;
759
760         ret = memblock_isolate_range(type, base, size, &start_rgn, &end_rgn);
761         if (ret)
762                 return ret;
763
764         for (i = end_rgn - 1; i >= start_rgn; i--)
765                 memblock_remove_region(type, i);
766         return 0;
767 }
768
769 int __init_memblock memblock_remove(phys_addr_t base, phys_addr_t size)
770 {
771         phys_addr_t end = base + size - 1;
772
773         memblock_dbg("memblock_remove: [%pa-%pa] %pS\n",
774                      &base, &end, (void *)_RET_IP_);
775
776         return memblock_remove_range(&memblock.memory, base, size);
777 }
778
779 /**
780  * memblock_free - free boot memory block
781  * @base: phys starting address of the  boot memory block
782  * @size: size of the boot memory block in bytes
783  *
784  * Free boot memory block previously allocated by memblock_alloc_xx() API.
785  * The freeing memory will not be released to the buddy allocator.
786  */
787 int __init_memblock memblock_free(phys_addr_t base, phys_addr_t size)
788 {
789         phys_addr_t end = base + size - 1;
790
791         memblock_dbg("   memblock_free: [%pa-%pa] %pS\n",
792                      &base, &end, (void *)_RET_IP_);
793
794         kmemleak_free_part_phys(base, size);
795         return memblock_remove_range(&memblock.reserved, base, size);
796 }
797
798 int __init_memblock memblock_reserve(phys_addr_t base, phys_addr_t size)
799 {
800         phys_addr_t end = base + size - 1;
801
802         memblock_dbg("memblock_reserve: [%pa-%pa] %pS\n",
803                      &base, &end, (void *)_RET_IP_);
804
805         return memblock_add_range(&memblock.reserved, base, size, MAX_NUMNODES, 0);
806 }
807
808 /**
809  * memblock_setclr_flag - set or clear flag for a memory region
810  * @base: base address of the region
811  * @size: size of the region
812  * @set: set or clear the flag
813  * @flag: the flag to udpate
814  *
815  * This function isolates region [@base, @base + @size), and sets/clears flag
816  *
817  * Return: 0 on success, -errno on failure.
818  */
819 static int __init_memblock memblock_setclr_flag(phys_addr_t base,
820                                 phys_addr_t size, int set, int flag)
821 {
822         struct memblock_type *type = &memblock.memory;
823         int i, ret, start_rgn, end_rgn;
824
825         ret = memblock_isolate_range(type, base, size, &start_rgn, &end_rgn);
826         if (ret)
827                 return ret;
828
829         for (i = start_rgn; i < end_rgn; i++) {
830                 struct memblock_region *r = &type->regions[i];
831
832                 if (set)
833                         r->flags |= flag;
834                 else
835                         r->flags &= ~flag;
836         }
837
838         memblock_merge_regions(type);
839         return 0;
840 }
841
842 /**
843  * memblock_mark_hotplug - Mark hotpluggable memory with flag MEMBLOCK_HOTPLUG.
844  * @base: the base phys addr of the region
845  * @size: the size of the region
846  *
847  * Return: 0 on success, -errno on failure.
848  */
849 int __init_memblock memblock_mark_hotplug(phys_addr_t base, phys_addr_t size)
850 {
851         return memblock_setclr_flag(base, size, 1, MEMBLOCK_HOTPLUG);
852 }
853
854 /**
855  * memblock_clear_hotplug - Clear flag MEMBLOCK_HOTPLUG for a specified region.
856  * @base: the base phys addr of the region
857  * @size: the size of the region
858  *
859  * Return: 0 on success, -errno on failure.
860  */
861 int __init_memblock memblock_clear_hotplug(phys_addr_t base, phys_addr_t size)
862 {
863         return memblock_setclr_flag(base, size, 0, MEMBLOCK_HOTPLUG);
864 }
865
866 /**
867  * memblock_mark_mirror - Mark mirrored memory with flag MEMBLOCK_MIRROR.
868  * @base: the base phys addr of the region
869  * @size: the size of the region
870  *
871  * Return: 0 on success, -errno on failure.
872  */
873 int __init_memblock memblock_mark_mirror(phys_addr_t base, phys_addr_t size)
874 {
875         system_has_some_mirror = true;
876
877         return memblock_setclr_flag(base, size, 1, MEMBLOCK_MIRROR);
878 }
879
880 /**
881  * memblock_mark_nomap - Mark a memory region with flag MEMBLOCK_NOMAP.
882  * @base: the base phys addr of the region
883  * @size: the size of the region
884  *
885  * Return: 0 on success, -errno on failure.
886  */
887 int __init_memblock memblock_mark_nomap(phys_addr_t base, phys_addr_t size)
888 {
889         return memblock_setclr_flag(base, size, 1, MEMBLOCK_NOMAP);
890 }
891
892 /**
893  * memblock_clear_nomap - Clear flag MEMBLOCK_NOMAP for a specified region.
894  * @base: the base phys addr of the region
895  * @size: the size of the region
896  *
897  * Return: 0 on success, -errno on failure.
898  */
899 int __init_memblock memblock_clear_nomap(phys_addr_t base, phys_addr_t size)
900 {
901         return memblock_setclr_flag(base, size, 0, MEMBLOCK_NOMAP);
902 }
903
904 /**
905  * __next_reserved_mem_region - next function for for_each_reserved_region()
906  * @idx: pointer to u64 loop variable
907  * @out_start: ptr to phys_addr_t for start address of the region, can be %NULL
908  * @out_end: ptr to phys_addr_t for end address of the region, can be %NULL
909  *
910  * Iterate over all reserved memory regions.
911  */
912 void __init_memblock __next_reserved_mem_region(u64 *idx,
913                                            phys_addr_t *out_start,
914                                            phys_addr_t *out_end)
915 {
916         struct memblock_type *type = &memblock.reserved;
917
918         if (*idx < type->cnt) {
919                 struct memblock_region *r = &type->regions[*idx];
920                 phys_addr_t base = r->base;
921                 phys_addr_t size = r->size;
922
923                 if (out_start)
924                         *out_start = base;
925                 if (out_end)
926                         *out_end = base + size - 1;
927
928                 *idx += 1;
929                 return;
930         }
931
932         /* signal end of iteration */
933         *idx = ULLONG_MAX;
934 }
935
936 static bool should_skip_region(struct memblock_region *m, int nid, int flags)
937 {
938         int m_nid = memblock_get_region_node(m);
939
940         /* only memory regions are associated with nodes, check it */
941         if (nid != NUMA_NO_NODE && nid != m_nid)
942                 return true;
943
944         /* skip hotpluggable memory regions if needed */
945         if (movable_node_is_enabled() && memblock_is_hotpluggable(m))
946                 return true;
947
948         /* if we want mirror memory skip non-mirror memory regions */
949         if ((flags & MEMBLOCK_MIRROR) && !memblock_is_mirror(m))
950                 return true;
951
952         /* skip nomap memory unless we were asked for it explicitly */
953         if (!(flags & MEMBLOCK_NOMAP) && memblock_is_nomap(m))
954                 return true;
955
956         return false;
957 }
958
959 /**
960  * __next_mem_range - next function for for_each_free_mem_range() etc.
961  * @idx: pointer to u64 loop variable
962  * @nid: node selector, %NUMA_NO_NODE for all nodes
963  * @flags: pick from blocks based on memory attributes
964  * @type_a: pointer to memblock_type from where the range is taken
965  * @type_b: pointer to memblock_type which excludes memory from being taken
966  * @out_start: ptr to phys_addr_t for start address of the range, can be %NULL
967  * @out_end: ptr to phys_addr_t for end address of the range, can be %NULL
968  * @out_nid: ptr to int for nid of the range, can be %NULL
969  *
970  * Find the first area from *@idx which matches @nid, fill the out
971  * parameters, and update *@idx for the next iteration.  The lower 32bit of
972  * *@idx contains index into type_a and the upper 32bit indexes the
973  * areas before each region in type_b.  For example, if type_b regions
974  * look like the following,
975  *
976  *      0:[0-16), 1:[32-48), 2:[128-130)
977  *
978  * The upper 32bit indexes the following regions.
979  *
980  *      0:[0-0), 1:[16-32), 2:[48-128), 3:[130-MAX)
981  *
982  * As both region arrays are sorted, the function advances the two indices
983  * in lockstep and returns each intersection.
984  */
985 void __init_memblock __next_mem_range(u64 *idx, int nid,
986                                       enum memblock_flags flags,
987                                       struct memblock_type *type_a,
988                                       struct memblock_type *type_b,
989                                       phys_addr_t *out_start,
990                                       phys_addr_t *out_end, int *out_nid)
991 {
992         int idx_a = *idx & 0xffffffff;
993         int idx_b = *idx >> 32;
994
995         if (WARN_ONCE(nid == MAX_NUMNODES,
996         "Usage of MAX_NUMNODES is deprecated. Use NUMA_NO_NODE instead\n"))
997                 nid = NUMA_NO_NODE;
998
999         for (; idx_a < type_a->cnt; idx_a++) {
1000                 struct memblock_region *m = &type_a->regions[idx_a];
1001
1002                 phys_addr_t m_start = m->base;
1003                 phys_addr_t m_end = m->base + m->size;
1004                 int         m_nid = memblock_get_region_node(m);
1005
1006                 if (should_skip_region(m, nid, flags))
1007                         continue;
1008
1009                 if (!type_b) {
1010                         if (out_start)
1011                                 *out_start = m_start;
1012                         if (out_end)
1013                                 *out_end = m_end;
1014                         if (out_nid)
1015                                 *out_nid = m_nid;
1016                         idx_a++;
1017                         *idx = (u32)idx_a | (u64)idx_b << 32;
1018                         return;
1019                 }
1020
1021                 /* scan areas before each reservation */
1022                 for (; idx_b < type_b->cnt + 1; idx_b++) {
1023                         struct memblock_region *r;
1024                         phys_addr_t r_start;
1025                         phys_addr_t r_end;
1026
1027                         r = &type_b->regions[idx_b];
1028                         r_start = idx_b ? r[-1].base + r[-1].size : 0;
1029                         r_end = idx_b < type_b->cnt ?
1030                                 r->base : PHYS_ADDR_MAX;
1031
1032                         /*
1033                          * if idx_b advanced past idx_a,
1034                          * break out to advance idx_a
1035                          */
1036                         if (r_start >= m_end)
1037                                 break;
1038                         /* if the two regions intersect, we're done */
1039                         if (m_start < r_end) {
1040                                 if (out_start)
1041                                         *out_start =
1042                                                 max(m_start, r_start);
1043                                 if (out_end)
1044                                         *out_end = min(m_end, r_end);
1045                                 if (out_nid)
1046                                         *out_nid = m_nid;
1047                                 /*
1048                                  * The region which ends first is
1049                                  * advanced for the next iteration.
1050                                  */
1051                                 if (m_end <= r_end)
1052                                         idx_a++;
1053                                 else
1054                                         idx_b++;
1055                                 *idx = (u32)idx_a | (u64)idx_b << 32;
1056                                 return;
1057                         }
1058                 }
1059         }
1060
1061         /* signal end of iteration */
1062         *idx = ULLONG_MAX;
1063 }
1064
1065 /**
1066  * __next_mem_range_rev - generic next function for for_each_*_range_rev()
1067  *
1068  * @idx: pointer to u64 loop variable
1069  * @nid: node selector, %NUMA_NO_NODE for all nodes
1070  * @flags: pick from blocks based on memory attributes
1071  * @type_a: pointer to memblock_type from where the range is taken
1072  * @type_b: pointer to memblock_type which excludes memory from being taken
1073  * @out_start: ptr to phys_addr_t for start address of the range, can be %NULL
1074  * @out_end: ptr to phys_addr_t for end address of the range, can be %NULL
1075  * @out_nid: ptr to int for nid of the range, can be %NULL
1076  *
1077  * Finds the next range from type_a which is not marked as unsuitable
1078  * in type_b.
1079  *
1080  * Reverse of __next_mem_range().
1081  */
1082 void __init_memblock __next_mem_range_rev(u64 *idx, int nid,
1083                                           enum memblock_flags flags,
1084                                           struct memblock_type *type_a,
1085                                           struct memblock_type *type_b,
1086                                           phys_addr_t *out_start,
1087                                           phys_addr_t *out_end, int *out_nid)
1088 {
1089         int idx_a = *idx & 0xffffffff;
1090         int idx_b = *idx >> 32;
1091
1092         if (WARN_ONCE(nid == MAX_NUMNODES, "Usage of MAX_NUMNODES is deprecated. Use NUMA_NO_NODE instead\n"))
1093                 nid = NUMA_NO_NODE;
1094
1095         if (*idx == (u64)ULLONG_MAX) {
1096                 idx_a = type_a->cnt - 1;
1097                 if (type_b != NULL)
1098                         idx_b = type_b->cnt;
1099                 else
1100                         idx_b = 0;
1101         }
1102
1103         for (; idx_a >= 0; idx_a--) {
1104                 struct memblock_region *m = &type_a->regions[idx_a];
1105
1106                 phys_addr_t m_start = m->base;
1107                 phys_addr_t m_end = m->base + m->size;
1108                 int m_nid = memblock_get_region_node(m);
1109
1110                 if (should_skip_region(m, nid, flags))
1111                         continue;
1112
1113                 if (!type_b) {
1114                         if (out_start)
1115                                 *out_start = m_start;
1116                         if (out_end)
1117                                 *out_end = m_end;
1118                         if (out_nid)
1119                                 *out_nid = m_nid;
1120                         idx_a--;
1121                         *idx = (u32)idx_a | (u64)idx_b << 32;
1122                         return;
1123                 }
1124
1125                 /* scan areas before each reservation */
1126                 for (; idx_b >= 0; idx_b--) {
1127                         struct memblock_region *r;
1128                         phys_addr_t r_start;
1129                         phys_addr_t r_end;
1130
1131                         r = &type_b->regions[idx_b];
1132                         r_start = idx_b ? r[-1].base + r[-1].size : 0;
1133                         r_end = idx_b < type_b->cnt ?
1134                                 r->base : PHYS_ADDR_MAX;
1135                         /*
1136                          * if idx_b advanced past idx_a,
1137                          * break out to advance idx_a
1138                          */
1139
1140                         if (r_end <= m_start)
1141                                 break;
1142                         /* if the two regions intersect, we're done */
1143                         if (m_end > r_start) {
1144                                 if (out_start)
1145                                         *out_start = max(m_start, r_start);
1146                                 if (out_end)
1147                                         *out_end = min(m_end, r_end);
1148                                 if (out_nid)
1149                                         *out_nid = m_nid;
1150                                 if (m_start >= r_start)
1151                                         idx_a--;
1152                                 else
1153                                         idx_b--;
1154                                 *idx = (u32)idx_a | (u64)idx_b << 32;
1155                                 return;
1156                         }
1157                 }
1158         }
1159         /* signal end of iteration */
1160         *idx = ULLONG_MAX;
1161 }
1162
1163 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
1164 /*
1165  * Common iterator interface used to define for_each_mem_pfn_range().
1166  */
1167 void __init_memblock __next_mem_pfn_range(int *idx, int nid,
1168                                 unsigned long *out_start_pfn,
1169                                 unsigned long *out_end_pfn, int *out_nid)
1170 {
1171         struct memblock_type *type = &memblock.memory;
1172         struct memblock_region *r;
1173
1174         while (++*idx < type->cnt) {
1175                 r = &type->regions[*idx];
1176
1177                 if (PFN_UP(r->base) >= PFN_DOWN(r->base + r->size))
1178                         continue;
1179                 if (nid == MAX_NUMNODES || nid == r->nid)
1180                         break;
1181         }
1182         if (*idx >= type->cnt) {
1183                 *idx = -1;
1184                 return;
1185         }
1186
1187         if (out_start_pfn)
1188                 *out_start_pfn = PFN_UP(r->base);
1189         if (out_end_pfn)
1190                 *out_end_pfn = PFN_DOWN(r->base + r->size);
1191         if (out_nid)
1192                 *out_nid = r->nid;
1193 }
1194
1195 /**
1196  * memblock_set_node - set node ID on memblock regions
1197  * @base: base of area to set node ID for
1198  * @size: size of area to set node ID for
1199  * @type: memblock type to set node ID for
1200  * @nid: node ID to set
1201  *
1202  * Set the nid of memblock @type regions in [@base, @base + @size) to @nid.
1203  * Regions which cross the area boundaries are split as necessary.
1204  *
1205  * Return:
1206  * 0 on success, -errno on failure.
1207  */
1208 int __init_memblock memblock_set_node(phys_addr_t base, phys_addr_t size,
1209                                       struct memblock_type *type, int nid)
1210 {
1211         int start_rgn, end_rgn;
1212         int i, ret;
1213
1214         ret = memblock_isolate_range(type, base, size, &start_rgn, &end_rgn);
1215         if (ret)
1216                 return ret;
1217
1218         for (i = start_rgn; i < end_rgn; i++)
1219                 memblock_set_region_node(&type->regions[i], nid);
1220
1221         memblock_merge_regions(type);
1222         return 0;
1223 }
1224 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
1225 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1226 /**
1227  * __next_mem_pfn_range_in_zone - iterator for for_each_*_range_in_zone()
1228  *
1229  * @idx: pointer to u64 loop variable
1230  * @zone: zone in which all of the memory blocks reside
1231  * @out_spfn: ptr to ulong for start pfn of the range, can be %NULL
1232  * @out_epfn: ptr to ulong for end pfn of the range, can be %NULL
1233  *
1234  * This function is meant to be a zone/pfn specific wrapper for the
1235  * for_each_mem_range type iterators. Specifically they are used in the
1236  * deferred memory init routines and as such we were duplicating much of
1237  * this logic throughout the code. So instead of having it in multiple
1238  * locations it seemed like it would make more sense to centralize this to
1239  * one new iterator that does everything they need.
1240  */
1241 void __init_memblock
1242 __next_mem_pfn_range_in_zone(u64 *idx, struct zone *zone,
1243                              unsigned long *out_spfn, unsigned long *out_epfn)
1244 {
1245         int zone_nid = zone_to_nid(zone);
1246         phys_addr_t spa, epa;
1247         int nid;
1248
1249         __next_mem_range(idx, zone_nid, MEMBLOCK_NONE,
1250                          &memblock.memory, &memblock.reserved,
1251                          &spa, &epa, &nid);
1252
1253         while (*idx != U64_MAX) {
1254                 unsigned long epfn = PFN_DOWN(epa);
1255                 unsigned long spfn = PFN_UP(spa);
1256
1257                 /*
1258                  * Verify the end is at least past the start of the zone and
1259                  * that we have at least one PFN to initialize.
1260                  */
1261                 if (zone->zone_start_pfn < epfn && spfn < epfn) {
1262                         /* if we went too far just stop searching */
1263                         if (zone_end_pfn(zone) <= spfn) {
1264                                 *idx = U64_MAX;
1265                                 break;
1266                         }
1267
1268                         if (out_spfn)
1269                                 *out_spfn = max(zone->zone_start_pfn, spfn);
1270                         if (out_epfn)
1271                                 *out_epfn = min(zone_end_pfn(zone), epfn);
1272
1273                         return;
1274                 }
1275
1276                 __next_mem_range(idx, zone_nid, MEMBLOCK_NONE,
1277                                  &memblock.memory, &memblock.reserved,
1278                                  &spa, &epa, &nid);
1279         }
1280
1281         /* signal end of iteration */
1282         if (out_spfn)
1283                 *out_spfn = ULONG_MAX;
1284         if (out_epfn)
1285                 *out_epfn = 0;
1286 }
1287
1288 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1289
1290 /**
1291  * memblock_alloc_range_nid - allocate boot memory block
1292  * @size: size of memory block to be allocated in bytes
1293  * @align: alignment of the region and block's size
1294  * @start: the lower bound of the memory region to allocate (phys address)
1295  * @end: the upper bound of the memory region to allocate (phys address)
1296  * @nid: nid of the free area to find, %NUMA_NO_NODE for any node
1297  *
1298  * The allocation is performed from memory region limited by
1299  * memblock.current_limit if @max_addr == %MEMBLOCK_ALLOC_ACCESSIBLE.
1300  *
1301  * If the specified node can not hold the requested memory the
1302  * allocation falls back to any node in the system
1303  *
1304  * For systems with memory mirroring, the allocation is attempted first
1305  * from the regions with mirroring enabled and then retried from any
1306  * memory region.
1307  *
1308  * In addition, function sets the min_count to 0 using kmemleak_alloc_phys for
1309  * allocated boot memory block, so that it is never reported as leaks.
1310  *
1311  * Return:
1312  * Physical address of allocated memory block on success, %0 on failure.
1313  */
1314 static phys_addr_t __init memblock_alloc_range_nid(phys_addr_t size,
1315                                         phys_addr_t align, phys_addr_t start,
1316                                         phys_addr_t end, int nid)
1317 {
1318         enum memblock_flags flags = choose_memblock_flags();
1319         phys_addr_t found;
1320
1321         if (WARN_ONCE(nid == MAX_NUMNODES, "Usage of MAX_NUMNODES is deprecated. Use NUMA_NO_NODE instead\n"))
1322                 nid = NUMA_NO_NODE;
1323
1324         if (!align) {
1325                 /* Can't use WARNs this early in boot on powerpc */
1326                 dump_stack();
1327                 align = SMP_CACHE_BYTES;
1328         }
1329
1330 again:
1331         found = memblock_find_in_range_node(size, align, start, end, nid,
1332                                             flags);
1333         if (found && !memblock_reserve(found, size))
1334                 goto done;
1335
1336         if (nid != NUMA_NO_NODE) {
1337                 found = memblock_find_in_range_node(size, align, start,
1338                                                     end, NUMA_NO_NODE,
1339                                                     flags);
1340                 if (found && !memblock_reserve(found, size))
1341                         goto done;
1342         }
1343
1344         if (flags & MEMBLOCK_MIRROR) {
1345                 flags &= ~MEMBLOCK_MIRROR;
1346                 pr_warn("Could not allocate %pap bytes of mirrored memory\n",
1347                         &size);
1348                 goto again;
1349         }
1350
1351         return 0;
1352
1353 done:
1354         /* Skip kmemleak for kasan_init() due to high volume. */
1355         if (end != MEMBLOCK_ALLOC_KASAN)
1356                 /*
1357                  * The min_count is set to 0 so that memblock allocated
1358                  * blocks are never reported as leaks. This is because many
1359                  * of these blocks are only referred via the physical
1360                  * address which is not looked up by kmemleak.
1361                  */
1362                 kmemleak_alloc_phys(found, size, 0, 0);
1363
1364         return found;
1365 }
1366
1367 /**
1368  * memblock_phys_alloc_range - allocate a memory block inside specified range
1369  * @size: size of memory block to be allocated in bytes
1370  * @align: alignment of the region and block's size
1371  * @start: the lower bound of the memory region to allocate (physical address)
1372  * @end: the upper bound of the memory region to allocate (physical address)
1373  *
1374  * Allocate @size bytes in the between @start and @end.
1375  *
1376  * Return: physical address of the allocated memory block on success,
1377  * %0 on failure.
1378  */
1379 phys_addr_t __init memblock_phys_alloc_range(phys_addr_t size,
1380                                              phys_addr_t align,
1381                                              phys_addr_t start,
1382                                              phys_addr_t end)
1383 {
1384         return memblock_alloc_range_nid(size, align, start, end, NUMA_NO_NODE);
1385 }
1386
1387 /**
1388  * memblock_phys_alloc_try_nid - allocate a memory block from specified MUMA node
1389  * @size: size of memory block to be allocated in bytes
1390  * @align: alignment of the region and block's size
1391  * @nid: nid of the free area to find, %NUMA_NO_NODE for any node
1392  *
1393  * Allocates memory block from the specified NUMA node. If the node
1394  * has no available memory, attempts to allocated from any node in the
1395  * system.
1396  *
1397  * Return: physical address of the allocated memory block on success,
1398  * %0 on failure.
1399  */
1400 phys_addr_t __init memblock_phys_alloc_try_nid(phys_addr_t size, phys_addr_t align, int nid)
1401 {
1402         return memblock_alloc_range_nid(size, align, 0,
1403                                         MEMBLOCK_ALLOC_ACCESSIBLE, nid);
1404 }
1405
1406 /**
1407  * memblock_alloc_internal - allocate boot memory block
1408  * @size: size of memory block to be allocated in bytes
1409  * @align: alignment of the region and block's size
1410  * @min_addr: the lower bound of the memory region to allocate (phys address)
1411  * @max_addr: the upper bound of the memory region to allocate (phys address)
1412  * @nid: nid of the free area to find, %NUMA_NO_NODE for any node
1413  *
1414  * Allocates memory block using memblock_alloc_range_nid() and
1415  * converts the returned physical address to virtual.
1416  *
1417  * The @min_addr limit is dropped if it can not be satisfied and the allocation
1418  * will fall back to memory below @min_addr. Other constraints, such
1419  * as node and mirrored memory will be handled again in
1420  * memblock_alloc_range_nid().
1421  *
1422  * Return:
1423  * Virtual address of allocated memory block on success, NULL on failure.
1424  */
1425 static void * __init memblock_alloc_internal(
1426                                 phys_addr_t size, phys_addr_t align,
1427                                 phys_addr_t min_addr, phys_addr_t max_addr,
1428                                 int nid)
1429 {
1430         phys_addr_t alloc;
1431
1432         /*
1433          * Detect any accidental use of these APIs after slab is ready, as at
1434          * this moment memblock may be deinitialized already and its
1435          * internal data may be destroyed (after execution of memblock_free_all)
1436          */
1437         if (WARN_ON_ONCE(slab_is_available()))
1438                 return kzalloc_node(size, GFP_NOWAIT, nid);
1439
1440         if (max_addr > memblock.current_limit)
1441                 max_addr = memblock.current_limit;
1442
1443         alloc = memblock_alloc_range_nid(size, align, min_addr, max_addr, nid);
1444
1445         /* retry allocation without lower limit */
1446         if (!alloc && min_addr)
1447                 alloc = memblock_alloc_range_nid(size, align, 0, max_addr, nid);
1448
1449         if (!alloc)
1450                 return NULL;
1451
1452         return phys_to_virt(alloc);
1453 }
1454
1455 /**
1456  * memblock_alloc_try_nid_raw - allocate boot memory block without zeroing
1457  * memory and without panicking
1458  * @size: size of memory block to be allocated in bytes
1459  * @align: alignment of the region and block's size
1460  * @min_addr: the lower bound of the memory region from where the allocation
1461  *        is preferred (phys address)
1462  * @max_addr: the upper bound of the memory region from where the allocation
1463  *            is preferred (phys address), or %MEMBLOCK_ALLOC_ACCESSIBLE to
1464  *            allocate only from memory limited by memblock.current_limit value
1465  * @nid: nid of the free area to find, %NUMA_NO_NODE for any node
1466  *
1467  * Public function, provides additional debug information (including caller
1468  * info), if enabled. Does not zero allocated memory, does not panic if request
1469  * cannot be satisfied.
1470  *
1471  * Return:
1472  * Virtual address of allocated memory block on success, NULL on failure.
1473  */
1474 void * __init memblock_alloc_try_nid_raw(
1475                         phys_addr_t size, phys_addr_t align,
1476                         phys_addr_t min_addr, phys_addr_t max_addr,
1477                         int nid)
1478 {
1479         void *ptr;
1480
1481         memblock_dbg("%s: %llu bytes align=0x%llx nid=%d from=%pa max_addr=%pa %pS\n",
1482                      __func__, (u64)size, (u64)align, nid, &min_addr,
1483                      &max_addr, (void *)_RET_IP_);
1484
1485         ptr = memblock_alloc_internal(size, align,
1486                                            min_addr, max_addr, nid);
1487         if (ptr && size > 0)
1488                 page_init_poison(ptr, size);
1489
1490         return ptr;
1491 }
1492
1493 /**
1494  * memblock_alloc_try_nid - allocate boot memory block
1495  * @size: size of memory block to be allocated in bytes
1496  * @align: alignment of the region and block's size
1497  * @min_addr: the lower bound of the memory region from where the allocation
1498  *        is preferred (phys address)
1499  * @max_addr: the upper bound of the memory region from where the allocation
1500  *            is preferred (phys address), or %MEMBLOCK_ALLOC_ACCESSIBLE to
1501  *            allocate only from memory limited by memblock.current_limit value
1502  * @nid: nid of the free area to find, %NUMA_NO_NODE for any node
1503  *
1504  * Public function, provides additional debug information (including caller
1505  * info), if enabled. This function zeroes the allocated memory.
1506  *
1507  * Return:
1508  * Virtual address of allocated memory block on success, NULL on failure.
1509  */
1510 void * __init memblock_alloc_try_nid(
1511                         phys_addr_t size, phys_addr_t align,
1512                         phys_addr_t min_addr, phys_addr_t max_addr,
1513                         int nid)
1514 {
1515         void *ptr;
1516
1517         memblock_dbg("%s: %llu bytes align=0x%llx nid=%d from=%pa max_addr=%pa %pS\n",
1518                      __func__, (u64)size, (u64)align, nid, &min_addr,
1519                      &max_addr, (void *)_RET_IP_);
1520         ptr = memblock_alloc_internal(size, align,
1521                                            min_addr, max_addr, nid);
1522         if (ptr)
1523                 memset(ptr, 0, size);
1524
1525         return ptr;
1526 }
1527
1528 /**
1529  * __memblock_free_late - free pages directly to buddy allocator
1530  * @base: phys starting address of the  boot memory block
1531  * @size: size of the boot memory block in bytes
1532  *
1533  * This is only useful when the memblock allocator has already been torn
1534  * down, but we are still initializing the system.  Pages are released directly
1535  * to the buddy allocator.
1536  */
1537 void __init __memblock_free_late(phys_addr_t base, phys_addr_t size)
1538 {
1539         phys_addr_t cursor, end;
1540
1541         end = base + size - 1;
1542         memblock_dbg("%s: [%pa-%pa] %pS\n",
1543                      __func__, &base, &end, (void *)_RET_IP_);
1544         kmemleak_free_part_phys(base, size);
1545         cursor = PFN_UP(base);
1546         end = PFN_DOWN(base + size);
1547
1548         for (; cursor < end; cursor++) {
1549                 memblock_free_pages(pfn_to_page(cursor), cursor, 0);
1550                 totalram_pages_inc();
1551         }
1552 }
1553
1554 /*
1555  * Remaining API functions
1556  */
1557
1558 phys_addr_t __init_memblock memblock_phys_mem_size(void)
1559 {
1560         return memblock.memory.total_size;
1561 }
1562
1563 phys_addr_t __init_memblock memblock_reserved_size(void)
1564 {
1565         return memblock.reserved.total_size;
1566 }
1567
1568 phys_addr_t __init memblock_mem_size(unsigned long limit_pfn)
1569 {
1570         unsigned long pages = 0;
1571         struct memblock_region *r;
1572         unsigned long start_pfn, end_pfn;
1573
1574         for_each_memblock(memory, r) {
1575                 start_pfn = memblock_region_memory_base_pfn(r);
1576                 end_pfn = memblock_region_memory_end_pfn(r);
1577                 start_pfn = min_t(unsigned long, start_pfn, limit_pfn);
1578                 end_pfn = min_t(unsigned long, end_pfn, limit_pfn);
1579                 pages += end_pfn - start_pfn;
1580         }
1581
1582         return PFN_PHYS(pages);
1583 }
1584
1585 /* lowest address */
1586 phys_addr_t __init_memblock memblock_start_of_DRAM(void)
1587 {
1588         return memblock.memory.regions[0].base;
1589 }
1590
1591 phys_addr_t __init_memblock memblock_end_of_DRAM(void)
1592 {
1593         int idx = memblock.memory.cnt - 1;
1594
1595         return (memblock.memory.regions[idx].base + memblock.memory.regions[idx].size);
1596 }
1597
1598 static phys_addr_t __init_memblock __find_max_addr(phys_addr_t limit)
1599 {
1600         phys_addr_t max_addr = PHYS_ADDR_MAX;
1601         struct memblock_region *r;
1602
1603         /*
1604          * translate the memory @limit size into the max address within one of
1605          * the memory memblock regions, if the @limit exceeds the total size
1606          * of those regions, max_addr will keep original value PHYS_ADDR_MAX
1607          */
1608         for_each_memblock(memory, r) {
1609                 if (limit <= r->size) {
1610                         max_addr = r->base + limit;
1611                         break;
1612                 }
1613                 limit -= r->size;
1614         }
1615
1616         return max_addr;
1617 }
1618
1619 void __init memblock_enforce_memory_limit(phys_addr_t limit)
1620 {
1621         phys_addr_t max_addr = PHYS_ADDR_MAX;
1622
1623         if (!limit)
1624                 return;
1625
1626         max_addr = __find_max_addr(limit);
1627
1628         /* @limit exceeds the total size of the memory, do nothing */
1629         if (max_addr == PHYS_ADDR_MAX)
1630                 return;
1631
1632         /* truncate both memory and reserved regions */
1633         memblock_remove_range(&memblock.memory, max_addr,
1634                               PHYS_ADDR_MAX);
1635         memblock_remove_range(&memblock.reserved, max_addr,
1636                               PHYS_ADDR_MAX);
1637 }
1638
1639 void __init memblock_cap_memory_range(phys_addr_t base, phys_addr_t size)
1640 {
1641         int start_rgn, end_rgn;
1642         int i, ret;
1643
1644         if (!size)
1645                 return;
1646
1647         ret = memblock_isolate_range(&memblock.memory, base, size,
1648                                                 &start_rgn, &end_rgn);
1649         if (ret)
1650                 return;
1651
1652         /* remove all the MAP regions */
1653         for (i = memblock.memory.cnt - 1; i >= end_rgn; i--)
1654                 if (!memblock_is_nomap(&memblock.memory.regions[i]))
1655                         memblock_remove_region(&memblock.memory, i);
1656
1657         for (i = start_rgn - 1; i >= 0; i--)
1658                 if (!memblock_is_nomap(&memblock.memory.regions[i]))
1659                         memblock_remove_region(&memblock.memory, i);
1660
1661         /* truncate the reserved regions */
1662         memblock_remove_range(&memblock.reserved, 0, base);
1663         memblock_remove_range(&memblock.reserved,
1664                         base + size, PHYS_ADDR_MAX);
1665 }
1666
1667 void __init memblock_mem_limit_remove_map(phys_addr_t limit)
1668 {
1669         phys_addr_t max_addr;
1670
1671         if (!limit)
1672                 return;
1673
1674         max_addr = __find_max_addr(limit);
1675
1676         /* @limit exceeds the total size of the memory, do nothing */
1677         if (max_addr == PHYS_ADDR_MAX)
1678                 return;
1679
1680         memblock_cap_memory_range(0, max_addr);
1681 }
1682
1683 static int __init_memblock memblock_search(struct memblock_type *type, phys_addr_t addr)
1684 {
1685         unsigned int left = 0, right = type->cnt;
1686
1687         do {
1688                 unsigned int mid = (right + left) / 2;
1689
1690                 if (addr < type->regions[mid].base)
1691                         right = mid;
1692                 else if (addr >= (type->regions[mid].base +
1693                                   type->regions[mid].size))
1694                         left = mid + 1;
1695                 else
1696                         return mid;
1697         } while (left < right);
1698         return -1;
1699 }
1700
1701 bool __init_memblock memblock_is_reserved(phys_addr_t addr)
1702 {
1703         return memblock_search(&memblock.reserved, addr) != -1;
1704 }
1705
1706 bool __init_memblock memblock_is_memory(phys_addr_t addr)
1707 {
1708         return memblock_search(&memblock.memory, addr) != -1;
1709 }
1710
1711 bool __init_memblock memblock_is_map_memory(phys_addr_t addr)
1712 {
1713         int i = memblock_search(&memblock.memory, addr);
1714
1715         if (i == -1)
1716                 return false;
1717         return !memblock_is_nomap(&memblock.memory.regions[i]);
1718 }
1719
1720 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
1721 int __init_memblock memblock_search_pfn_nid(unsigned long pfn,
1722                          unsigned long *start_pfn, unsigned long *end_pfn)
1723 {
1724         struct memblock_type *type = &memblock.memory;
1725         int mid = memblock_search(type, PFN_PHYS(pfn));
1726
1727         if (mid == -1)
1728                 return -1;
1729
1730         *start_pfn = PFN_DOWN(type->regions[mid].base);
1731         *end_pfn = PFN_DOWN(type->regions[mid].base + type->regions[mid].size);
1732
1733         return type->regions[mid].nid;
1734 }
1735 #endif
1736
1737 /**
1738  * memblock_is_region_memory - check if a region is a subset of memory
1739  * @base: base of region to check
1740  * @size: size of region to check
1741  *
1742  * Check if the region [@base, @base + @size) is a subset of a memory block.
1743  *
1744  * Return:
1745  * 0 if false, non-zero if true
1746  */
1747 bool __init_memblock memblock_is_region_memory(phys_addr_t base, phys_addr_t size)
1748 {
1749         int idx = memblock_search(&memblock.memory, base);
1750         phys_addr_t end = base + memblock_cap_size(base, &size);
1751
1752         if (idx == -1)
1753                 return false;
1754         return (memblock.memory.regions[idx].base +
1755                  memblock.memory.regions[idx].size) >= end;
1756 }
1757
1758 /**
1759  * memblock_is_region_reserved - check if a region intersects reserved memory
1760  * @base: base of region to check
1761  * @size: size of region to check
1762  *
1763  * Check if the region [@base, @base + @size) intersects a reserved
1764  * memory block.
1765  *
1766  * Return:
1767  * True if they intersect, false if not.
1768  */
1769 bool __init_memblock memblock_is_region_reserved(phys_addr_t base, phys_addr_t size)
1770 {
1771         return memblock_overlaps_region(&memblock.reserved, base, size);
1772 }
1773
1774 void __init_memblock memblock_trim_memory(phys_addr_t align)
1775 {
1776         phys_addr_t start, end, orig_start, orig_end;
1777         struct memblock_region *r;
1778
1779         for_each_memblock(memory, r) {
1780                 orig_start = r->base;
1781                 orig_end = r->base + r->size;
1782                 start = round_up(orig_start, align);
1783                 end = round_down(orig_end, align);
1784
1785                 if (start == orig_start && end == orig_end)
1786                         continue;
1787
1788                 if (start < end) {
1789                         r->base = start;
1790                         r->size = end - start;
1791                 } else {
1792                         memblock_remove_region(&memblock.memory,
1793                                                r - memblock.memory.regions);
1794                         r--;
1795                 }
1796         }
1797 }
1798
1799 void __init_memblock memblock_set_current_limit(phys_addr_t limit)
1800 {
1801         memblock.current_limit = limit;
1802 }
1803
1804 phys_addr_t __init_memblock memblock_get_current_limit(void)
1805 {
1806         return memblock.current_limit;
1807 }
1808
1809 static void __init_memblock memblock_dump(struct memblock_type *type)
1810 {
1811         phys_addr_t base, end, size;
1812         enum memblock_flags flags;
1813         int idx;
1814         struct memblock_region *rgn;
1815
1816         pr_info(" %s.cnt  = 0x%lx\n", type->name, type->cnt);
1817
1818         for_each_memblock_type(idx, type, rgn) {
1819                 char nid_buf[32] = "";
1820
1821                 base = rgn->base;
1822                 size = rgn->size;
1823                 end = base + size - 1;
1824                 flags = rgn->flags;
1825 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
1826                 if (memblock_get_region_node(rgn) != MAX_NUMNODES)
1827                         snprintf(nid_buf, sizeof(nid_buf), " on node %d",
1828                                  memblock_get_region_node(rgn));
1829 #endif
1830                 pr_info(" %s[%#x]\t[%pa-%pa], %pa bytes%s flags: %#x\n",
1831                         type->name, idx, &base, &end, &size, nid_buf, flags);
1832         }
1833 }
1834
1835 void __init_memblock __memblock_dump_all(void)
1836 {
1837         pr_info("MEMBLOCK configuration:\n");
1838         pr_info(" memory size = %pa reserved size = %pa\n",
1839                 &memblock.memory.total_size,
1840                 &memblock.reserved.total_size);
1841
1842         memblock_dump(&memblock.memory);
1843         memblock_dump(&memblock.reserved);
1844 #ifdef CONFIG_HAVE_MEMBLOCK_PHYS_MAP
1845         memblock_dump(&memblock.physmem);
1846 #endif
1847 }
1848
1849 void __init memblock_allow_resize(void)
1850 {
1851         memblock_can_resize = 1;
1852 }
1853
1854 static int __init early_memblock(char *p)
1855 {
1856         if (p && strstr(p, "debug"))
1857                 memblock_debug = 1;
1858         return 0;
1859 }
1860 early_param("memblock", early_memblock);
1861
1862 static void __init __free_pages_memory(unsigned long start, unsigned long end)
1863 {
1864         int order;
1865
1866         while (start < end) {
1867                 order = min(MAX_ORDER - 1UL, __ffs(start));
1868
1869                 while (start + (1UL << order) > end)
1870                         order--;
1871
1872                 memblock_free_pages(pfn_to_page(start), start, order);
1873
1874                 start += (1UL << order);
1875         }
1876 }
1877
1878 static unsigned long __init __free_memory_core(phys_addr_t start,
1879                                  phys_addr_t end)
1880 {
1881         unsigned long start_pfn = PFN_UP(start);
1882         unsigned long end_pfn = min_t(unsigned long,
1883                                       PFN_DOWN(end), max_low_pfn);
1884
1885         if (start_pfn >= end_pfn)
1886                 return 0;
1887
1888         __free_pages_memory(start_pfn, end_pfn);
1889
1890         return end_pfn - start_pfn;
1891 }
1892
1893 static unsigned long __init free_low_memory_core_early(void)
1894 {
1895         unsigned long count = 0;
1896         phys_addr_t start, end;
1897         u64 i;
1898
1899         memblock_clear_hotplug(0, -1);
1900
1901         for_each_reserved_mem_region(i, &start, &end)
1902                 reserve_bootmem_region(start, end);
1903
1904         /*
1905          * We need to use NUMA_NO_NODE instead of NODE_DATA(0)->node_id
1906          *  because in some case like Node0 doesn't have RAM installed
1907          *  low ram will be on Node1
1908          */
1909         for_each_free_mem_range(i, NUMA_NO_NODE, MEMBLOCK_NONE, &start, &end,
1910                                 NULL)
1911                 count += __free_memory_core(start, end);
1912
1913         return count;
1914 }
1915
1916 static int reset_managed_pages_done __initdata;
1917
1918 void reset_node_managed_pages(pg_data_t *pgdat)
1919 {
1920         struct zone *z;
1921
1922         for (z = pgdat->node_zones; z < pgdat->node_zones + MAX_NR_ZONES; z++)
1923                 atomic_long_set(&z->managed_pages, 0);
1924 }
1925
1926 void __init reset_all_zones_managed_pages(void)
1927 {
1928         struct pglist_data *pgdat;
1929
1930         if (reset_managed_pages_done)
1931                 return;
1932
1933         for_each_online_pgdat(pgdat)
1934                 reset_node_managed_pages(pgdat);
1935
1936         reset_managed_pages_done = 1;
1937 }
1938
1939 /**
1940  * memblock_free_all - release free pages to the buddy allocator
1941  *
1942  * Return: the number of pages actually released.
1943  */
1944 unsigned long __init memblock_free_all(void)
1945 {
1946         unsigned long pages;
1947
1948         reset_all_zones_managed_pages();
1949
1950         pages = free_low_memory_core_early();
1951         totalram_pages_add(pages);
1952
1953         return pages;
1954 }
1955
1956 #if defined(CONFIG_DEBUG_FS) && defined(CONFIG_ARCH_KEEP_MEMBLOCK)
1957
1958 static int memblock_debug_show(struct seq_file *m, void *private)
1959 {
1960         struct memblock_type *type = m->private;
1961         struct memblock_region *reg;
1962         int i;
1963         phys_addr_t end;
1964
1965         for (i = 0; i < type->cnt; i++) {
1966                 reg = &type->regions[i];
1967                 end = reg->base + reg->size - 1;
1968
1969                 seq_printf(m, "%4d: ", i);
1970                 seq_printf(m, "%pa..%pa\n", &reg->base, &end);
1971         }
1972         return 0;
1973 }
1974 DEFINE_SHOW_ATTRIBUTE(memblock_debug);
1975
1976 static int __init memblock_init_debugfs(void)
1977 {
1978         struct dentry *root = debugfs_create_dir("memblock", NULL);
1979
1980         debugfs_create_file("memory", 0444, root,
1981                             &memblock.memory, &memblock_debug_fops);
1982         debugfs_create_file("reserved", 0444, root,
1983                             &memblock.reserved, &memblock_debug_fops);
1984 #ifdef CONFIG_HAVE_MEMBLOCK_PHYS_MAP
1985         debugfs_create_file("physmem", 0444, root,
1986                             &memblock.physmem, &memblock_debug_fops);
1987 #endif
1988
1989         return 0;
1990 }
1991 __initcall(memblock_init_debugfs);
1992
1993 #endif /* CONFIG_DEBUG_FS */