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