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