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