tile: support "memmap" boot parameter
[firefly-linux-kernel-4.4.55.git] / arch / tile / kernel / setup.c
1 /*
2  * Copyright 2010 Tilera Corporation. All Rights Reserved.
3  *
4  *   This program is free software; you can redistribute it and/or
5  *   modify it under the terms of the GNU General Public License
6  *   as published by the Free Software Foundation, version 2.
7  *
8  *   This program is distributed in the hope that it will be useful, but
9  *   WITHOUT ANY WARRANTY; without even the implied warranty of
10  *   MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
11  *   NON INFRINGEMENT.  See the GNU General Public License for
12  *   more details.
13  */
14
15 #include <linux/sched.h>
16 #include <linux/kernel.h>
17 #include <linux/mmzone.h>
18 #include <linux/bootmem.h>
19 #include <linux/module.h>
20 #include <linux/node.h>
21 #include <linux/cpu.h>
22 #include <linux/ioport.h>
23 #include <linux/irq.h>
24 #include <linux/kexec.h>
25 #include <linux/pci.h>
26 #include <linux/swiotlb.h>
27 #include <linux/initrd.h>
28 #include <linux/io.h>
29 #include <linux/highmem.h>
30 #include <linux/smp.h>
31 #include <linux/timex.h>
32 #include <linux/hugetlb.h>
33 #include <linux/start_kernel.h>
34 #include <linux/screen_info.h>
35 #include <asm/setup.h>
36 #include <asm/sections.h>
37 #include <asm/cacheflush.h>
38 #include <asm/pgalloc.h>
39 #include <asm/mmu_context.h>
40 #include <hv/hypervisor.h>
41 #include <arch/interrupts.h>
42
43 /* <linux/smp.h> doesn't provide this definition. */
44 #ifndef CONFIG_SMP
45 #define setup_max_cpus 1
46 #endif
47
48 static inline int ABS(int x) { return x >= 0 ? x : -x; }
49
50 /* Chip information */
51 char chip_model[64] __write_once;
52
53 #ifdef CONFIG_VT
54 struct screen_info screen_info;
55 #endif
56
57 struct pglist_data node_data[MAX_NUMNODES] __read_mostly;
58 EXPORT_SYMBOL(node_data);
59
60 /* Information on the NUMA nodes that we compute early */
61 unsigned long __cpuinitdata node_start_pfn[MAX_NUMNODES];
62 unsigned long __cpuinitdata node_end_pfn[MAX_NUMNODES];
63 unsigned long __initdata node_memmap_pfn[MAX_NUMNODES];
64 unsigned long __initdata node_percpu_pfn[MAX_NUMNODES];
65 unsigned long __initdata node_free_pfn[MAX_NUMNODES];
66
67 static unsigned long __initdata node_percpu[MAX_NUMNODES];
68
69 /*
70  * per-CPU stack and boot info.
71  */
72 DEFINE_PER_CPU(unsigned long, boot_sp) =
73         (unsigned long)init_stack + THREAD_SIZE;
74
75 #ifdef CONFIG_SMP
76 DEFINE_PER_CPU(unsigned long, boot_pc) = (unsigned long)start_kernel;
77 #else
78 /*
79  * The variable must be __initdata since it references __init code.
80  * With CONFIG_SMP it is per-cpu data, which is exempt from validation.
81  */
82 unsigned long __initdata boot_pc = (unsigned long)start_kernel;
83 #endif
84
85 #ifdef CONFIG_HIGHMEM
86 /* Page frame index of end of lowmem on each controller. */
87 unsigned long __cpuinitdata node_lowmem_end_pfn[MAX_NUMNODES];
88
89 /* Number of pages that can be mapped into lowmem. */
90 static unsigned long __initdata mappable_physpages;
91 #endif
92
93 /* Data on which physical memory controller corresponds to which NUMA node */
94 int node_controller[MAX_NUMNODES] = { [0 ... MAX_NUMNODES-1] = -1 };
95
96 #ifdef CONFIG_HIGHMEM
97 /* Map information from VAs to PAs */
98 unsigned long pbase_map[1 << (32 - HPAGE_SHIFT)]
99   __write_once __attribute__((aligned(L2_CACHE_BYTES)));
100 EXPORT_SYMBOL(pbase_map);
101
102 /* Map information from PAs to VAs */
103 void *vbase_map[NR_PA_HIGHBIT_VALUES]
104   __write_once __attribute__((aligned(L2_CACHE_BYTES)));
105 EXPORT_SYMBOL(vbase_map);
106 #endif
107
108 /* Node number as a function of the high PA bits */
109 int highbits_to_node[NR_PA_HIGHBIT_VALUES] __write_once;
110 EXPORT_SYMBOL(highbits_to_node);
111
112 static unsigned int __initdata maxmem_pfn = -1U;
113 static unsigned int __initdata maxnodemem_pfn[MAX_NUMNODES] = {
114         [0 ... MAX_NUMNODES-1] = -1U
115 };
116 static nodemask_t __initdata isolnodes;
117
118 #if defined(CONFIG_PCI) && !defined(__tilegx__)
119 enum { DEFAULT_PCI_RESERVE_MB = 64 };
120 static unsigned int __initdata pci_reserve_mb = DEFAULT_PCI_RESERVE_MB;
121 unsigned long __initdata pci_reserve_start_pfn = -1U;
122 unsigned long __initdata pci_reserve_end_pfn = -1U;
123 #endif
124
125 static int __init setup_maxmem(char *str)
126 {
127         unsigned long long maxmem;
128         if (str == NULL || (maxmem = memparse(str, NULL)) == 0)
129                 return -EINVAL;
130
131         maxmem_pfn = (maxmem >> HPAGE_SHIFT) << (HPAGE_SHIFT - PAGE_SHIFT);
132         pr_info("Forcing RAM used to no more than %dMB\n",
133                maxmem_pfn >> (20 - PAGE_SHIFT));
134         return 0;
135 }
136 early_param("maxmem", setup_maxmem);
137
138 static int __init setup_maxnodemem(char *str)
139 {
140         char *endp;
141         unsigned long long maxnodemem;
142         long node;
143
144         node = str ? simple_strtoul(str, &endp, 0) : INT_MAX;
145         if (node >= MAX_NUMNODES || *endp != ':')
146                 return -EINVAL;
147
148         maxnodemem = memparse(endp+1, NULL);
149         maxnodemem_pfn[node] = (maxnodemem >> HPAGE_SHIFT) <<
150                 (HPAGE_SHIFT - PAGE_SHIFT);
151         pr_info("Forcing RAM used on node %ld to no more than %dMB\n",
152                node, maxnodemem_pfn[node] >> (20 - PAGE_SHIFT));
153         return 0;
154 }
155 early_param("maxnodemem", setup_maxnodemem);
156
157 struct memmap_entry {
158         u64 addr;       /* start of memory segment */
159         u64 size;       /* size of memory segment */
160 };
161 static struct memmap_entry memmap_map[64];
162 static int memmap_nr;
163
164 static void add_memmap_region(u64 addr, u64 size)
165 {
166         if (memmap_nr >= ARRAY_SIZE(memmap_map)) {
167                 pr_err("Ooops! Too many entries in the memory map!\n");
168                 return;
169         }
170         memmap_map[memmap_nr].addr = addr;
171         memmap_map[memmap_nr].size = size;
172         memmap_nr++;
173 }
174
175 static int __init setup_memmap(char *p)
176 {
177         char *oldp;
178         u64 start_at, mem_size;
179
180         if (!p)
181                 return -EINVAL;
182
183         if (!strncmp(p, "exactmap", 8)) {
184                 pr_err("\"memmap=exactmap\" not valid on tile\n");
185                 return 0;
186         }
187
188         oldp = p;
189         mem_size = memparse(p, &p);
190         if (p == oldp)
191                 return -EINVAL;
192
193         if (*p == '@') {
194                 pr_err("\"memmap=nn@ss\" (force RAM) invalid on tile\n");
195         } else if (*p == '#') {
196                 pr_err("\"memmap=nn#ss\" (force ACPI data) invalid on tile\n");
197         } else if (*p == '$') {
198                 start_at = memparse(p+1, &p);
199                 add_memmap_region(start_at, mem_size);
200         } else {
201                 if (mem_size == 0)
202                         return -EINVAL;
203                 maxmem_pfn = (mem_size >> HPAGE_SHIFT) <<
204                         (HPAGE_SHIFT - PAGE_SHIFT);
205         }
206         return *p == '\0' ? 0 : -EINVAL;
207 }
208 early_param("memmap", setup_memmap);
209
210 static int __init setup_mem(char *str)
211 {
212         return setup_maxmem(str);
213 }
214 early_param("mem", setup_mem);  /* compatibility with x86 */
215
216 static int __init setup_isolnodes(char *str)
217 {
218         char buf[MAX_NUMNODES * 5];
219         if (str == NULL || nodelist_parse(str, isolnodes) != 0)
220                 return -EINVAL;
221
222         nodelist_scnprintf(buf, sizeof(buf), isolnodes);
223         pr_info("Set isolnodes value to '%s'\n", buf);
224         return 0;
225 }
226 early_param("isolnodes", setup_isolnodes);
227
228 #if defined(CONFIG_PCI) && !defined(__tilegx__)
229 static int __init setup_pci_reserve(char* str)
230 {
231         unsigned long mb;
232
233         if (str == NULL || strict_strtoul(str, 0, &mb) != 0 ||
234             mb > 3 * 1024)
235                 return -EINVAL;
236
237         pci_reserve_mb = mb;
238         pr_info("Reserving %dMB for PCIE root complex mappings\n",
239                 pci_reserve_mb);
240         return 0;
241 }
242 early_param("pci_reserve", setup_pci_reserve);
243 #endif
244
245 #ifndef __tilegx__
246 /*
247  * vmalloc=size forces the vmalloc area to be exactly 'size' bytes.
248  * This can be used to increase (or decrease) the vmalloc area.
249  */
250 static int __init parse_vmalloc(char *arg)
251 {
252         if (!arg)
253                 return -EINVAL;
254
255         VMALLOC_RESERVE = (memparse(arg, &arg) + PGDIR_SIZE - 1) & PGDIR_MASK;
256
257         /* See validate_va() for more on this test. */
258         if ((long)_VMALLOC_START >= 0)
259                 early_panic("\"vmalloc=%#lx\" value too large: maximum %#lx\n",
260                             VMALLOC_RESERVE, _VMALLOC_END - 0x80000000UL);
261
262         return 0;
263 }
264 early_param("vmalloc", parse_vmalloc);
265 #endif
266
267 #ifdef CONFIG_HIGHMEM
268 /*
269  * Determine for each controller where its lowmem is mapped and how much of
270  * it is mapped there.  On controller zero, the first few megabytes are
271  * already mapped in as code at MEM_SV_INTRPT, so in principle we could
272  * start our data mappings higher up, but for now we don't bother, to avoid
273  * additional confusion.
274  *
275  * One question is whether, on systems with more than 768 Mb and
276  * controllers of different sizes, to map in a proportionate amount of
277  * each one, or to try to map the same amount from each controller.
278  * (E.g. if we have three controllers with 256MB, 1GB, and 256MB
279  * respectively, do we map 256MB from each, or do we map 128 MB, 512
280  * MB, and 128 MB respectively?)  For now we use a proportionate
281  * solution like the latter.
282  *
283  * The VA/PA mapping demands that we align our decisions at 16 MB
284  * boundaries so that we can rapidly convert VA to PA.
285  */
286 static void *__init setup_pa_va_mapping(void)
287 {
288         unsigned long curr_pages = 0;
289         unsigned long vaddr = PAGE_OFFSET;
290         nodemask_t highonlynodes = isolnodes;
291         int i, j;
292
293         memset(pbase_map, -1, sizeof(pbase_map));
294         memset(vbase_map, -1, sizeof(vbase_map));
295
296         /* Node zero cannot be isolated for LOWMEM purposes. */
297         node_clear(0, highonlynodes);
298
299         /* Count up the number of pages on non-highonlynodes controllers. */
300         mappable_physpages = 0;
301         for_each_online_node(i) {
302                 if (!node_isset(i, highonlynodes))
303                         mappable_physpages +=
304                                 node_end_pfn[i] - node_start_pfn[i];
305         }
306
307         for_each_online_node(i) {
308                 unsigned long start = node_start_pfn[i];
309                 unsigned long end = node_end_pfn[i];
310                 unsigned long size = end - start;
311                 unsigned long vaddr_end;
312
313                 if (node_isset(i, highonlynodes)) {
314                         /* Mark this controller as having no lowmem. */
315                         node_lowmem_end_pfn[i] = start;
316                         continue;
317                 }
318
319                 curr_pages += size;
320                 if (mappable_physpages > MAXMEM_PFN) {
321                         vaddr_end = PAGE_OFFSET +
322                                 (((u64)curr_pages * MAXMEM_PFN /
323                                   mappable_physpages)
324                                  << PAGE_SHIFT);
325                 } else {
326                         vaddr_end = PAGE_OFFSET + (curr_pages << PAGE_SHIFT);
327                 }
328                 for (j = 0; vaddr < vaddr_end; vaddr += HPAGE_SIZE, ++j) {
329                         unsigned long this_pfn =
330                                 start + (j << HUGETLB_PAGE_ORDER);
331                         pbase_map[vaddr >> HPAGE_SHIFT] = this_pfn;
332                         if (vbase_map[__pfn_to_highbits(this_pfn)] ==
333                             (void *)-1)
334                                 vbase_map[__pfn_to_highbits(this_pfn)] =
335                                         (void *)(vaddr & HPAGE_MASK);
336                 }
337                 node_lowmem_end_pfn[i] = start + (j << HUGETLB_PAGE_ORDER);
338                 BUG_ON(node_lowmem_end_pfn[i] > end);
339         }
340
341         /* Return highest address of any mapped memory. */
342         return (void *)vaddr;
343 }
344 #endif /* CONFIG_HIGHMEM */
345
346 /*
347  * Register our most important memory mappings with the debug stub.
348  *
349  * This is up to 4 mappings for lowmem, one mapping per memory
350  * controller, plus one for our text segment.
351  */
352 static void __cpuinit store_permanent_mappings(void)
353 {
354         int i;
355
356         for_each_online_node(i) {
357                 HV_PhysAddr pa = ((HV_PhysAddr)node_start_pfn[i]) << PAGE_SHIFT;
358 #ifdef CONFIG_HIGHMEM
359                 HV_PhysAddr high_mapped_pa = node_lowmem_end_pfn[i];
360 #else
361                 HV_PhysAddr high_mapped_pa = node_end_pfn[i];
362 #endif
363
364                 unsigned long pages = high_mapped_pa - node_start_pfn[i];
365                 HV_VirtAddr addr = (HV_VirtAddr) __va(pa);
366                 hv_store_mapping(addr, pages << PAGE_SHIFT, pa);
367         }
368
369         hv_store_mapping((HV_VirtAddr)_text,
370                          (uint32_t)(_einittext - _text), 0);
371 }
372
373 /*
374  * Use hv_inquire_physical() to populate node_{start,end}_pfn[]
375  * and node_online_map, doing suitable sanity-checking.
376  * Also set min_low_pfn, max_low_pfn, and max_pfn.
377  */
378 static void __init setup_memory(void)
379 {
380         int i, j;
381         int highbits_seen[NR_PA_HIGHBIT_VALUES] = { 0 };
382 #ifdef CONFIG_HIGHMEM
383         long highmem_pages;
384 #endif
385 #ifndef __tilegx__
386         int cap;
387 #endif
388 #if defined(CONFIG_HIGHMEM) || defined(__tilegx__)
389         long lowmem_pages;
390 #endif
391         unsigned long physpages = 0;
392
393         /* We are using a char to hold the cpu_2_node[] mapping */
394         BUILD_BUG_ON(MAX_NUMNODES > 127);
395
396         /* Discover the ranges of memory available to us */
397         for (i = 0; ; ++i) {
398                 unsigned long start, size, end, highbits;
399                 HV_PhysAddrRange range = hv_inquire_physical(i);
400                 if (range.size == 0)
401                         break;
402 #ifdef CONFIG_FLATMEM
403                 if (i > 0) {
404                         pr_err("Can't use discontiguous PAs: %#llx..%#llx\n",
405                                range.size, range.start + range.size);
406                         continue;
407                 }
408 #endif
409 #ifndef __tilegx__
410                 if ((unsigned long)range.start) {
411                         pr_err("Range not at 4GB multiple: %#llx..%#llx\n",
412                                range.start, range.start + range.size);
413                         continue;
414                 }
415 #endif
416                 if ((range.start & (HPAGE_SIZE-1)) != 0 ||
417                     (range.size & (HPAGE_SIZE-1)) != 0) {
418                         unsigned long long start_pa = range.start;
419                         unsigned long long orig_size = range.size;
420                         range.start = (start_pa + HPAGE_SIZE - 1) & HPAGE_MASK;
421                         range.size -= (range.start - start_pa);
422                         range.size &= HPAGE_MASK;
423                         pr_err("Range not hugepage-aligned: %#llx..%#llx:"
424                                " now %#llx-%#llx\n",
425                                start_pa, start_pa + orig_size,
426                                range.start, range.start + range.size);
427                 }
428                 highbits = __pa_to_highbits(range.start);
429                 if (highbits >= NR_PA_HIGHBIT_VALUES) {
430                         pr_err("PA high bits too high: %#llx..%#llx\n",
431                                range.start, range.start + range.size);
432                         continue;
433                 }
434                 if (highbits_seen[highbits]) {
435                         pr_err("Range overlaps in high bits: %#llx..%#llx\n",
436                                range.start, range.start + range.size);
437                         continue;
438                 }
439                 highbits_seen[highbits] = 1;
440                 if (PFN_DOWN(range.size) > maxnodemem_pfn[i]) {
441                         int max_size = maxnodemem_pfn[i];
442                         if (max_size > 0) {
443                                 pr_err("Maxnodemem reduced node %d to"
444                                        " %d pages\n", i, max_size);
445                                 range.size = PFN_PHYS(max_size);
446                         } else {
447                                 pr_err("Maxnodemem disabled node %d\n", i);
448                                 continue;
449                         }
450                 }
451                 if (physpages + PFN_DOWN(range.size) > maxmem_pfn) {
452                         int max_size = maxmem_pfn - physpages;
453                         if (max_size > 0) {
454                                 pr_err("Maxmem reduced node %d to %d pages\n",
455                                        i, max_size);
456                                 range.size = PFN_PHYS(max_size);
457                         } else {
458                                 pr_err("Maxmem disabled node %d\n", i);
459                                 continue;
460                         }
461                 }
462                 if (i >= MAX_NUMNODES) {
463                         pr_err("Too many PA nodes (#%d): %#llx...%#llx\n",
464                                i, range.size, range.size + range.start);
465                         continue;
466                 }
467
468                 start = range.start >> PAGE_SHIFT;
469                 size = range.size >> PAGE_SHIFT;
470                 end = start + size;
471
472 #ifndef __tilegx__
473                 if (((HV_PhysAddr)end << PAGE_SHIFT) !=
474                     (range.start + range.size)) {
475                         pr_err("PAs too high to represent: %#llx..%#llx\n",
476                                range.start, range.start + range.size);
477                         continue;
478                 }
479 #endif
480 #if defined(CONFIG_PCI) && !defined(__tilegx__)
481                 /*
482                  * Blocks that overlap the pci reserved region must
483                  * have enough space to hold the maximum percpu data
484                  * region at the top of the range.  If there isn't
485                  * enough space above the reserved region, just
486                  * truncate the node.
487                  */
488                 if (start <= pci_reserve_start_pfn &&
489                     end > pci_reserve_start_pfn) {
490                         unsigned int per_cpu_size =
491                                 __per_cpu_end - __per_cpu_start;
492                         unsigned int percpu_pages =
493                                 NR_CPUS * (PFN_UP(per_cpu_size) >> PAGE_SHIFT);
494                         if (end < pci_reserve_end_pfn + percpu_pages) {
495                                 end = pci_reserve_start_pfn;
496                                 pr_err("PCI mapping region reduced node %d to"
497                                        " %ld pages\n", i, end - start);
498                         }
499                 }
500 #endif
501
502                 for (j = __pfn_to_highbits(start);
503                      j <= __pfn_to_highbits(end - 1); j++)
504                         highbits_to_node[j] = i;
505
506                 node_start_pfn[i] = start;
507                 node_end_pfn[i] = end;
508                 node_controller[i] = range.controller;
509                 physpages += size;
510                 max_pfn = end;
511
512                 /* Mark node as online */
513                 node_set(i, node_online_map);
514                 node_set(i, node_possible_map);
515         }
516
517 #ifndef __tilegx__
518         /*
519          * For 4KB pages, mem_map "struct page" data is 1% of the size
520          * of the physical memory, so can be quite big (640 MB for
521          * four 16G zones).  These structures must be mapped in
522          * lowmem, and since we currently cap out at about 768 MB,
523          * it's impractical to try to use this much address space.
524          * For now, arbitrarily cap the amount of physical memory
525          * we're willing to use at 8 million pages (32GB of 4KB pages).
526          */
527         cap = 8 * 1024 * 1024;  /* 8 million pages */
528         if (physpages > cap) {
529                 int num_nodes = num_online_nodes();
530                 int cap_each = cap / num_nodes;
531                 unsigned long dropped_pages = 0;
532                 for (i = 0; i < num_nodes; ++i) {
533                         int size = node_end_pfn[i] - node_start_pfn[i];
534                         if (size > cap_each) {
535                                 dropped_pages += (size - cap_each);
536                                 node_end_pfn[i] = node_start_pfn[i] + cap_each;
537                         }
538                 }
539                 physpages -= dropped_pages;
540                 pr_warning("Only using %ldMB memory;"
541                        " ignoring %ldMB.\n",
542                        physpages >> (20 - PAGE_SHIFT),
543                        dropped_pages >> (20 - PAGE_SHIFT));
544                 pr_warning("Consider using a larger page size.\n");
545         }
546 #endif
547
548         /* Heap starts just above the last loaded address. */
549         min_low_pfn = PFN_UP((unsigned long)_end - PAGE_OFFSET);
550
551 #ifdef CONFIG_HIGHMEM
552         /* Find where we map lowmem from each controller. */
553         high_memory = setup_pa_va_mapping();
554
555         /* Set max_low_pfn based on what node 0 can directly address. */
556         max_low_pfn = node_lowmem_end_pfn[0];
557
558         lowmem_pages = (mappable_physpages > MAXMEM_PFN) ?
559                 MAXMEM_PFN : mappable_physpages;
560         highmem_pages = (long) (physpages - lowmem_pages);
561
562         pr_notice("%ldMB HIGHMEM available.\n",
563                pages_to_mb(highmem_pages > 0 ? highmem_pages : 0));
564         pr_notice("%ldMB LOWMEM available.\n",
565                         pages_to_mb(lowmem_pages));
566 #else
567         /* Set max_low_pfn based on what node 0 can directly address. */
568         max_low_pfn = node_end_pfn[0];
569
570 #ifndef __tilegx__
571         if (node_end_pfn[0] > MAXMEM_PFN) {
572                 pr_warning("Only using %ldMB LOWMEM.\n",
573                        MAXMEM>>20);
574                 pr_warning("Use a HIGHMEM enabled kernel.\n");
575                 max_low_pfn = MAXMEM_PFN;
576                 max_pfn = MAXMEM_PFN;
577                 node_end_pfn[0] = MAXMEM_PFN;
578         } else {
579                 pr_notice("%ldMB memory available.\n",
580                        pages_to_mb(node_end_pfn[0]));
581         }
582         for (i = 1; i < MAX_NUMNODES; ++i) {
583                 node_start_pfn[i] = 0;
584                 node_end_pfn[i] = 0;
585         }
586         high_memory = __va(node_end_pfn[0]);
587 #else
588         lowmem_pages = 0;
589         for (i = 0; i < MAX_NUMNODES; ++i) {
590                 int pages = node_end_pfn[i] - node_start_pfn[i];
591                 lowmem_pages += pages;
592                 if (pages)
593                         high_memory = pfn_to_kaddr(node_end_pfn[i]);
594         }
595         pr_notice("%ldMB memory available.\n",
596                pages_to_mb(lowmem_pages));
597 #endif
598 #endif
599 }
600
601 /*
602  * On 32-bit machines, we only put bootmem on the low controller,
603  * since PAs > 4GB can't be used in bootmem.  In principle one could
604  * imagine, e.g., multiple 1 GB controllers all of which could support
605  * bootmem, but in practice using controllers this small isn't a
606  * particularly interesting scenario, so we just keep it simple and
607  * use only the first controller for bootmem on 32-bit machines.
608  */
609 static inline int node_has_bootmem(int nid)
610 {
611 #ifdef CONFIG_64BIT
612         return 1;
613 #else
614         return nid == 0;
615 #endif
616 }
617
618 static inline unsigned long alloc_bootmem_pfn(int nid,
619                                               unsigned long size,
620                                               unsigned long goal)
621 {
622         void *kva = __alloc_bootmem_node(NODE_DATA(nid), size,
623                                          PAGE_SIZE, goal);
624         unsigned long pfn = kaddr_to_pfn(kva);
625         BUG_ON(goal && PFN_PHYS(pfn) != goal);
626         return pfn;
627 }
628
629 static void __init setup_bootmem_allocator_node(int i)
630 {
631         unsigned long start, end, mapsize, mapstart;
632
633         if (node_has_bootmem(i)) {
634                 NODE_DATA(i)->bdata = &bootmem_node_data[i];
635         } else {
636                 /* Share controller zero's bdata for now. */
637                 NODE_DATA(i)->bdata = &bootmem_node_data[0];
638                 return;
639         }
640
641         /* Skip up to after the bss in node 0. */
642         start = (i == 0) ? min_low_pfn : node_start_pfn[i];
643
644         /* Only lowmem, if we're a HIGHMEM build. */
645 #ifdef CONFIG_HIGHMEM
646         end = node_lowmem_end_pfn[i];
647 #else
648         end = node_end_pfn[i];
649 #endif
650
651         /* No memory here. */
652         if (end == start)
653                 return;
654
655         /* Figure out where the bootmem bitmap is located. */
656         mapsize = bootmem_bootmap_pages(end - start);
657         if (i == 0) {
658                 /* Use some space right before the heap on node 0. */
659                 mapstart = start;
660                 start += mapsize;
661         } else {
662                 /* Allocate bitmap on node 0 to avoid page table issues. */
663                 mapstart = alloc_bootmem_pfn(0, PFN_PHYS(mapsize), 0);
664         }
665
666         /* Initialize a node. */
667         init_bootmem_node(NODE_DATA(i), mapstart, start, end);
668
669         /* Free all the space back into the allocator. */
670         free_bootmem(PFN_PHYS(start), PFN_PHYS(end - start));
671
672 #if defined(CONFIG_PCI) && !defined(__tilegx__)
673         /*
674          * Throw away any memory aliased by the PCI region.
675          */
676         if (pci_reserve_start_pfn < end && pci_reserve_end_pfn > start) {
677                 start = max(pci_reserve_start_pfn, start);
678                 end = min(pci_reserve_end_pfn, end);
679                 reserve_bootmem(PFN_PHYS(start), PFN_PHYS(end - start),
680                                 BOOTMEM_EXCLUSIVE);
681         }
682 #endif
683 }
684
685 static void __init setup_bootmem_allocator(void)
686 {
687         int i;
688         for (i = 0; i < MAX_NUMNODES; ++i)
689                 setup_bootmem_allocator_node(i);
690
691         /* Reserve any memory excluded by "memmap" arguments. */
692         for (i = 0; i < memmap_nr; ++i) {
693                 struct memmap_entry *m = &memmap_map[i];
694                 reserve_bootmem(m->addr, m->size, 0);
695         }
696
697 #ifdef CONFIG_KEXEC
698         if (crashk_res.start != crashk_res.end)
699                 reserve_bootmem(crashk_res.start, resource_size(&crashk_res), 0);
700 #endif
701 }
702
703 void *__init alloc_remap(int nid, unsigned long size)
704 {
705         int pages = node_end_pfn[nid] - node_start_pfn[nid];
706         void *map = pfn_to_kaddr(node_memmap_pfn[nid]);
707         BUG_ON(size != pages * sizeof(struct page));
708         memset(map, 0, size);
709         return map;
710 }
711
712 static int __init percpu_size(void)
713 {
714         int size = __per_cpu_end - __per_cpu_start;
715         size += PERCPU_MODULE_RESERVE;
716         size += PERCPU_DYNAMIC_EARLY_SIZE;
717         if (size < PCPU_MIN_UNIT_SIZE)
718                 size = PCPU_MIN_UNIT_SIZE;
719         size = roundup(size, PAGE_SIZE);
720
721         /* In several places we assume the per-cpu data fits on a huge page. */
722         BUG_ON(kdata_huge && size > HPAGE_SIZE);
723         return size;
724 }
725
726 static void __init zone_sizes_init(void)
727 {
728         unsigned long zones_size[MAX_NR_ZONES] = { 0 };
729         int size = percpu_size();
730         int num_cpus = smp_height * smp_width;
731         const unsigned long dma_end = (1UL << (32 - PAGE_SHIFT));
732
733         int i;
734
735         for (i = 0; i < num_cpus; ++i)
736                 node_percpu[cpu_to_node(i)] += size;
737
738         for_each_online_node(i) {
739                 unsigned long start = node_start_pfn[i];
740                 unsigned long end = node_end_pfn[i];
741 #ifdef CONFIG_HIGHMEM
742                 unsigned long lowmem_end = node_lowmem_end_pfn[i];
743 #else
744                 unsigned long lowmem_end = end;
745 #endif
746                 int memmap_size = (end - start) * sizeof(struct page);
747                 node_free_pfn[i] = start;
748
749                 /*
750                  * Set aside pages for per-cpu data and the mem_map array.
751                  *
752                  * Since the per-cpu data requires special homecaching,
753                  * if we are in kdata_huge mode, we put it at the end of
754                  * the lowmem region.  If we're not in kdata_huge mode,
755                  * we take the per-cpu pages from the bottom of the
756                  * controller, since that avoids fragmenting a huge page
757                  * that users might want.  We always take the memmap
758                  * from the bottom of the controller, since with
759                  * kdata_huge that lets it be under a huge TLB entry.
760                  *
761                  * If the user has requested isolnodes for a controller,
762                  * though, there'll be no lowmem, so we just alloc_bootmem
763                  * the memmap.  There will be no percpu memory either.
764                  */
765                 if (i != 0 && cpu_isset(i, isolnodes)) {
766                         node_memmap_pfn[i] =
767                                 alloc_bootmem_pfn(0, memmap_size, 0);
768                         BUG_ON(node_percpu[i] != 0);
769                 } else if (node_has_bootmem(start)) {
770                         unsigned long goal = 0;
771                         node_memmap_pfn[i] =
772                                 alloc_bootmem_pfn(i, memmap_size, 0);
773                         if (kdata_huge)
774                                 goal = PFN_PHYS(lowmem_end) - node_percpu[i];
775                         if (node_percpu[i])
776                                 node_percpu_pfn[i] =
777                                         alloc_bootmem_pfn(i, node_percpu[i],
778                                                           goal);
779                 } else {
780                         /* In non-bootmem zones, just reserve some pages. */
781                         node_memmap_pfn[i] = node_free_pfn[i];
782                         node_free_pfn[i] += PFN_UP(memmap_size);
783                         if (!kdata_huge) {
784                                 node_percpu_pfn[i] = node_free_pfn[i];
785                                 node_free_pfn[i] += PFN_UP(node_percpu[i]);
786                         } else {
787                                 node_percpu_pfn[i] =
788                                         lowmem_end - PFN_UP(node_percpu[i]);
789                         }
790                 }
791
792 #ifdef CONFIG_HIGHMEM
793                 if (start > lowmem_end) {
794                         zones_size[ZONE_NORMAL] = 0;
795                         zones_size[ZONE_HIGHMEM] = end - start;
796                 } else {
797                         zones_size[ZONE_NORMAL] = lowmem_end - start;
798                         zones_size[ZONE_HIGHMEM] = end - lowmem_end;
799                 }
800 #else
801                 zones_size[ZONE_NORMAL] = end - start;
802 #endif
803
804                 if (start < dma_end) {
805                         zones_size[ZONE_DMA] = min(zones_size[ZONE_NORMAL],
806                                                    dma_end - start);
807                         zones_size[ZONE_NORMAL] -= zones_size[ZONE_DMA];
808                 } else {
809                         zones_size[ZONE_DMA] = 0;
810                 }
811
812                 /* Take zone metadata from controller 0 if we're isolnode. */
813                 if (node_isset(i, isolnodes))
814                         NODE_DATA(i)->bdata = &bootmem_node_data[0];
815
816                 free_area_init_node(i, zones_size, start, NULL);
817                 printk(KERN_DEBUG "  Normal zone: %ld per-cpu pages\n",
818                        PFN_UP(node_percpu[i]));
819
820                 /* Track the type of memory on each node */
821                 if (zones_size[ZONE_NORMAL] || zones_size[ZONE_DMA])
822                         node_set_state(i, N_NORMAL_MEMORY);
823 #ifdef CONFIG_HIGHMEM
824                 if (end != start)
825                         node_set_state(i, N_HIGH_MEMORY);
826 #endif
827
828                 node_set_online(i);
829         }
830 }
831
832 #ifdef CONFIG_NUMA
833
834 /* which logical CPUs are on which nodes */
835 struct cpumask node_2_cpu_mask[MAX_NUMNODES] __write_once;
836 EXPORT_SYMBOL(node_2_cpu_mask);
837
838 /* which node each logical CPU is on */
839 char cpu_2_node[NR_CPUS] __write_once __attribute__((aligned(L2_CACHE_BYTES)));
840 EXPORT_SYMBOL(cpu_2_node);
841
842 /* Return cpu_to_node() except for cpus not yet assigned, which return -1 */
843 static int __init cpu_to_bound_node(int cpu, struct cpumask* unbound_cpus)
844 {
845         if (!cpu_possible(cpu) || cpumask_test_cpu(cpu, unbound_cpus))
846                 return -1;
847         else
848                 return cpu_to_node(cpu);
849 }
850
851 /* Return number of immediately-adjacent tiles sharing the same NUMA node. */
852 static int __init node_neighbors(int node, int cpu,
853                                  struct cpumask *unbound_cpus)
854 {
855         int neighbors = 0;
856         int w = smp_width;
857         int h = smp_height;
858         int x = cpu % w;
859         int y = cpu / w;
860         if (x > 0 && cpu_to_bound_node(cpu-1, unbound_cpus) == node)
861                 ++neighbors;
862         if (x < w-1 && cpu_to_bound_node(cpu+1, unbound_cpus) == node)
863                 ++neighbors;
864         if (y > 0 && cpu_to_bound_node(cpu-w, unbound_cpus) == node)
865                 ++neighbors;
866         if (y < h-1 && cpu_to_bound_node(cpu+w, unbound_cpus) == node)
867                 ++neighbors;
868         return neighbors;
869 }
870
871 static void __init setup_numa_mapping(void)
872 {
873         int distance[MAX_NUMNODES][NR_CPUS];
874         HV_Coord coord;
875         int cpu, node, cpus, i, x, y;
876         int num_nodes = num_online_nodes();
877         struct cpumask unbound_cpus;
878         nodemask_t default_nodes;
879
880         cpumask_clear(&unbound_cpus);
881
882         /* Get set of nodes we will use for defaults */
883         nodes_andnot(default_nodes, node_online_map, isolnodes);
884         if (nodes_empty(default_nodes)) {
885                 BUG_ON(!node_isset(0, node_online_map));
886                 pr_err("Forcing NUMA node zero available as a default node\n");
887                 node_set(0, default_nodes);
888         }
889
890         /* Populate the distance[] array */
891         memset(distance, -1, sizeof(distance));
892         cpu = 0;
893         for (coord.y = 0; coord.y < smp_height; ++coord.y) {
894                 for (coord.x = 0; coord.x < smp_width;
895                      ++coord.x, ++cpu) {
896                         BUG_ON(cpu >= nr_cpu_ids);
897                         if (!cpu_possible(cpu)) {
898                                 cpu_2_node[cpu] = -1;
899                                 continue;
900                         }
901                         for_each_node_mask(node, default_nodes) {
902                                 HV_MemoryControllerInfo info =
903                                         hv_inquire_memory_controller(
904                                                 coord, node_controller[node]);
905                                 distance[node][cpu] =
906                                         ABS(info.coord.x) + ABS(info.coord.y);
907                         }
908                         cpumask_set_cpu(cpu, &unbound_cpus);
909                 }
910         }
911         cpus = cpu;
912
913         /*
914          * Round-robin through the NUMA nodes until all the cpus are
915          * assigned.  We could be more clever here (e.g. create four
916          * sorted linked lists on the same set of cpu nodes, and pull
917          * off them in round-robin sequence, removing from all four
918          * lists each time) but given the relatively small numbers
919          * involved, O(n^2) seem OK for a one-time cost.
920          */
921         node = first_node(default_nodes);
922         while (!cpumask_empty(&unbound_cpus)) {
923                 int best_cpu = -1;
924                 int best_distance = INT_MAX;
925                 for (cpu = 0; cpu < cpus; ++cpu) {
926                         if (cpumask_test_cpu(cpu, &unbound_cpus)) {
927                                 /*
928                                  * Compute metric, which is how much
929                                  * closer the cpu is to this memory
930                                  * controller than the others, shifted
931                                  * up, and then the number of
932                                  * neighbors already in the node as an
933                                  * epsilon adjustment to try to keep
934                                  * the nodes compact.
935                                  */
936                                 int d = distance[node][cpu] * num_nodes;
937                                 for_each_node_mask(i, default_nodes) {
938                                         if (i != node)
939                                                 d -= distance[i][cpu];
940                                 }
941                                 d *= 8;  /* allow space for epsilon */
942                                 d -= node_neighbors(node, cpu, &unbound_cpus);
943                                 if (d < best_distance) {
944                                         best_cpu = cpu;
945                                         best_distance = d;
946                                 }
947                         }
948                 }
949                 BUG_ON(best_cpu < 0);
950                 cpumask_set_cpu(best_cpu, &node_2_cpu_mask[node]);
951                 cpu_2_node[best_cpu] = node;
952                 cpumask_clear_cpu(best_cpu, &unbound_cpus);
953                 node = next_node(node, default_nodes);
954                 if (node == MAX_NUMNODES)
955                         node = first_node(default_nodes);
956         }
957
958         /* Print out node assignments and set defaults for disabled cpus */
959         cpu = 0;
960         for (y = 0; y < smp_height; ++y) {
961                 printk(KERN_DEBUG "NUMA cpu-to-node row %d:", y);
962                 for (x = 0; x < smp_width; ++x, ++cpu) {
963                         if (cpu_to_node(cpu) < 0) {
964                                 pr_cont(" -");
965                                 cpu_2_node[cpu] = first_node(default_nodes);
966                         } else {
967                                 pr_cont(" %d", cpu_to_node(cpu));
968                         }
969                 }
970                 pr_cont("\n");
971         }
972 }
973
974 static struct cpu cpu_devices[NR_CPUS];
975
976 static int __init topology_init(void)
977 {
978         int i;
979
980         for_each_online_node(i)
981                 register_one_node(i);
982
983         for (i = 0; i < smp_height * smp_width; ++i)
984                 register_cpu(&cpu_devices[i], i);
985
986         return 0;
987 }
988
989 subsys_initcall(topology_init);
990
991 #else /* !CONFIG_NUMA */
992
993 #define setup_numa_mapping() do { } while (0)
994
995 #endif /* CONFIG_NUMA */
996
997 /*
998  * Initialize hugepage support on this cpu.  We do this on all cores
999  * early in boot: before argument parsing for the boot cpu, and after
1000  * argument parsing but before the init functions run on the secondaries.
1001  * So the values we set up here in the hypervisor may be overridden on
1002  * the boot cpu as arguments are parsed.
1003  */
1004 static __cpuinit void init_super_pages(void)
1005 {
1006 #ifdef CONFIG_HUGETLB_SUPER_PAGES
1007         int i;
1008         for (i = 0; i < HUGE_SHIFT_ENTRIES; ++i)
1009                 hv_set_pte_super_shift(i, huge_shift[i]);
1010 #endif
1011 }
1012
1013 /**
1014  * setup_cpu() - Do all necessary per-cpu, tile-specific initialization.
1015  * @boot: Is this the boot cpu?
1016  *
1017  * Called from setup_arch() on the boot cpu, or online_secondary().
1018  */
1019 void __cpuinit setup_cpu(int boot)
1020 {
1021         /* The boot cpu sets up its permanent mappings much earlier. */
1022         if (!boot)
1023                 store_permanent_mappings();
1024
1025         /* Allow asynchronous TLB interrupts. */
1026 #if CHIP_HAS_TILE_DMA()
1027         arch_local_irq_unmask(INT_DMATLB_MISS);
1028         arch_local_irq_unmask(INT_DMATLB_ACCESS);
1029 #endif
1030 #if CHIP_HAS_SN_PROC()
1031         arch_local_irq_unmask(INT_SNITLB_MISS);
1032 #endif
1033 #ifdef __tilegx__
1034         arch_local_irq_unmask(INT_SINGLE_STEP_K);
1035 #endif
1036
1037         /*
1038          * Allow user access to many generic SPRs, like the cycle
1039          * counter, PASS/FAIL/DONE, INTERRUPT_CRITICAL_SECTION, etc.
1040          */
1041         __insn_mtspr(SPR_MPL_WORLD_ACCESS_SET_0, 1);
1042
1043 #if CHIP_HAS_SN()
1044         /* Static network is not restricted. */
1045         __insn_mtspr(SPR_MPL_SN_ACCESS_SET_0, 1);
1046 #endif
1047 #if CHIP_HAS_SN_PROC()
1048         __insn_mtspr(SPR_MPL_SN_NOTIFY_SET_0, 1);
1049         __insn_mtspr(SPR_MPL_SN_CPL_SET_0, 1);
1050 #endif
1051
1052         /*
1053          * Set the MPL for interrupt control 0 & 1 to the corresponding
1054          * values.  This includes access to the SYSTEM_SAVE and EX_CONTEXT
1055          * SPRs, as well as the interrupt mask.
1056          */
1057         __insn_mtspr(SPR_MPL_INTCTRL_0_SET_0, 1);
1058         __insn_mtspr(SPR_MPL_INTCTRL_1_SET_1, 1);
1059
1060         /* Initialize IRQ support for this cpu. */
1061         setup_irq_regs();
1062
1063 #ifdef CONFIG_HARDWALL
1064         /* Reset the network state on this cpu. */
1065         reset_network_state();
1066 #endif
1067
1068         init_super_pages();
1069 }
1070
1071 #ifdef CONFIG_BLK_DEV_INITRD
1072
1073 static int __initdata set_initramfs_file;
1074 static char __initdata initramfs_file[128] = "initramfs";
1075
1076 static int __init setup_initramfs_file(char *str)
1077 {
1078         if (str == NULL)
1079                 return -EINVAL;
1080         strncpy(initramfs_file, str, sizeof(initramfs_file) - 1);
1081         set_initramfs_file = 1;
1082
1083         return 0;
1084 }
1085 early_param("initramfs_file", setup_initramfs_file);
1086
1087 /*
1088  * We look for a file called "initramfs" in the hvfs.  If there is one, we
1089  * allocate some memory for it and it will be unpacked to the initramfs.
1090  * If it's compressed, the initd code will uncompress it first.
1091  */
1092 static void __init load_hv_initrd(void)
1093 {
1094         HV_FS_StatInfo stat;
1095         int fd, rc;
1096         void *initrd;
1097
1098         fd = hv_fs_findfile((HV_VirtAddr) initramfs_file);
1099         if (fd == HV_ENOENT) {
1100                 if (set_initramfs_file) {
1101                         pr_warning("No such hvfs initramfs file '%s'\n",
1102                                    initramfs_file);
1103                         return;
1104                 } else {
1105                         /* Try old backwards-compatible name. */
1106                         fd = hv_fs_findfile((HV_VirtAddr)"initramfs.cpio.gz");
1107                         if (fd == HV_ENOENT)
1108                                 return;
1109                 }
1110         }
1111         BUG_ON(fd < 0);
1112         stat = hv_fs_fstat(fd);
1113         BUG_ON(stat.size < 0);
1114         if (stat.flags & HV_FS_ISDIR) {
1115                 pr_warning("Ignoring hvfs file '%s': it's a directory.\n",
1116                            initramfs_file);
1117                 return;
1118         }
1119         initrd = alloc_bootmem_pages(stat.size);
1120         rc = hv_fs_pread(fd, (HV_VirtAddr) initrd, stat.size, 0);
1121         if (rc != stat.size) {
1122                 pr_err("Error reading %d bytes from hvfs file '%s': %d\n",
1123                        stat.size, initramfs_file, rc);
1124                 free_initrd_mem((unsigned long) initrd, stat.size);
1125                 return;
1126         }
1127         initrd_start = (unsigned long) initrd;
1128         initrd_end = initrd_start + stat.size;
1129 }
1130
1131 void __init free_initrd_mem(unsigned long begin, unsigned long end)
1132 {
1133         free_bootmem(__pa(begin), end - begin);
1134 }
1135
1136 #else
1137 static inline void load_hv_initrd(void) {}
1138 #endif /* CONFIG_BLK_DEV_INITRD */
1139
1140 static void __init validate_hv(void)
1141 {
1142         /*
1143          * It may already be too late, but let's check our built-in
1144          * configuration against what the hypervisor is providing.
1145          */
1146         unsigned long glue_size = hv_sysconf(HV_SYSCONF_GLUE_SIZE);
1147         int hv_page_size = hv_sysconf(HV_SYSCONF_PAGE_SIZE_SMALL);
1148         int hv_hpage_size = hv_sysconf(HV_SYSCONF_PAGE_SIZE_LARGE);
1149         HV_ASIDRange asid_range;
1150
1151 #ifndef CONFIG_SMP
1152         HV_Topology topology = hv_inquire_topology();
1153         BUG_ON(topology.coord.x != 0 || topology.coord.y != 0);
1154         if (topology.width != 1 || topology.height != 1) {
1155                 pr_warning("Warning: booting UP kernel on %dx%d grid;"
1156                            " will ignore all but first tile.\n",
1157                            topology.width, topology.height);
1158         }
1159 #endif
1160
1161         if (PAGE_OFFSET + HV_GLUE_START_CPA + glue_size > (unsigned long)_text)
1162                 early_panic("Hypervisor glue size %ld is too big!\n",
1163                             glue_size);
1164         if (hv_page_size != PAGE_SIZE)
1165                 early_panic("Hypervisor page size %#x != our %#lx\n",
1166                             hv_page_size, PAGE_SIZE);
1167         if (hv_hpage_size != HPAGE_SIZE)
1168                 early_panic("Hypervisor huge page size %#x != our %#lx\n",
1169                             hv_hpage_size, HPAGE_SIZE);
1170
1171 #ifdef CONFIG_SMP
1172         /*
1173          * Some hypervisor APIs take a pointer to a bitmap array
1174          * whose size is at least the number of cpus on the chip.
1175          * We use a struct cpumask for this, so it must be big enough.
1176          */
1177         if ((smp_height * smp_width) > nr_cpu_ids)
1178                 early_panic("Hypervisor %d x %d grid too big for Linux"
1179                             " NR_CPUS %d\n", smp_height, smp_width,
1180                             nr_cpu_ids);
1181 #endif
1182
1183         /*
1184          * Check that we're using allowed ASIDs, and initialize the
1185          * various asid variables to their appropriate initial states.
1186          */
1187         asid_range = hv_inquire_asid(0);
1188         __get_cpu_var(current_asid) = min_asid = asid_range.start;
1189         max_asid = asid_range.start + asid_range.size - 1;
1190
1191         if (hv_confstr(HV_CONFSTR_CHIP_MODEL, (HV_VirtAddr)chip_model,
1192                        sizeof(chip_model)) < 0) {
1193                 pr_err("Warning: HV_CONFSTR_CHIP_MODEL not available\n");
1194                 strlcpy(chip_model, "unknown", sizeof(chip_model));
1195         }
1196 }
1197
1198 static void __init validate_va(void)
1199 {
1200 #ifndef __tilegx__   /* FIXME: GX: probably some validation relevant here */
1201         /*
1202          * Similarly, make sure we're only using allowed VAs.
1203          * We assume we can contiguously use MEM_USER_INTRPT .. MEM_HV_INTRPT,
1204          * and 0 .. KERNEL_HIGH_VADDR.
1205          * In addition, make sure we CAN'T use the end of memory, since
1206          * we use the last chunk of each pgd for the pgd_list.
1207          */
1208         int i, user_kernel_ok = 0;
1209         unsigned long max_va = 0;
1210         unsigned long list_va =
1211                 ((PGD_LIST_OFFSET / sizeof(pgd_t)) << PGDIR_SHIFT);
1212
1213         for (i = 0; ; ++i) {
1214                 HV_VirtAddrRange range = hv_inquire_virtual(i);
1215                 if (range.size == 0)
1216                         break;
1217                 if (range.start <= MEM_USER_INTRPT &&
1218                     range.start + range.size >= MEM_HV_INTRPT)
1219                         user_kernel_ok = 1;
1220                 if (range.start == 0)
1221                         max_va = range.size;
1222                 BUG_ON(range.start + range.size > list_va);
1223         }
1224         if (!user_kernel_ok)
1225                 early_panic("Hypervisor not configured for user/kernel VAs\n");
1226         if (max_va == 0)
1227                 early_panic("Hypervisor not configured for low VAs\n");
1228         if (max_va < KERNEL_HIGH_VADDR)
1229                 early_panic("Hypervisor max VA %#lx smaller than %#lx\n",
1230                             max_va, KERNEL_HIGH_VADDR);
1231
1232         /* Kernel PCs must have their high bit set; see intvec.S. */
1233         if ((long)VMALLOC_START >= 0)
1234                 early_panic(
1235                         "Linux VMALLOC region below the 2GB line (%#lx)!\n"
1236                         "Reconfigure the kernel with fewer NR_HUGE_VMAPS\n"
1237                         "or smaller VMALLOC_RESERVE.\n",
1238                         VMALLOC_START);
1239 #endif
1240 }
1241
1242 /*
1243  * cpu_lotar_map lists all the cpus that are valid for the supervisor
1244  * to cache data on at a page level, i.e. what cpus can be placed in
1245  * the LOTAR field of a PTE.  It is equivalent to the set of possible
1246  * cpus plus any other cpus that are willing to share their cache.
1247  * It is set by hv_inquire_tiles(HV_INQ_TILES_LOTAR).
1248  */
1249 struct cpumask __write_once cpu_lotar_map;
1250 EXPORT_SYMBOL(cpu_lotar_map);
1251
1252 #if CHIP_HAS_CBOX_HOME_MAP()
1253 /*
1254  * hash_for_home_map lists all the tiles that hash-for-home data
1255  * will be cached on.  Note that this may includes tiles that are not
1256  * valid for this supervisor to use otherwise (e.g. if a hypervisor
1257  * device is being shared between multiple supervisors).
1258  * It is set by hv_inquire_tiles(HV_INQ_TILES_HFH_CACHE).
1259  */
1260 struct cpumask hash_for_home_map;
1261 EXPORT_SYMBOL(hash_for_home_map);
1262 #endif
1263
1264 /*
1265  * cpu_cacheable_map lists all the cpus whose caches the hypervisor can
1266  * flush on our behalf.  It is set to cpu_possible_mask OR'ed with
1267  * hash_for_home_map, and it is what should be passed to
1268  * hv_flush_remote() to flush all caches.  Note that if there are
1269  * dedicated hypervisor driver tiles that have authorized use of their
1270  * cache, those tiles will only appear in cpu_lotar_map, NOT in
1271  * cpu_cacheable_map, as they are a special case.
1272  */
1273 struct cpumask __write_once cpu_cacheable_map;
1274 EXPORT_SYMBOL(cpu_cacheable_map);
1275
1276 static __initdata struct cpumask disabled_map;
1277
1278 static int __init disabled_cpus(char *str)
1279 {
1280         int boot_cpu = smp_processor_id();
1281
1282         if (str == NULL || cpulist_parse_crop(str, &disabled_map) != 0)
1283                 return -EINVAL;
1284         if (cpumask_test_cpu(boot_cpu, &disabled_map)) {
1285                 pr_err("disabled_cpus: can't disable boot cpu %d\n", boot_cpu);
1286                 cpumask_clear_cpu(boot_cpu, &disabled_map);
1287         }
1288         return 0;
1289 }
1290
1291 early_param("disabled_cpus", disabled_cpus);
1292
1293 void __init print_disabled_cpus(void)
1294 {
1295         if (!cpumask_empty(&disabled_map)) {
1296                 char buf[100];
1297                 cpulist_scnprintf(buf, sizeof(buf), &disabled_map);
1298                 pr_info("CPUs not available for Linux: %s\n", buf);
1299         }
1300 }
1301
1302 static void __init setup_cpu_maps(void)
1303 {
1304         struct cpumask hv_disabled_map, cpu_possible_init;
1305         int boot_cpu = smp_processor_id();
1306         int cpus, i, rc;
1307
1308         /* Learn which cpus are allowed by the hypervisor. */
1309         rc = hv_inquire_tiles(HV_INQ_TILES_AVAIL,
1310                               (HV_VirtAddr) cpumask_bits(&cpu_possible_init),
1311                               sizeof(cpu_cacheable_map));
1312         if (rc < 0)
1313                 early_panic("hv_inquire_tiles(AVAIL) failed: rc %d\n", rc);
1314         if (!cpumask_test_cpu(boot_cpu, &cpu_possible_init))
1315                 early_panic("Boot CPU %d disabled by hypervisor!\n", boot_cpu);
1316
1317         /* Compute the cpus disabled by the hvconfig file. */
1318         cpumask_complement(&hv_disabled_map, &cpu_possible_init);
1319
1320         /* Include them with the cpus disabled by "disabled_cpus". */
1321         cpumask_or(&disabled_map, &disabled_map, &hv_disabled_map);
1322
1323         /*
1324          * Disable every cpu after "setup_max_cpus".  But don't mark
1325          * as disabled the cpus that are outside of our initial rectangle,
1326          * since that turns out to be confusing.
1327          */
1328         cpus = 1;                          /* this cpu */
1329         cpumask_set_cpu(boot_cpu, &disabled_map);   /* ignore this cpu */
1330         for (i = 0; cpus < setup_max_cpus; ++i)
1331                 if (!cpumask_test_cpu(i, &disabled_map))
1332                         ++cpus;
1333         for (; i < smp_height * smp_width; ++i)
1334                 cpumask_set_cpu(i, &disabled_map);
1335         cpumask_clear_cpu(boot_cpu, &disabled_map); /* reset this cpu */
1336         for (i = smp_height * smp_width; i < NR_CPUS; ++i)
1337                 cpumask_clear_cpu(i, &disabled_map);
1338
1339         /*
1340          * Setup cpu_possible map as every cpu allocated to us, minus
1341          * the results of any "disabled_cpus" settings.
1342          */
1343         cpumask_andnot(&cpu_possible_init, &cpu_possible_init, &disabled_map);
1344         init_cpu_possible(&cpu_possible_init);
1345
1346         /* Learn which cpus are valid for LOTAR caching. */
1347         rc = hv_inquire_tiles(HV_INQ_TILES_LOTAR,
1348                               (HV_VirtAddr) cpumask_bits(&cpu_lotar_map),
1349                               sizeof(cpu_lotar_map));
1350         if (rc < 0) {
1351                 pr_err("warning: no HV_INQ_TILES_LOTAR; using AVAIL\n");
1352                 cpu_lotar_map = *cpu_possible_mask;
1353         }
1354
1355 #if CHIP_HAS_CBOX_HOME_MAP()
1356         /* Retrieve set of CPUs used for hash-for-home caching */
1357         rc = hv_inquire_tiles(HV_INQ_TILES_HFH_CACHE,
1358                               (HV_VirtAddr) hash_for_home_map.bits,
1359                               sizeof(hash_for_home_map));
1360         if (rc < 0)
1361                 early_panic("hv_inquire_tiles(HFH_CACHE) failed: rc %d\n", rc);
1362         cpumask_or(&cpu_cacheable_map, cpu_possible_mask, &hash_for_home_map);
1363 #else
1364         cpu_cacheable_map = *cpu_possible_mask;
1365 #endif
1366 }
1367
1368
1369 static int __init dataplane(char *str)
1370 {
1371         pr_warning("WARNING: dataplane support disabled in this kernel\n");
1372         return 0;
1373 }
1374
1375 early_param("dataplane", dataplane);
1376
1377 #ifdef CONFIG_CMDLINE_BOOL
1378 static char __initdata builtin_cmdline[COMMAND_LINE_SIZE] = CONFIG_CMDLINE;
1379 #endif
1380
1381 void __init setup_arch(char **cmdline_p)
1382 {
1383         int len;
1384
1385 #if defined(CONFIG_CMDLINE_BOOL) && defined(CONFIG_CMDLINE_OVERRIDE)
1386         len = hv_get_command_line((HV_VirtAddr) boot_command_line,
1387                                   COMMAND_LINE_SIZE);
1388         if (boot_command_line[0])
1389                 pr_warning("WARNING: ignoring dynamic command line \"%s\"\n",
1390                            boot_command_line);
1391         strlcpy(boot_command_line, builtin_cmdline, COMMAND_LINE_SIZE);
1392 #else
1393         char *hv_cmdline;
1394 #if defined(CONFIG_CMDLINE_BOOL)
1395         if (builtin_cmdline[0]) {
1396                 int builtin_len = strlcpy(boot_command_line, builtin_cmdline,
1397                                           COMMAND_LINE_SIZE);
1398                 if (builtin_len < COMMAND_LINE_SIZE-1)
1399                         boot_command_line[builtin_len++] = ' ';
1400                 hv_cmdline = &boot_command_line[builtin_len];
1401                 len = COMMAND_LINE_SIZE - builtin_len;
1402         } else
1403 #endif
1404         {
1405                 hv_cmdline = boot_command_line;
1406                 len = COMMAND_LINE_SIZE;
1407         }
1408         len = hv_get_command_line((HV_VirtAddr) hv_cmdline, len);
1409         if (len < 0 || len > COMMAND_LINE_SIZE)
1410                 early_panic("hv_get_command_line failed: %d\n", len);
1411 #endif
1412
1413         *cmdline_p = boot_command_line;
1414
1415         /* Set disabled_map and setup_max_cpus very early */
1416         parse_early_param();
1417
1418         /* Make sure the kernel is compatible with the hypervisor. */
1419         validate_hv();
1420         validate_va();
1421
1422         setup_cpu_maps();
1423
1424
1425 #if defined(CONFIG_PCI) && !defined(__tilegx__)
1426         /*
1427          * Initialize the PCI structures.  This is done before memory
1428          * setup so that we know whether or not a pci_reserve region
1429          * is necessary.
1430          */
1431         if (tile_pci_init() == 0)
1432                 pci_reserve_mb = 0;
1433
1434         /* PCI systems reserve a region just below 4GB for mapping iomem. */
1435         pci_reserve_end_pfn  = (1 << (32 - PAGE_SHIFT));
1436         pci_reserve_start_pfn = pci_reserve_end_pfn -
1437                 (pci_reserve_mb << (20 - PAGE_SHIFT));
1438 #endif
1439
1440         init_mm.start_code = (unsigned long) _text;
1441         init_mm.end_code = (unsigned long) _etext;
1442         init_mm.end_data = (unsigned long) _edata;
1443         init_mm.brk = (unsigned long) _end;
1444
1445         setup_memory();
1446         store_permanent_mappings();
1447         setup_bootmem_allocator();
1448
1449         /*
1450          * NOTE: before this point _nobody_ is allowed to allocate
1451          * any memory using the bootmem allocator.
1452          */
1453
1454 #ifdef CONFIG_SWIOTLB
1455         swiotlb_init(0);
1456 #endif
1457
1458         paging_init();
1459         setup_numa_mapping();
1460         zone_sizes_init();
1461         set_page_homes();
1462         setup_cpu(1);
1463         setup_clock();
1464         load_hv_initrd();
1465 }
1466
1467
1468 /*
1469  * Set up per-cpu memory.
1470  */
1471
1472 unsigned long __per_cpu_offset[NR_CPUS] __write_once;
1473 EXPORT_SYMBOL(__per_cpu_offset);
1474
1475 static size_t __initdata pfn_offset[MAX_NUMNODES] = { 0 };
1476 static unsigned long __initdata percpu_pfn[NR_CPUS] = { 0 };
1477
1478 /*
1479  * As the percpu code allocates pages, we return the pages from the
1480  * end of the node for the specified cpu.
1481  */
1482 static void *__init pcpu_fc_alloc(unsigned int cpu, size_t size, size_t align)
1483 {
1484         int nid = cpu_to_node(cpu);
1485         unsigned long pfn = node_percpu_pfn[nid] + pfn_offset[nid];
1486
1487         BUG_ON(size % PAGE_SIZE != 0);
1488         pfn_offset[nid] += size / PAGE_SIZE;
1489         BUG_ON(node_percpu[nid] < size);
1490         node_percpu[nid] -= size;
1491         if (percpu_pfn[cpu] == 0)
1492                 percpu_pfn[cpu] = pfn;
1493         return pfn_to_kaddr(pfn);
1494 }
1495
1496 /*
1497  * Pages reserved for percpu memory are not freeable, and in any case we are
1498  * on a short path to panic() in setup_per_cpu_area() at this point anyway.
1499  */
1500 static void __init pcpu_fc_free(void *ptr, size_t size)
1501 {
1502 }
1503
1504 /*
1505  * Set up vmalloc page tables using bootmem for the percpu code.
1506  */
1507 static void __init pcpu_fc_populate_pte(unsigned long addr)
1508 {
1509         pgd_t *pgd;
1510         pud_t *pud;
1511         pmd_t *pmd;
1512         pte_t *pte;
1513
1514         BUG_ON(pgd_addr_invalid(addr));
1515         if (addr < VMALLOC_START || addr >= VMALLOC_END)
1516                 panic("PCPU addr %#lx outside vmalloc range %#lx..%#lx;"
1517                       " try increasing CONFIG_VMALLOC_RESERVE\n",
1518                       addr, VMALLOC_START, VMALLOC_END);
1519
1520         pgd = swapper_pg_dir + pgd_index(addr);
1521         pud = pud_offset(pgd, addr);
1522         BUG_ON(!pud_present(*pud));
1523         pmd = pmd_offset(pud, addr);
1524         if (pmd_present(*pmd)) {
1525                 BUG_ON(pmd_huge_page(*pmd));
1526         } else {
1527                 pte = __alloc_bootmem(L2_KERNEL_PGTABLE_SIZE,
1528                                       HV_PAGE_TABLE_ALIGN, 0);
1529                 pmd_populate_kernel(&init_mm, pmd, pte);
1530         }
1531 }
1532
1533 void __init setup_per_cpu_areas(void)
1534 {
1535         struct page *pg;
1536         unsigned long delta, pfn, lowmem_va;
1537         unsigned long size = percpu_size();
1538         char *ptr;
1539         int rc, cpu, i;
1540
1541         rc = pcpu_page_first_chunk(PERCPU_MODULE_RESERVE, pcpu_fc_alloc,
1542                                    pcpu_fc_free, pcpu_fc_populate_pte);
1543         if (rc < 0)
1544                 panic("Cannot initialize percpu area (err=%d)", rc);
1545
1546         delta = (unsigned long)pcpu_base_addr - (unsigned long)__per_cpu_start;
1547         for_each_possible_cpu(cpu) {
1548                 __per_cpu_offset[cpu] = delta + pcpu_unit_offsets[cpu];
1549
1550                 /* finv the copy out of cache so we can change homecache */
1551                 ptr = pcpu_base_addr + pcpu_unit_offsets[cpu];
1552                 __finv_buffer(ptr, size);
1553                 pfn = percpu_pfn[cpu];
1554
1555                 /* Rewrite the page tables to cache on that cpu */
1556                 pg = pfn_to_page(pfn);
1557                 for (i = 0; i < size; i += PAGE_SIZE, ++pfn, ++pg) {
1558
1559                         /* Update the vmalloc mapping and page home. */
1560                         unsigned long addr = (unsigned long)ptr + i;
1561                         pte_t *ptep = virt_to_pte(NULL, addr);
1562                         pte_t pte = *ptep;
1563                         BUG_ON(pfn != pte_pfn(pte));
1564                         pte = hv_pte_set_mode(pte, HV_PTE_MODE_CACHE_TILE_L3);
1565                         pte = set_remote_cache_cpu(pte, cpu);
1566                         set_pte_at(&init_mm, addr, ptep, pte);
1567
1568                         /* Update the lowmem mapping for consistency. */
1569                         lowmem_va = (unsigned long)pfn_to_kaddr(pfn);
1570                         ptep = virt_to_pte(NULL, lowmem_va);
1571                         if (pte_huge(*ptep)) {
1572                                 printk(KERN_DEBUG "early shatter of huge page"
1573                                        " at %#lx\n", lowmem_va);
1574                                 shatter_pmd((pmd_t *)ptep);
1575                                 ptep = virt_to_pte(NULL, lowmem_va);
1576                                 BUG_ON(pte_huge(*ptep));
1577                         }
1578                         BUG_ON(pfn != pte_pfn(*ptep));
1579                         set_pte_at(&init_mm, lowmem_va, ptep, pte);
1580                 }
1581         }
1582
1583         /* Set our thread pointer appropriately. */
1584         set_my_cpu_offset(__per_cpu_offset[smp_processor_id()]);
1585
1586         /* Make sure the finv's have completed. */
1587         mb_incoherent();
1588
1589         /* Flush the TLB so we reference it properly from here on out. */
1590         local_flush_tlb_all();
1591 }
1592
1593 static struct resource data_resource = {
1594         .name   = "Kernel data",
1595         .start  = 0,
1596         .end    = 0,
1597         .flags  = IORESOURCE_BUSY | IORESOURCE_MEM
1598 };
1599
1600 static struct resource code_resource = {
1601         .name   = "Kernel code",
1602         .start  = 0,
1603         .end    = 0,
1604         .flags  = IORESOURCE_BUSY | IORESOURCE_MEM
1605 };
1606
1607 /*
1608  * On Pro, we reserve all resources above 4GB so that PCI won't try to put
1609  * mappings above 4GB.
1610  */
1611 #if defined(CONFIG_PCI) && !defined(__tilegx__)
1612 static struct resource* __init
1613 insert_non_bus_resource(void)
1614 {
1615         struct resource *res =
1616                 kzalloc(sizeof(struct resource), GFP_ATOMIC);
1617         res->name = "Non-Bus Physical Address Space";
1618         res->start = (1ULL << 32);
1619         res->end = -1LL;
1620         res->flags = IORESOURCE_BUSY | IORESOURCE_MEM;
1621         if (insert_resource(&iomem_resource, res)) {
1622                 kfree(res);
1623                 return NULL;
1624         }
1625         return res;
1626 }
1627 #endif
1628
1629 static struct resource* __init
1630 insert_ram_resource(u64 start_pfn, u64 end_pfn, bool reserved)
1631 {
1632         struct resource *res =
1633                 kzalloc(sizeof(struct resource), GFP_ATOMIC);
1634         res->name = reserved ? "Reserved" : "System RAM";
1635         res->start = start_pfn << PAGE_SHIFT;
1636         res->end = (end_pfn << PAGE_SHIFT) - 1;
1637         res->flags = IORESOURCE_BUSY | IORESOURCE_MEM;
1638         if (insert_resource(&iomem_resource, res)) {
1639                 kfree(res);
1640                 return NULL;
1641         }
1642         return res;
1643 }
1644
1645 /*
1646  * Request address space for all standard resources
1647  *
1648  * If the system includes PCI root complex drivers, we need to create
1649  * a window just below 4GB where PCI BARs can be mapped.
1650  */
1651 static int __init request_standard_resources(void)
1652 {
1653         int i;
1654         enum { CODE_DELTA = MEM_SV_INTRPT - PAGE_OFFSET };
1655
1656 #if defined(CONFIG_PCI) && !defined(__tilegx__)
1657         insert_non_bus_resource();
1658 #endif
1659
1660         for_each_online_node(i) {
1661                 u64 start_pfn = node_start_pfn[i];
1662                 u64 end_pfn = node_end_pfn[i];
1663
1664 #if defined(CONFIG_PCI) && !defined(__tilegx__)
1665                 if (start_pfn <= pci_reserve_start_pfn &&
1666                     end_pfn > pci_reserve_start_pfn) {
1667                         if (end_pfn > pci_reserve_end_pfn)
1668                                 insert_ram_resource(pci_reserve_end_pfn,
1669                                                     end_pfn, 0);
1670                         end_pfn = pci_reserve_start_pfn;
1671                 }
1672 #endif
1673                 insert_ram_resource(start_pfn, end_pfn, 0);
1674         }
1675
1676         code_resource.start = __pa(_text - CODE_DELTA);
1677         code_resource.end = __pa(_etext - CODE_DELTA)-1;
1678         data_resource.start = __pa(_sdata);
1679         data_resource.end = __pa(_end)-1;
1680
1681         insert_resource(&iomem_resource, &code_resource);
1682         insert_resource(&iomem_resource, &data_resource);
1683
1684         /* Mark any "memmap" regions busy for the resource manager. */
1685         for (i = 0; i < memmap_nr; ++i) {
1686                 struct memmap_entry *m = &memmap_map[i];
1687                 insert_ram_resource(PFN_DOWN(m->addr),
1688                                     PFN_UP(m->addr + m->size - 1), 1);
1689         }
1690
1691 #ifdef CONFIG_KEXEC
1692         insert_resource(&iomem_resource, &crashk_res);
1693 #endif
1694
1695         return 0;
1696 }
1697
1698 subsys_initcall(request_standard_resources);