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