Mention branches and keyring.
[releases.git] / platforms / pseries / lpar.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * pSeries_lpar.c
4  * Copyright (C) 2001 Todd Inglett, IBM Corporation
5  *
6  * pSeries LPAR support.
7  */
8
9 /* Enables debugging of low-level hash table routines - careful! */
10 #undef DEBUG
11 #define pr_fmt(fmt) "lpar: " fmt
12
13 #include <linux/kernel.h>
14 #include <linux/dma-mapping.h>
15 #include <linux/console.h>
16 #include <linux/export.h>
17 #include <linux/jump_label.h>
18 #include <linux/delay.h>
19 #include <linux/stop_machine.h>
20 #include <linux/spinlock.h>
21 #include <linux/cpuhotplug.h>
22 #include <linux/workqueue.h>
23 #include <linux/proc_fs.h>
24 #include <linux/pgtable.h>
25 #include <linux/debugfs.h>
26
27 #include <asm/processor.h>
28 #include <asm/mmu.h>
29 #include <asm/page.h>
30 #include <asm/setup.h>
31 #include <asm/mmu_context.h>
32 #include <asm/iommu.h>
33 #include <asm/tlb.h>
34 #include <asm/cputable.h>
35 #include <asm/papr-sysparm.h>
36 #include <asm/udbg.h>
37 #include <asm/smp.h>
38 #include <asm/trace.h>
39 #include <asm/firmware.h>
40 #include <asm/plpar_wrappers.h>
41 #include <asm/kexec.h>
42 #include <asm/fadump.h>
43 #include <asm/dtl.h>
44
45 #include "pseries.h"
46
47 /* Flag bits for H_BULK_REMOVE */
48 #define HBR_REQUEST     0x4000000000000000UL
49 #define HBR_RESPONSE    0x8000000000000000UL
50 #define HBR_END         0xc000000000000000UL
51 #define HBR_AVPN        0x0200000000000000UL
52 #define HBR_ANDCOND     0x0100000000000000UL
53
54
55 /* in hvCall.S */
56 EXPORT_SYMBOL(plpar_hcall);
57 EXPORT_SYMBOL(plpar_hcall9);
58 EXPORT_SYMBOL(plpar_hcall_norets);
59
60 #ifdef CONFIG_PPC_64S_HASH_MMU
61 /*
62  * H_BLOCK_REMOVE supported block size for this page size in segment who's base
63  * page size is that page size.
64  *
65  * The first index is the segment base page size, the second one is the actual
66  * page size.
67  */
68 static int hblkrm_size[MMU_PAGE_COUNT][MMU_PAGE_COUNT] __ro_after_init;
69 #endif
70
71 /*
72  * Due to the involved complexity, and that the current hypervisor is only
73  * returning this value or 0, we are limiting the support of the H_BLOCK_REMOVE
74  * buffer size to 8 size block.
75  */
76 #define HBLKRM_SUPPORTED_BLOCK_SIZE 8
77
78 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
79 static u8 dtl_mask = DTL_LOG_PREEMPT;
80 #else
81 static u8 dtl_mask;
82 #endif
83
84 void alloc_dtl_buffers(unsigned long *time_limit)
85 {
86         int cpu;
87         struct paca_struct *pp;
88         struct dtl_entry *dtl;
89
90         for_each_possible_cpu(cpu) {
91                 pp = paca_ptrs[cpu];
92                 if (pp->dispatch_log)
93                         continue;
94                 dtl = kmem_cache_alloc(dtl_cache, GFP_KERNEL);
95                 if (!dtl) {
96                         pr_warn("Failed to allocate dispatch trace log for cpu %d\n",
97                                 cpu);
98 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
99                         pr_warn("Stolen time statistics will be unreliable\n");
100 #endif
101                         break;
102                 }
103
104                 pp->dtl_ridx = 0;
105                 pp->dispatch_log = dtl;
106                 pp->dispatch_log_end = dtl + N_DISPATCH_LOG;
107                 pp->dtl_curr = dtl;
108
109                 if (time_limit && time_after(jiffies, *time_limit)) {
110                         cond_resched();
111                         *time_limit = jiffies + HZ;
112                 }
113         }
114 }
115
116 void register_dtl_buffer(int cpu)
117 {
118         long ret;
119         struct paca_struct *pp;
120         struct dtl_entry *dtl;
121         int hwcpu = get_hard_smp_processor_id(cpu);
122
123         pp = paca_ptrs[cpu];
124         dtl = pp->dispatch_log;
125         if (dtl && dtl_mask) {
126                 pp->dtl_ridx = 0;
127                 pp->dtl_curr = dtl;
128                 lppaca_of(cpu).dtl_idx = 0;
129
130                 /* hypervisor reads buffer length from this field */
131                 dtl->enqueue_to_dispatch_time = cpu_to_be32(DISPATCH_LOG_BYTES);
132                 ret = register_dtl(hwcpu, __pa(dtl));
133                 if (ret)
134                         pr_err("WARNING: DTL registration of cpu %d (hw %d) failed with %ld\n",
135                                cpu, hwcpu, ret);
136
137                 lppaca_of(cpu).dtl_enable_mask = dtl_mask;
138         }
139 }
140
141 #ifdef CONFIG_PPC_SPLPAR
142 struct dtl_worker {
143         struct delayed_work work;
144         int cpu;
145 };
146
147 struct vcpu_dispatch_data {
148         int last_disp_cpu;
149
150         int total_disp;
151
152         int same_cpu_disp;
153         int same_chip_disp;
154         int diff_chip_disp;
155         int far_chip_disp;
156
157         int numa_home_disp;
158         int numa_remote_disp;
159         int numa_far_disp;
160 };
161
162 /*
163  * This represents the number of cpus in the hypervisor. Since there is no
164  * architected way to discover the number of processors in the host, we
165  * provision for dealing with NR_CPUS. This is currently 2048 by default, and
166  * is sufficient for our purposes. This will need to be tweaked if
167  * CONFIG_NR_CPUS is changed.
168  */
169 #define NR_CPUS_H       NR_CPUS
170
171 DEFINE_RWLOCK(dtl_access_lock);
172 static DEFINE_PER_CPU(struct vcpu_dispatch_data, vcpu_disp_data);
173 static DEFINE_PER_CPU(u64, dtl_entry_ridx);
174 static DEFINE_PER_CPU(struct dtl_worker, dtl_workers);
175 static enum cpuhp_state dtl_worker_state;
176 static DEFINE_MUTEX(dtl_enable_mutex);
177 static int vcpudispatch_stats_on __read_mostly;
178 static int vcpudispatch_stats_freq = 50;
179 static __be32 *vcpu_associativity, *pcpu_associativity;
180
181
182 static void free_dtl_buffers(unsigned long *time_limit)
183 {
184 #ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
185         int cpu;
186         struct paca_struct *pp;
187
188         for_each_possible_cpu(cpu) {
189                 pp = paca_ptrs[cpu];
190                 if (!pp->dispatch_log)
191                         continue;
192                 kmem_cache_free(dtl_cache, pp->dispatch_log);
193                 pp->dtl_ridx = 0;
194                 pp->dispatch_log = 0;
195                 pp->dispatch_log_end = 0;
196                 pp->dtl_curr = 0;
197
198                 if (time_limit && time_after(jiffies, *time_limit)) {
199                         cond_resched();
200                         *time_limit = jiffies + HZ;
201                 }
202         }
203 #endif
204 }
205
206 static int init_cpu_associativity(void)
207 {
208         vcpu_associativity = kcalloc(num_possible_cpus() / threads_per_core,
209                         VPHN_ASSOC_BUFSIZE * sizeof(__be32), GFP_KERNEL);
210         pcpu_associativity = kcalloc(NR_CPUS_H / threads_per_core,
211                         VPHN_ASSOC_BUFSIZE * sizeof(__be32), GFP_KERNEL);
212
213         if (!vcpu_associativity || !pcpu_associativity) {
214                 pr_err("error allocating memory for associativity information\n");
215                 return -ENOMEM;
216         }
217
218         return 0;
219 }
220
221 static void destroy_cpu_associativity(void)
222 {
223         kfree(vcpu_associativity);
224         kfree(pcpu_associativity);
225         vcpu_associativity = pcpu_associativity = 0;
226 }
227
228 static __be32 *__get_cpu_associativity(int cpu, __be32 *cpu_assoc, int flag)
229 {
230         __be32 *assoc;
231         int rc = 0;
232
233         assoc = &cpu_assoc[(int)(cpu / threads_per_core) * VPHN_ASSOC_BUFSIZE];
234         if (!assoc[0]) {
235                 rc = hcall_vphn(cpu, flag, &assoc[0]);
236                 if (rc)
237                         return NULL;
238         }
239
240         return assoc;
241 }
242
243 static __be32 *get_pcpu_associativity(int cpu)
244 {
245         return __get_cpu_associativity(cpu, pcpu_associativity, VPHN_FLAG_PCPU);
246 }
247
248 static __be32 *get_vcpu_associativity(int cpu)
249 {
250         return __get_cpu_associativity(cpu, vcpu_associativity, VPHN_FLAG_VCPU);
251 }
252
253 static int cpu_relative_dispatch_distance(int last_disp_cpu, int cur_disp_cpu)
254 {
255         __be32 *last_disp_cpu_assoc, *cur_disp_cpu_assoc;
256
257         if (last_disp_cpu >= NR_CPUS_H || cur_disp_cpu >= NR_CPUS_H)
258                 return -EINVAL;
259
260         last_disp_cpu_assoc = get_pcpu_associativity(last_disp_cpu);
261         cur_disp_cpu_assoc = get_pcpu_associativity(cur_disp_cpu);
262
263         if (!last_disp_cpu_assoc || !cur_disp_cpu_assoc)
264                 return -EIO;
265
266         return cpu_relative_distance(last_disp_cpu_assoc, cur_disp_cpu_assoc);
267 }
268
269 static int cpu_home_node_dispatch_distance(int disp_cpu)
270 {
271         __be32 *disp_cpu_assoc, *vcpu_assoc;
272         int vcpu_id = smp_processor_id();
273
274         if (disp_cpu >= NR_CPUS_H) {
275                 pr_debug_ratelimited("vcpu dispatch cpu %d > %d\n",
276                                                 disp_cpu, NR_CPUS_H);
277                 return -EINVAL;
278         }
279
280         disp_cpu_assoc = get_pcpu_associativity(disp_cpu);
281         vcpu_assoc = get_vcpu_associativity(vcpu_id);
282
283         if (!disp_cpu_assoc || !vcpu_assoc)
284                 return -EIO;
285
286         return cpu_relative_distance(disp_cpu_assoc, vcpu_assoc);
287 }
288
289 static void update_vcpu_disp_stat(int disp_cpu)
290 {
291         struct vcpu_dispatch_data *disp;
292         int distance;
293
294         disp = this_cpu_ptr(&vcpu_disp_data);
295         if (disp->last_disp_cpu == -1) {
296                 disp->last_disp_cpu = disp_cpu;
297                 return;
298         }
299
300         disp->total_disp++;
301
302         if (disp->last_disp_cpu == disp_cpu ||
303                 (cpu_first_thread_sibling(disp->last_disp_cpu) ==
304                                         cpu_first_thread_sibling(disp_cpu)))
305                 disp->same_cpu_disp++;
306         else {
307                 distance = cpu_relative_dispatch_distance(disp->last_disp_cpu,
308                                                                 disp_cpu);
309                 if (distance < 0)
310                         pr_debug_ratelimited("vcpudispatch_stats: cpu %d: error determining associativity\n",
311                                         smp_processor_id());
312                 else {
313                         switch (distance) {
314                         case 0:
315                                 disp->same_chip_disp++;
316                                 break;
317                         case 1:
318                                 disp->diff_chip_disp++;
319                                 break;
320                         case 2:
321                                 disp->far_chip_disp++;
322                                 break;
323                         default:
324                                 pr_debug_ratelimited("vcpudispatch_stats: cpu %d (%d -> %d): unexpected relative dispatch distance %d\n",
325                                                  smp_processor_id(),
326                                                  disp->last_disp_cpu,
327                                                  disp_cpu,
328                                                  distance);
329                         }
330                 }
331         }
332
333         distance = cpu_home_node_dispatch_distance(disp_cpu);
334         if (distance < 0)
335                 pr_debug_ratelimited("vcpudispatch_stats: cpu %d: error determining associativity\n",
336                                 smp_processor_id());
337         else {
338                 switch (distance) {
339                 case 0:
340                         disp->numa_home_disp++;
341                         break;
342                 case 1:
343                         disp->numa_remote_disp++;
344                         break;
345                 case 2:
346                         disp->numa_far_disp++;
347                         break;
348                 default:
349                         pr_debug_ratelimited("vcpudispatch_stats: cpu %d on %d: unexpected numa dispatch distance %d\n",
350                                                  smp_processor_id(),
351                                                  disp_cpu,
352                                                  distance);
353                 }
354         }
355
356         disp->last_disp_cpu = disp_cpu;
357 }
358
359 static void process_dtl_buffer(struct work_struct *work)
360 {
361         struct dtl_entry dtle;
362         u64 i = __this_cpu_read(dtl_entry_ridx);
363         struct dtl_entry *dtl = local_paca->dispatch_log + (i % N_DISPATCH_LOG);
364         struct dtl_entry *dtl_end = local_paca->dispatch_log_end;
365         struct lppaca *vpa = local_paca->lppaca_ptr;
366         struct dtl_worker *d = container_of(work, struct dtl_worker, work.work);
367
368         if (!local_paca->dispatch_log)
369                 return;
370
371         /* if we have been migrated away, we cancel ourself */
372         if (d->cpu != smp_processor_id()) {
373                 pr_debug("vcpudispatch_stats: cpu %d worker migrated -- canceling worker\n",
374                                                 smp_processor_id());
375                 return;
376         }
377
378         if (i == be64_to_cpu(vpa->dtl_idx))
379                 goto out;
380
381         while (i < be64_to_cpu(vpa->dtl_idx)) {
382                 dtle = *dtl;
383                 barrier();
384                 if (i + N_DISPATCH_LOG < be64_to_cpu(vpa->dtl_idx)) {
385                         /* buffer has overflowed */
386                         pr_debug_ratelimited("vcpudispatch_stats: cpu %d lost %lld DTL samples\n",
387                                 d->cpu,
388                                 be64_to_cpu(vpa->dtl_idx) - N_DISPATCH_LOG - i);
389                         i = be64_to_cpu(vpa->dtl_idx) - N_DISPATCH_LOG;
390                         dtl = local_paca->dispatch_log + (i % N_DISPATCH_LOG);
391                         continue;
392                 }
393                 update_vcpu_disp_stat(be16_to_cpu(dtle.processor_id));
394                 ++i;
395                 ++dtl;
396                 if (dtl == dtl_end)
397                         dtl = local_paca->dispatch_log;
398         }
399
400         __this_cpu_write(dtl_entry_ridx, i);
401
402 out:
403         schedule_delayed_work_on(d->cpu, to_delayed_work(work),
404                                         HZ / vcpudispatch_stats_freq);
405 }
406
407 static int dtl_worker_online(unsigned int cpu)
408 {
409         struct dtl_worker *d = &per_cpu(dtl_workers, cpu);
410
411         memset(d, 0, sizeof(*d));
412         INIT_DELAYED_WORK(&d->work, process_dtl_buffer);
413         d->cpu = cpu;
414
415 #ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
416         per_cpu(dtl_entry_ridx, cpu) = 0;
417         register_dtl_buffer(cpu);
418 #else
419         per_cpu(dtl_entry_ridx, cpu) = be64_to_cpu(lppaca_of(cpu).dtl_idx);
420 #endif
421
422         schedule_delayed_work_on(cpu, &d->work, HZ / vcpudispatch_stats_freq);
423         return 0;
424 }
425
426 static int dtl_worker_offline(unsigned int cpu)
427 {
428         struct dtl_worker *d = &per_cpu(dtl_workers, cpu);
429
430         cancel_delayed_work_sync(&d->work);
431
432 #ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
433         unregister_dtl(get_hard_smp_processor_id(cpu));
434 #endif
435
436         return 0;
437 }
438
439 static void set_global_dtl_mask(u8 mask)
440 {
441         int cpu;
442
443         dtl_mask = mask;
444         for_each_present_cpu(cpu)
445                 lppaca_of(cpu).dtl_enable_mask = dtl_mask;
446 }
447
448 static void reset_global_dtl_mask(void)
449 {
450         int cpu;
451
452 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
453         dtl_mask = DTL_LOG_PREEMPT;
454 #else
455         dtl_mask = 0;
456 #endif
457         for_each_present_cpu(cpu)
458                 lppaca_of(cpu).dtl_enable_mask = dtl_mask;
459 }
460
461 static int dtl_worker_enable(unsigned long *time_limit)
462 {
463         int rc = 0, state;
464
465         if (!write_trylock(&dtl_access_lock)) {
466                 rc = -EBUSY;
467                 goto out;
468         }
469
470         set_global_dtl_mask(DTL_LOG_ALL);
471
472         /* Setup dtl buffers and register those */
473         alloc_dtl_buffers(time_limit);
474
475         state = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "powerpc/dtl:online",
476                                         dtl_worker_online, dtl_worker_offline);
477         if (state < 0) {
478                 pr_err("vcpudispatch_stats: unable to setup workqueue for DTL processing\n");
479                 free_dtl_buffers(time_limit);
480                 reset_global_dtl_mask();
481                 write_unlock(&dtl_access_lock);
482                 rc = -EINVAL;
483                 goto out;
484         }
485         dtl_worker_state = state;
486
487 out:
488         return rc;
489 }
490
491 static void dtl_worker_disable(unsigned long *time_limit)
492 {
493         cpuhp_remove_state(dtl_worker_state);
494         free_dtl_buffers(time_limit);
495         reset_global_dtl_mask();
496         write_unlock(&dtl_access_lock);
497 }
498
499 static ssize_t vcpudispatch_stats_write(struct file *file, const char __user *p,
500                 size_t count, loff_t *ppos)
501 {
502         unsigned long time_limit = jiffies + HZ;
503         struct vcpu_dispatch_data *disp;
504         int rc, cmd, cpu;
505         char buf[16];
506
507         if (count > 15)
508                 return -EINVAL;
509
510         if (copy_from_user(buf, p, count))
511                 return -EFAULT;
512
513         buf[count] = 0;
514         rc = kstrtoint(buf, 0, &cmd);
515         if (rc || cmd < 0 || cmd > 1) {
516                 pr_err("vcpudispatch_stats: please use 0 to disable or 1 to enable dispatch statistics\n");
517                 return rc ? rc : -EINVAL;
518         }
519
520         mutex_lock(&dtl_enable_mutex);
521
522         if ((cmd == 0 && !vcpudispatch_stats_on) ||
523                         (cmd == 1 && vcpudispatch_stats_on))
524                 goto out;
525
526         if (cmd) {
527                 rc = init_cpu_associativity();
528                 if (rc)
529                         goto out;
530
531                 for_each_possible_cpu(cpu) {
532                         disp = per_cpu_ptr(&vcpu_disp_data, cpu);
533                         memset(disp, 0, sizeof(*disp));
534                         disp->last_disp_cpu = -1;
535                 }
536
537                 rc = dtl_worker_enable(&time_limit);
538                 if (rc) {
539                         destroy_cpu_associativity();
540                         goto out;
541                 }
542         } else {
543                 dtl_worker_disable(&time_limit);
544                 destroy_cpu_associativity();
545         }
546
547         vcpudispatch_stats_on = cmd;
548
549 out:
550         mutex_unlock(&dtl_enable_mutex);
551         if (rc)
552                 return rc;
553         return count;
554 }
555
556 static int vcpudispatch_stats_display(struct seq_file *p, void *v)
557 {
558         int cpu;
559         struct vcpu_dispatch_data *disp;
560
561         if (!vcpudispatch_stats_on) {
562                 seq_puts(p, "off\n");
563                 return 0;
564         }
565
566         for_each_online_cpu(cpu) {
567                 disp = per_cpu_ptr(&vcpu_disp_data, cpu);
568                 seq_printf(p, "cpu%d", cpu);
569                 seq_put_decimal_ull(p, " ", disp->total_disp);
570                 seq_put_decimal_ull(p, " ", disp->same_cpu_disp);
571                 seq_put_decimal_ull(p, " ", disp->same_chip_disp);
572                 seq_put_decimal_ull(p, " ", disp->diff_chip_disp);
573                 seq_put_decimal_ull(p, " ", disp->far_chip_disp);
574                 seq_put_decimal_ull(p, " ", disp->numa_home_disp);
575                 seq_put_decimal_ull(p, " ", disp->numa_remote_disp);
576                 seq_put_decimal_ull(p, " ", disp->numa_far_disp);
577                 seq_puts(p, "\n");
578         }
579
580         return 0;
581 }
582
583 static int vcpudispatch_stats_open(struct inode *inode, struct file *file)
584 {
585         return single_open(file, vcpudispatch_stats_display, NULL);
586 }
587
588 static const struct proc_ops vcpudispatch_stats_proc_ops = {
589         .proc_open      = vcpudispatch_stats_open,
590         .proc_read      = seq_read,
591         .proc_write     = vcpudispatch_stats_write,
592         .proc_lseek     = seq_lseek,
593         .proc_release   = single_release,
594 };
595
596 static ssize_t vcpudispatch_stats_freq_write(struct file *file,
597                 const char __user *p, size_t count, loff_t *ppos)
598 {
599         int rc, freq;
600         char buf[16];
601
602         if (count > 15)
603                 return -EINVAL;
604
605         if (copy_from_user(buf, p, count))
606                 return -EFAULT;
607
608         buf[count] = 0;
609         rc = kstrtoint(buf, 0, &freq);
610         if (rc || freq < 1 || freq > HZ) {
611                 pr_err("vcpudispatch_stats_freq: please specify a frequency between 1 and %d\n",
612                                 HZ);
613                 return rc ? rc : -EINVAL;
614         }
615
616         vcpudispatch_stats_freq = freq;
617
618         return count;
619 }
620
621 static int vcpudispatch_stats_freq_display(struct seq_file *p, void *v)
622 {
623         seq_printf(p, "%d\n", vcpudispatch_stats_freq);
624         return 0;
625 }
626
627 static int vcpudispatch_stats_freq_open(struct inode *inode, struct file *file)
628 {
629         return single_open(file, vcpudispatch_stats_freq_display, NULL);
630 }
631
632 static const struct proc_ops vcpudispatch_stats_freq_proc_ops = {
633         .proc_open      = vcpudispatch_stats_freq_open,
634         .proc_read      = seq_read,
635         .proc_write     = vcpudispatch_stats_freq_write,
636         .proc_lseek     = seq_lseek,
637         .proc_release   = single_release,
638 };
639
640 static int __init vcpudispatch_stats_procfs_init(void)
641 {
642         if (!lppaca_shared_proc())
643                 return 0;
644
645         if (!proc_create("powerpc/vcpudispatch_stats", 0600, NULL,
646                                         &vcpudispatch_stats_proc_ops))
647                 pr_err("vcpudispatch_stats: error creating procfs file\n");
648         else if (!proc_create("powerpc/vcpudispatch_stats_freq", 0600, NULL,
649                                         &vcpudispatch_stats_freq_proc_ops))
650                 pr_err("vcpudispatch_stats_freq: error creating procfs file\n");
651
652         return 0;
653 }
654
655 machine_device_initcall(pseries, vcpudispatch_stats_procfs_init);
656
657 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
658 u64 pseries_paravirt_steal_clock(int cpu)
659 {
660         struct lppaca *lppaca = &lppaca_of(cpu);
661
662         return be64_to_cpu(READ_ONCE(lppaca->enqueue_dispatch_tb)) +
663                 be64_to_cpu(READ_ONCE(lppaca->ready_enqueue_tb));
664 }
665 #endif
666
667 #endif /* CONFIG_PPC_SPLPAR */
668
669 void vpa_init(int cpu)
670 {
671         int hwcpu = get_hard_smp_processor_id(cpu);
672         unsigned long addr;
673         long ret;
674
675         /*
676          * The spec says it "may be problematic" if CPU x registers the VPA of
677          * CPU y. We should never do that, but wail if we ever do.
678          */
679         WARN_ON(cpu != smp_processor_id());
680
681         if (cpu_has_feature(CPU_FTR_ALTIVEC))
682                 lppaca_of(cpu).vmxregs_in_use = 1;
683
684         if (cpu_has_feature(CPU_FTR_ARCH_207S))
685                 lppaca_of(cpu).ebb_regs_in_use = 1;
686
687         addr = __pa(&lppaca_of(cpu));
688         ret = register_vpa(hwcpu, addr);
689
690         if (ret) {
691                 pr_err("WARNING: VPA registration for cpu %d (hw %d) of area "
692                        "%lx failed with %ld\n", cpu, hwcpu, addr, ret);
693                 return;
694         }
695
696 #ifdef CONFIG_PPC_64S_HASH_MMU
697         /*
698          * PAPR says this feature is SLB-Buffer but firmware never
699          * reports that.  All SPLPAR support SLB shadow buffer.
700          */
701         if (!radix_enabled() && firmware_has_feature(FW_FEATURE_SPLPAR)) {
702                 addr = __pa(paca_ptrs[cpu]->slb_shadow_ptr);
703                 ret = register_slb_shadow(hwcpu, addr);
704                 if (ret)
705                         pr_err("WARNING: SLB shadow buffer registration for "
706                                "cpu %d (hw %d) of area %lx failed with %ld\n",
707                                cpu, hwcpu, addr, ret);
708         }
709 #endif /* CONFIG_PPC_64S_HASH_MMU */
710
711         /*
712          * Register dispatch trace log, if one has been allocated.
713          */
714         register_dtl_buffer(cpu);
715 }
716
717 #ifdef CONFIG_PPC_BOOK3S_64
718
719 static int __init pseries_lpar_register_process_table(unsigned long base,
720                         unsigned long page_size, unsigned long table_size)
721 {
722         long rc;
723         unsigned long flags = 0;
724
725         if (table_size)
726                 flags |= PROC_TABLE_NEW;
727         if (radix_enabled()) {
728                 flags |= PROC_TABLE_RADIX;
729                 if (mmu_has_feature(MMU_FTR_GTSE))
730                         flags |= PROC_TABLE_GTSE;
731         } else
732                 flags |= PROC_TABLE_HPT_SLB;
733         for (;;) {
734                 rc = plpar_hcall_norets(H_REGISTER_PROC_TBL, flags, base,
735                                         page_size, table_size);
736                 if (!H_IS_LONG_BUSY(rc))
737                         break;
738                 mdelay(get_longbusy_msecs(rc));
739         }
740         if (rc != H_SUCCESS) {
741                 pr_err("Failed to register process table (rc=%ld)\n", rc);
742                 BUG();
743         }
744         return rc;
745 }
746
747 #ifdef CONFIG_PPC_64S_HASH_MMU
748
749 static long pSeries_lpar_hpte_insert(unsigned long hpte_group,
750                                      unsigned long vpn, unsigned long pa,
751                                      unsigned long rflags, unsigned long vflags,
752                                      int psize, int apsize, int ssize)
753 {
754         unsigned long lpar_rc;
755         unsigned long flags;
756         unsigned long slot;
757         unsigned long hpte_v, hpte_r;
758
759         if (!(vflags & HPTE_V_BOLTED))
760                 pr_devel("hpte_insert(group=%lx, vpn=%016lx, "
761                          "pa=%016lx, rflags=%lx, vflags=%lx, psize=%d)\n",
762                          hpte_group, vpn,  pa, rflags, vflags, psize);
763
764         hpte_v = hpte_encode_v(vpn, psize, apsize, ssize) | vflags | HPTE_V_VALID;
765         hpte_r = hpte_encode_r(pa, psize, apsize) | rflags;
766
767         if (!(vflags & HPTE_V_BOLTED))
768                 pr_devel(" hpte_v=%016lx, hpte_r=%016lx\n", hpte_v, hpte_r);
769
770         /* Now fill in the actual HPTE */
771         /* Set CEC cookie to 0         */
772         /* Zero page = 0               */
773         /* I-cache Invalidate = 0      */
774         /* I-cache synchronize = 0     */
775         /* Exact = 0                   */
776         flags = 0;
777
778         if (firmware_has_feature(FW_FEATURE_XCMO) && !(hpte_r & HPTE_R_N))
779                 flags |= H_COALESCE_CAND;
780
781         lpar_rc = plpar_pte_enter(flags, hpte_group, hpte_v, hpte_r, &slot);
782         if (unlikely(lpar_rc == H_PTEG_FULL)) {
783                 pr_devel("Hash table group is full\n");
784                 return -1;
785         }
786
787         /*
788          * Since we try and ioremap PHBs we don't own, the pte insert
789          * will fail. However we must catch the failure in hash_page
790          * or we will loop forever, so return -2 in this case.
791          */
792         if (unlikely(lpar_rc != H_SUCCESS)) {
793                 pr_err("Failed hash pte insert with error %ld\n", lpar_rc);
794                 return -2;
795         }
796         if (!(vflags & HPTE_V_BOLTED))
797                 pr_devel(" -> slot: %lu\n", slot & 7);
798
799         /* Because of iSeries, we have to pass down the secondary
800          * bucket bit here as well
801          */
802         return (slot & 7) | (!!(vflags & HPTE_V_SECONDARY) << 3);
803 }
804
805 static DEFINE_SPINLOCK(pSeries_lpar_tlbie_lock);
806
807 static long pSeries_lpar_hpte_remove(unsigned long hpte_group)
808 {
809         unsigned long slot_offset;
810         unsigned long lpar_rc;
811         int i;
812         unsigned long dummy1, dummy2;
813
814         /* pick a random slot to start at */
815         slot_offset = mftb() & 0x7;
816
817         for (i = 0; i < HPTES_PER_GROUP; i++) {
818
819                 /* don't remove a bolted entry */
820                 lpar_rc = plpar_pte_remove(H_ANDCOND, hpte_group + slot_offset,
821                                            HPTE_V_BOLTED, &dummy1, &dummy2);
822                 if (lpar_rc == H_SUCCESS)
823                         return i;
824
825                 /*
826                  * The test for adjunct partition is performed before the
827                  * ANDCOND test.  H_RESOURCE may be returned, so we need to
828                  * check for that as well.
829                  */
830                 BUG_ON(lpar_rc != H_NOT_FOUND && lpar_rc != H_RESOURCE);
831
832                 slot_offset++;
833                 slot_offset &= 0x7;
834         }
835
836         return -1;
837 }
838
839 /* Called during kexec sequence with MMU off */
840 static notrace void manual_hpte_clear_all(void)
841 {
842         unsigned long size_bytes = 1UL << ppc64_pft_size;
843         unsigned long hpte_count = size_bytes >> 4;
844         struct {
845                 unsigned long pteh;
846                 unsigned long ptel;
847         } ptes[4];
848         long lpar_rc;
849         unsigned long i, j;
850
851         /* Read in batches of 4,
852          * invalidate only valid entries not in the VRMA
853          * hpte_count will be a multiple of 4
854          */
855         for (i = 0; i < hpte_count; i += 4) {
856                 lpar_rc = plpar_pte_read_4_raw(0, i, (void *)ptes);
857                 if (lpar_rc != H_SUCCESS) {
858                         pr_info("Failed to read hash page table at %ld err %ld\n",
859                                 i, lpar_rc);
860                         continue;
861                 }
862                 for (j = 0; j < 4; j++){
863                         if ((ptes[j].pteh & HPTE_V_VRMA_MASK) ==
864                                 HPTE_V_VRMA_MASK)
865                                 continue;
866                         if (ptes[j].pteh & HPTE_V_VALID)
867                                 plpar_pte_remove_raw(0, i + j, 0,
868                                         &(ptes[j].pteh), &(ptes[j].ptel));
869                 }
870         }
871 }
872
873 /* Called during kexec sequence with MMU off */
874 static notrace int hcall_hpte_clear_all(void)
875 {
876         int rc;
877
878         do {
879                 rc = plpar_hcall_norets(H_CLEAR_HPT);
880         } while (rc == H_CONTINUE);
881
882         return rc;
883 }
884
885 /* Called during kexec sequence with MMU off */
886 static notrace void pseries_hpte_clear_all(void)
887 {
888         int rc;
889
890         rc = hcall_hpte_clear_all();
891         if (rc != H_SUCCESS)
892                 manual_hpte_clear_all();
893
894 #ifdef __LITTLE_ENDIAN__
895         /*
896          * Reset exceptions to big endian.
897          *
898          * FIXME this is a hack for kexec, we need to reset the exception
899          * endian before starting the new kernel and this is a convenient place
900          * to do it.
901          *
902          * This is also called on boot when a fadump happens. In that case we
903          * must not change the exception endian mode.
904          */
905         if (firmware_has_feature(FW_FEATURE_SET_MODE) && !is_fadump_active())
906                 pseries_big_endian_exceptions();
907 #endif
908 }
909
910 /*
911  * NOTE: for updatepp ops we are fortunate that the linux "newpp" bits and
912  * the low 3 bits of flags happen to line up.  So no transform is needed.
913  * We can probably optimize here and assume the high bits of newpp are
914  * already zero.  For now I am paranoid.
915  */
916 static long pSeries_lpar_hpte_updatepp(unsigned long slot,
917                                        unsigned long newpp,
918                                        unsigned long vpn,
919                                        int psize, int apsize,
920                                        int ssize, unsigned long inv_flags)
921 {
922         unsigned long lpar_rc;
923         unsigned long flags;
924         unsigned long want_v;
925
926         want_v = hpte_encode_avpn(vpn, psize, ssize);
927
928         flags = (newpp & (HPTE_R_PP | HPTE_R_N | HPTE_R_KEY_LO)) | H_AVPN;
929         flags |= (newpp & HPTE_R_KEY_HI) >> 48;
930         if (mmu_has_feature(MMU_FTR_KERNEL_RO))
931                 /* Move pp0 into bit 8 (IBM 55) */
932                 flags |= (newpp & HPTE_R_PP0) >> 55;
933
934         pr_devel("    update: avpnv=%016lx, hash=%016lx, f=%lx, psize: %d ...",
935                  want_v, slot, flags, psize);
936
937         lpar_rc = plpar_pte_protect(flags, slot, want_v);
938
939         if (lpar_rc == H_NOT_FOUND) {
940                 pr_devel("not found !\n");
941                 return -1;
942         }
943
944         pr_devel("ok\n");
945
946         BUG_ON(lpar_rc != H_SUCCESS);
947
948         return 0;
949 }
950
951 static long __pSeries_lpar_hpte_find(unsigned long want_v, unsigned long hpte_group)
952 {
953         long lpar_rc;
954         unsigned long i, j;
955         struct {
956                 unsigned long pteh;
957                 unsigned long ptel;
958         } ptes[4];
959
960         for (i = 0; i < HPTES_PER_GROUP; i += 4, hpte_group += 4) {
961
962                 lpar_rc = plpar_pte_read_4(0, hpte_group, (void *)ptes);
963                 if (lpar_rc != H_SUCCESS) {
964                         pr_info("Failed to read hash page table at %ld err %ld\n",
965                                 hpte_group, lpar_rc);
966                         continue;
967                 }
968
969                 for (j = 0; j < 4; j++) {
970                         if (HPTE_V_COMPARE(ptes[j].pteh, want_v) &&
971                             (ptes[j].pteh & HPTE_V_VALID))
972                                 return i + j;
973                 }
974         }
975
976         return -1;
977 }
978
979 static long pSeries_lpar_hpte_find(unsigned long vpn, int psize, int ssize)
980 {
981         long slot;
982         unsigned long hash;
983         unsigned long want_v;
984         unsigned long hpte_group;
985
986         hash = hpt_hash(vpn, mmu_psize_defs[psize].shift, ssize);
987         want_v = hpte_encode_avpn(vpn, psize, ssize);
988
989         /*
990          * We try to keep bolted entries always in primary hash
991          * But in some case we can find them in secondary too.
992          */
993         hpte_group = (hash & htab_hash_mask) * HPTES_PER_GROUP;
994         slot = __pSeries_lpar_hpte_find(want_v, hpte_group);
995         if (slot < 0) {
996                 /* Try in secondary */
997                 hpte_group = (~hash & htab_hash_mask) * HPTES_PER_GROUP;
998                 slot = __pSeries_lpar_hpte_find(want_v, hpte_group);
999                 if (slot < 0)
1000                         return -1;
1001         }
1002         return hpte_group + slot;
1003 }
1004
1005 static void pSeries_lpar_hpte_updateboltedpp(unsigned long newpp,
1006                                              unsigned long ea,
1007                                              int psize, int ssize)
1008 {
1009         unsigned long vpn;
1010         unsigned long lpar_rc, slot, vsid, flags;
1011
1012         vsid = get_kernel_vsid(ea, ssize);
1013         vpn = hpt_vpn(ea, vsid, ssize);
1014
1015         slot = pSeries_lpar_hpte_find(vpn, psize, ssize);
1016         BUG_ON(slot == -1);
1017
1018         flags = newpp & (HPTE_R_PP | HPTE_R_N);
1019         if (mmu_has_feature(MMU_FTR_KERNEL_RO))
1020                 /* Move pp0 into bit 8 (IBM 55) */
1021                 flags |= (newpp & HPTE_R_PP0) >> 55;
1022
1023         flags |= ((newpp & HPTE_R_KEY_HI) >> 48) | (newpp & HPTE_R_KEY_LO);
1024
1025         lpar_rc = plpar_pte_protect(flags, slot, 0);
1026
1027         BUG_ON(lpar_rc != H_SUCCESS);
1028 }
1029
1030 static void pSeries_lpar_hpte_invalidate(unsigned long slot, unsigned long vpn,
1031                                          int psize, int apsize,
1032                                          int ssize, int local)
1033 {
1034         unsigned long want_v;
1035         unsigned long lpar_rc;
1036         unsigned long dummy1, dummy2;
1037
1038         pr_devel("    inval : slot=%lx, vpn=%016lx, psize: %d, local: %d\n",
1039                  slot, vpn, psize, local);
1040
1041         want_v = hpte_encode_avpn(vpn, psize, ssize);
1042         lpar_rc = plpar_pte_remove(H_AVPN, slot, want_v, &dummy1, &dummy2);
1043         if (lpar_rc == H_NOT_FOUND)
1044                 return;
1045
1046         BUG_ON(lpar_rc != H_SUCCESS);
1047 }
1048
1049
1050 /*
1051  * As defined in the PAPR's section 14.5.4.1.8
1052  * The control mask doesn't include the returned reference and change bit from
1053  * the processed PTE.
1054  */
1055 #define HBLKR_AVPN              0x0100000000000000UL
1056 #define HBLKR_CTRL_MASK         0xf800000000000000UL
1057 #define HBLKR_CTRL_SUCCESS      0x8000000000000000UL
1058 #define HBLKR_CTRL_ERRNOTFOUND  0x8800000000000000UL
1059 #define HBLKR_CTRL_ERRBUSY      0xa000000000000000UL
1060
1061 /*
1062  * Returned true if we are supporting this block size for the specified segment
1063  * base page size and actual page size.
1064  *
1065  * Currently, we only support 8 size block.
1066  */
1067 static inline bool is_supported_hlbkrm(int bpsize, int psize)
1068 {
1069         return (hblkrm_size[bpsize][psize] == HBLKRM_SUPPORTED_BLOCK_SIZE);
1070 }
1071
1072 /**
1073  * H_BLOCK_REMOVE caller.
1074  * @idx should point to the latest @param entry set with a PTEX.
1075  * If PTE cannot be processed because another CPUs has already locked that
1076  * group, those entries are put back in @param starting at index 1.
1077  * If entries has to be retried and @retry_busy is set to true, these entries
1078  * are retried until success. If @retry_busy is set to false, the returned
1079  * is the number of entries yet to process.
1080  */
1081 static unsigned long call_block_remove(unsigned long idx, unsigned long *param,
1082                                        bool retry_busy)
1083 {
1084         unsigned long i, rc, new_idx;
1085         unsigned long retbuf[PLPAR_HCALL9_BUFSIZE];
1086
1087         if (idx < 2) {
1088                 pr_warn("Unexpected empty call to H_BLOCK_REMOVE");
1089                 return 0;
1090         }
1091 again:
1092         new_idx = 0;
1093         if (idx > PLPAR_HCALL9_BUFSIZE) {
1094                 pr_err("Too many PTEs (%lu) for H_BLOCK_REMOVE", idx);
1095                 idx = PLPAR_HCALL9_BUFSIZE;
1096         } else if (idx < PLPAR_HCALL9_BUFSIZE)
1097                 param[idx] = HBR_END;
1098
1099         rc = plpar_hcall9(H_BLOCK_REMOVE, retbuf,
1100                           param[0], /* AVA */
1101                           param[1],  param[2],  param[3],  param[4], /* TS0-7 */
1102                           param[5],  param[6],  param[7],  param[8]);
1103         if (rc == H_SUCCESS)
1104                 return 0;
1105
1106         BUG_ON(rc != H_PARTIAL);
1107
1108         /* Check that the unprocessed entries were 'not found' or 'busy' */
1109         for (i = 0; i < idx-1; i++) {
1110                 unsigned long ctrl = retbuf[i] & HBLKR_CTRL_MASK;
1111
1112                 if (ctrl == HBLKR_CTRL_ERRBUSY) {
1113                         param[++new_idx] = param[i+1];
1114                         continue;
1115                 }
1116
1117                 BUG_ON(ctrl != HBLKR_CTRL_SUCCESS
1118                        && ctrl != HBLKR_CTRL_ERRNOTFOUND);
1119         }
1120
1121         /*
1122          * If there were entries found busy, retry these entries if requested,
1123          * of if all the entries have to be retried.
1124          */
1125         if (new_idx && (retry_busy || new_idx == (PLPAR_HCALL9_BUFSIZE-1))) {
1126                 idx = new_idx + 1;
1127                 goto again;
1128         }
1129
1130         return new_idx;
1131 }
1132
1133 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1134 /*
1135  * Limit iterations holding pSeries_lpar_tlbie_lock to 3. We also need
1136  * to make sure that we avoid bouncing the hypervisor tlbie lock.
1137  */
1138 #define PPC64_HUGE_HPTE_BATCH 12
1139
1140 static void hugepage_block_invalidate(unsigned long *slot, unsigned long *vpn,
1141                                       int count, int psize, int ssize)
1142 {
1143         unsigned long param[PLPAR_HCALL9_BUFSIZE];
1144         unsigned long shift, current_vpgb, vpgb;
1145         int i, pix = 0;
1146
1147         shift = mmu_psize_defs[psize].shift;
1148
1149         for (i = 0; i < count; i++) {
1150                 /*
1151                  * Shifting 3 bits more on the right to get a
1152                  * 8 pages aligned virtual addresse.
1153                  */
1154                 vpgb = (vpn[i] >> (shift - VPN_SHIFT + 3));
1155                 if (!pix || vpgb != current_vpgb) {
1156                         /*
1157                          * Need to start a new 8 pages block, flush
1158                          * the current one if needed.
1159                          */
1160                         if (pix)
1161                                 (void)call_block_remove(pix, param, true);
1162                         current_vpgb = vpgb;
1163                         param[0] = hpte_encode_avpn(vpn[i], psize, ssize);
1164                         pix = 1;
1165                 }
1166
1167                 param[pix++] = HBR_REQUEST | HBLKR_AVPN | slot[i];
1168                 if (pix == PLPAR_HCALL9_BUFSIZE) {
1169                         pix = call_block_remove(pix, param, false);
1170                         /*
1171                          * pix = 0 means that all the entries were
1172                          * removed, we can start a new block.
1173                          * Otherwise, this means that there are entries
1174                          * to retry, and pix points to latest one, so
1175                          * we should increment it and try to continue
1176                          * the same block.
1177                          */
1178                         if (pix)
1179                                 pix++;
1180                 }
1181         }
1182         if (pix)
1183                 (void)call_block_remove(pix, param, true);
1184 }
1185
1186 static void hugepage_bulk_invalidate(unsigned long *slot, unsigned long *vpn,
1187                                      int count, int psize, int ssize)
1188 {
1189         unsigned long param[PLPAR_HCALL9_BUFSIZE];
1190         int i = 0, pix = 0, rc;
1191
1192         for (i = 0; i < count; i++) {
1193
1194                 if (!firmware_has_feature(FW_FEATURE_BULK_REMOVE)) {
1195                         pSeries_lpar_hpte_invalidate(slot[i], vpn[i], psize, 0,
1196                                                      ssize, 0);
1197                 } else {
1198                         param[pix] = HBR_REQUEST | HBR_AVPN | slot[i];
1199                         param[pix+1] = hpte_encode_avpn(vpn[i], psize, ssize);
1200                         pix += 2;
1201                         if (pix == 8) {
1202                                 rc = plpar_hcall9(H_BULK_REMOVE, param,
1203                                                   param[0], param[1], param[2],
1204                                                   param[3], param[4], param[5],
1205                                                   param[6], param[7]);
1206                                 BUG_ON(rc != H_SUCCESS);
1207                                 pix = 0;
1208                         }
1209                 }
1210         }
1211         if (pix) {
1212                 param[pix] = HBR_END;
1213                 rc = plpar_hcall9(H_BULK_REMOVE, param, param[0], param[1],
1214                                   param[2], param[3], param[4], param[5],
1215                                   param[6], param[7]);
1216                 BUG_ON(rc != H_SUCCESS);
1217         }
1218 }
1219
1220 static inline void __pSeries_lpar_hugepage_invalidate(unsigned long *slot,
1221                                                       unsigned long *vpn,
1222                                                       int count, int psize,
1223                                                       int ssize)
1224 {
1225         unsigned long flags = 0;
1226         int lock_tlbie = !mmu_has_feature(MMU_FTR_LOCKLESS_TLBIE);
1227
1228         if (lock_tlbie)
1229                 spin_lock_irqsave(&pSeries_lpar_tlbie_lock, flags);
1230
1231         /* Assuming THP size is 16M */
1232         if (is_supported_hlbkrm(psize, MMU_PAGE_16M))
1233                 hugepage_block_invalidate(slot, vpn, count, psize, ssize);
1234         else
1235                 hugepage_bulk_invalidate(slot, vpn, count, psize, ssize);
1236
1237         if (lock_tlbie)
1238                 spin_unlock_irqrestore(&pSeries_lpar_tlbie_lock, flags);
1239 }
1240
1241 static void pSeries_lpar_hugepage_invalidate(unsigned long vsid,
1242                                              unsigned long addr,
1243                                              unsigned char *hpte_slot_array,
1244                                              int psize, int ssize, int local)
1245 {
1246         int i, index = 0;
1247         unsigned long s_addr = addr;
1248         unsigned int max_hpte_count, valid;
1249         unsigned long vpn_array[PPC64_HUGE_HPTE_BATCH];
1250         unsigned long slot_array[PPC64_HUGE_HPTE_BATCH];
1251         unsigned long shift, hidx, vpn = 0, hash, slot;
1252
1253         shift = mmu_psize_defs[psize].shift;
1254         max_hpte_count = 1U << (PMD_SHIFT - shift);
1255
1256         for (i = 0; i < max_hpte_count; i++) {
1257                 valid = hpte_valid(hpte_slot_array, i);
1258                 if (!valid)
1259                         continue;
1260                 hidx =  hpte_hash_index(hpte_slot_array, i);
1261
1262                 /* get the vpn */
1263                 addr = s_addr + (i * (1ul << shift));
1264                 vpn = hpt_vpn(addr, vsid, ssize);
1265                 hash = hpt_hash(vpn, shift, ssize);
1266                 if (hidx & _PTEIDX_SECONDARY)
1267                         hash = ~hash;
1268
1269                 slot = (hash & htab_hash_mask) * HPTES_PER_GROUP;
1270                 slot += hidx & _PTEIDX_GROUP_IX;
1271
1272                 slot_array[index] = slot;
1273                 vpn_array[index] = vpn;
1274                 if (index == PPC64_HUGE_HPTE_BATCH - 1) {
1275                         /*
1276                          * Now do a bluk invalidate
1277                          */
1278                         __pSeries_lpar_hugepage_invalidate(slot_array,
1279                                                            vpn_array,
1280                                                            PPC64_HUGE_HPTE_BATCH,
1281                                                            psize, ssize);
1282                         index = 0;
1283                 } else
1284                         index++;
1285         }
1286         if (index)
1287                 __pSeries_lpar_hugepage_invalidate(slot_array, vpn_array,
1288                                                    index, psize, ssize);
1289 }
1290 #else
1291 static void pSeries_lpar_hugepage_invalidate(unsigned long vsid,
1292                                              unsigned long addr,
1293                                              unsigned char *hpte_slot_array,
1294                                              int psize, int ssize, int local)
1295 {
1296         WARN(1, "%s called without THP support\n", __func__);
1297 }
1298 #endif
1299
1300 static int pSeries_lpar_hpte_removebolted(unsigned long ea,
1301                                           int psize, int ssize)
1302 {
1303         unsigned long vpn;
1304         unsigned long slot, vsid;
1305
1306         vsid = get_kernel_vsid(ea, ssize);
1307         vpn = hpt_vpn(ea, vsid, ssize);
1308
1309         slot = pSeries_lpar_hpte_find(vpn, psize, ssize);
1310         if (slot == -1)
1311                 return -ENOENT;
1312
1313         /*
1314          * lpar doesn't use the passed actual page size
1315          */
1316         pSeries_lpar_hpte_invalidate(slot, vpn, psize, 0, ssize, 0);
1317         return 0;
1318 }
1319
1320
1321 static inline unsigned long compute_slot(real_pte_t pte,
1322                                          unsigned long vpn,
1323                                          unsigned long index,
1324                                          unsigned long shift,
1325                                          int ssize)
1326 {
1327         unsigned long slot, hash, hidx;
1328
1329         hash = hpt_hash(vpn, shift, ssize);
1330         hidx = __rpte_to_hidx(pte, index);
1331         if (hidx & _PTEIDX_SECONDARY)
1332                 hash = ~hash;
1333         slot = (hash & htab_hash_mask) * HPTES_PER_GROUP;
1334         slot += hidx & _PTEIDX_GROUP_IX;
1335         return slot;
1336 }
1337
1338 /**
1339  * The hcall H_BLOCK_REMOVE implies that the virtual pages to processed are
1340  * "all within the same naturally aligned 8 page virtual address block".
1341  */
1342 static void do_block_remove(unsigned long number, struct ppc64_tlb_batch *batch,
1343                             unsigned long *param)
1344 {
1345         unsigned long vpn;
1346         unsigned long i, pix = 0;
1347         unsigned long index, shift, slot, current_vpgb, vpgb;
1348         real_pte_t pte;
1349         int psize, ssize;
1350
1351         psize = batch->psize;
1352         ssize = batch->ssize;
1353
1354         for (i = 0; i < number; i++) {
1355                 vpn = batch->vpn[i];
1356                 pte = batch->pte[i];
1357                 pte_iterate_hashed_subpages(pte, psize, vpn, index, shift) {
1358                         /*
1359                          * Shifting 3 bits more on the right to get a
1360                          * 8 pages aligned virtual addresse.
1361                          */
1362                         vpgb = (vpn >> (shift - VPN_SHIFT + 3));
1363                         if (!pix || vpgb != current_vpgb) {
1364                                 /*
1365                                  * Need to start a new 8 pages block, flush
1366                                  * the current one if needed.
1367                                  */
1368                                 if (pix)
1369                                         (void)call_block_remove(pix, param,
1370                                                                 true);
1371                                 current_vpgb = vpgb;
1372                                 param[0] = hpte_encode_avpn(vpn, psize,
1373                                                             ssize);
1374                                 pix = 1;
1375                         }
1376
1377                         slot = compute_slot(pte, vpn, index, shift, ssize);
1378                         param[pix++] = HBR_REQUEST | HBLKR_AVPN | slot;
1379
1380                         if (pix == PLPAR_HCALL9_BUFSIZE) {
1381                                 pix = call_block_remove(pix, param, false);
1382                                 /*
1383                                  * pix = 0 means that all the entries were
1384                                  * removed, we can start a new block.
1385                                  * Otherwise, this means that there are entries
1386                                  * to retry, and pix points to latest one, so
1387                                  * we should increment it and try to continue
1388                                  * the same block.
1389                                  */
1390                                 if (pix)
1391                                         pix++;
1392                         }
1393                 } pte_iterate_hashed_end();
1394         }
1395
1396         if (pix)
1397                 (void)call_block_remove(pix, param, true);
1398 }
1399
1400 /*
1401  * TLB Block Invalidate Characteristics
1402  *
1403  * These characteristics define the size of the block the hcall H_BLOCK_REMOVE
1404  * is able to process for each couple segment base page size, actual page size.
1405  *
1406  * The ibm,get-system-parameter properties is returning a buffer with the
1407  * following layout:
1408  *
1409  * [ 2 bytes size of the RTAS buffer (excluding these 2 bytes) ]
1410  * -----------------
1411  * TLB Block Invalidate Specifiers:
1412  * [ 1 byte LOG base 2 of the TLB invalidate block size being specified ]
1413  * [ 1 byte Number of page sizes (N) that are supported for the specified
1414  *          TLB invalidate block size ]
1415  * [ 1 byte Encoded segment base page size and actual page size
1416  *          MSB=0 means 4k segment base page size and actual page size
1417  *          MSB=1 the penc value in mmu_psize_def ]
1418  * ...
1419  * -----------------
1420  * Next TLB Block Invalidate Specifiers...
1421  * -----------------
1422  * [ 0 ]
1423  */
1424 static inline void set_hblkrm_bloc_size(int bpsize, int psize,
1425                                         unsigned int block_size)
1426 {
1427         if (block_size > hblkrm_size[bpsize][psize])
1428                 hblkrm_size[bpsize][psize] = block_size;
1429 }
1430
1431 /*
1432  * Decode the Encoded segment base page size and actual page size.
1433  * PAPR specifies:
1434  *   - bit 7 is the L bit
1435  *   - bits 0-5 are the penc value
1436  * If the L bit is 0, this means 4K segment base page size and actual page size
1437  * otherwise the penc value should be read.
1438  */
1439 #define HBLKRM_L_MASK           0x80
1440 #define HBLKRM_PENC_MASK        0x3f
1441 static inline void __init check_lp_set_hblkrm(unsigned int lp,
1442                                               unsigned int block_size)
1443 {
1444         unsigned int bpsize, psize;
1445
1446         /* First, check the L bit, if not set, this means 4K */
1447         if ((lp & HBLKRM_L_MASK) == 0) {
1448                 set_hblkrm_bloc_size(MMU_PAGE_4K, MMU_PAGE_4K, block_size);
1449                 return;
1450         }
1451
1452         lp &= HBLKRM_PENC_MASK;
1453         for (bpsize = 0; bpsize < MMU_PAGE_COUNT; bpsize++) {
1454                 struct mmu_psize_def *def = &mmu_psize_defs[bpsize];
1455
1456                 for (psize = 0; psize < MMU_PAGE_COUNT; psize++) {
1457                         if (def->penc[psize] == lp) {
1458                                 set_hblkrm_bloc_size(bpsize, psize, block_size);
1459                                 return;
1460                         }
1461                 }
1462         }
1463 }
1464
1465 /*
1466  * The size of the TLB Block Invalidate Characteristics is variable. But at the
1467  * maximum it will be the number of possible page sizes *2 + 10 bytes.
1468  * Currently MMU_PAGE_COUNT is 16, which means 42 bytes. Use a cache line size
1469  * (128 bytes) for the buffer to get plenty of space.
1470  */
1471 #define SPLPAR_TLB_BIC_MAXLENGTH        128
1472
1473 void __init pseries_lpar_read_hblkrm_characteristics(void)
1474 {
1475         static struct papr_sysparm_buf buf __initdata;
1476         int len, idx, bpsize;
1477
1478         if (!firmware_has_feature(FW_FEATURE_BLOCK_REMOVE))
1479                 return;
1480
1481         if (papr_sysparm_get(PAPR_SYSPARM_TLB_BLOCK_INVALIDATE_ATTRS, &buf))
1482                 return;
1483
1484         len = be16_to_cpu(buf.len);
1485         if (len > SPLPAR_TLB_BIC_MAXLENGTH) {
1486                 pr_warn("%s too large returned buffer %d", __func__, len);
1487                 return;
1488         }
1489
1490         idx = 0;
1491         while (idx < len) {
1492                 u8 block_shift = buf.val[idx++];
1493                 u32 block_size;
1494                 unsigned int npsize;
1495
1496                 if (!block_shift)
1497                         break;
1498
1499                 block_size = 1 << block_shift;
1500
1501                 for (npsize = buf.val[idx++];
1502                      npsize > 0 && idx < len; npsize--)
1503                         check_lp_set_hblkrm((unsigned int)buf.val[idx++],
1504                                             block_size);
1505         }
1506
1507         for (bpsize = 0; bpsize < MMU_PAGE_COUNT; bpsize++)
1508                 for (idx = 0; idx < MMU_PAGE_COUNT; idx++)
1509                         if (hblkrm_size[bpsize][idx])
1510                                 pr_info("H_BLOCK_REMOVE supports base psize:%d psize:%d block size:%d",
1511                                         bpsize, idx, hblkrm_size[bpsize][idx]);
1512 }
1513
1514 /*
1515  * Take a spinlock around flushes to avoid bouncing the hypervisor tlbie
1516  * lock.
1517  */
1518 static void pSeries_lpar_flush_hash_range(unsigned long number, int local)
1519 {
1520         unsigned long vpn;
1521         unsigned long i, pix, rc;
1522         unsigned long flags = 0;
1523         struct ppc64_tlb_batch *batch = this_cpu_ptr(&ppc64_tlb_batch);
1524         int lock_tlbie = !mmu_has_feature(MMU_FTR_LOCKLESS_TLBIE);
1525         unsigned long param[PLPAR_HCALL9_BUFSIZE];
1526         unsigned long index, shift, slot;
1527         real_pte_t pte;
1528         int psize, ssize;
1529
1530         if (lock_tlbie)
1531                 spin_lock_irqsave(&pSeries_lpar_tlbie_lock, flags);
1532
1533         if (is_supported_hlbkrm(batch->psize, batch->psize)) {
1534                 do_block_remove(number, batch, param);
1535                 goto out;
1536         }
1537
1538         psize = batch->psize;
1539         ssize = batch->ssize;
1540         pix = 0;
1541         for (i = 0; i < number; i++) {
1542                 vpn = batch->vpn[i];
1543                 pte = batch->pte[i];
1544                 pte_iterate_hashed_subpages(pte, psize, vpn, index, shift) {
1545                         slot = compute_slot(pte, vpn, index, shift, ssize);
1546                         if (!firmware_has_feature(FW_FEATURE_BULK_REMOVE)) {
1547                                 /*
1548                                  * lpar doesn't use the passed actual page size
1549                                  */
1550                                 pSeries_lpar_hpte_invalidate(slot, vpn, psize,
1551                                                              0, ssize, local);
1552                         } else {
1553                                 param[pix] = HBR_REQUEST | HBR_AVPN | slot;
1554                                 param[pix+1] = hpte_encode_avpn(vpn, psize,
1555                                                                 ssize);
1556                                 pix += 2;
1557                                 if (pix == 8) {
1558                                         rc = plpar_hcall9(H_BULK_REMOVE, param,
1559                                                 param[0], param[1], param[2],
1560                                                 param[3], param[4], param[5],
1561                                                 param[6], param[7]);
1562                                         BUG_ON(rc != H_SUCCESS);
1563                                         pix = 0;
1564                                 }
1565                         }
1566                 } pte_iterate_hashed_end();
1567         }
1568         if (pix) {
1569                 param[pix] = HBR_END;
1570                 rc = plpar_hcall9(H_BULK_REMOVE, param, param[0], param[1],
1571                                   param[2], param[3], param[4], param[5],
1572                                   param[6], param[7]);
1573                 BUG_ON(rc != H_SUCCESS);
1574         }
1575
1576 out:
1577         if (lock_tlbie)
1578                 spin_unlock_irqrestore(&pSeries_lpar_tlbie_lock, flags);
1579 }
1580
1581 static int __init disable_bulk_remove(char *str)
1582 {
1583         if (strcmp(str, "off") == 0 &&
1584             firmware_has_feature(FW_FEATURE_BULK_REMOVE)) {
1585                 pr_info("Disabling BULK_REMOVE firmware feature");
1586                 powerpc_firmware_features &= ~FW_FEATURE_BULK_REMOVE;
1587         }
1588         return 1;
1589 }
1590
1591 __setup("bulk_remove=", disable_bulk_remove);
1592
1593 #define HPT_RESIZE_TIMEOUT      10000 /* ms */
1594
1595 struct hpt_resize_state {
1596         unsigned long shift;
1597         int commit_rc;
1598 };
1599
1600 static int pseries_lpar_resize_hpt_commit(void *data)
1601 {
1602         struct hpt_resize_state *state = data;
1603
1604         state->commit_rc = plpar_resize_hpt_commit(0, state->shift);
1605         if (state->commit_rc != H_SUCCESS)
1606                 return -EIO;
1607
1608         /* Hypervisor has transitioned the HTAB, update our globals */
1609         ppc64_pft_size = state->shift;
1610         htab_size_bytes = 1UL << ppc64_pft_size;
1611         htab_hash_mask = (htab_size_bytes >> 7) - 1;
1612
1613         return 0;
1614 }
1615
1616 /*
1617  * Must be called in process context. The caller must hold the
1618  * cpus_lock.
1619  */
1620 static int pseries_lpar_resize_hpt(unsigned long shift)
1621 {
1622         struct hpt_resize_state state = {
1623                 .shift = shift,
1624                 .commit_rc = H_FUNCTION,
1625         };
1626         unsigned int delay, total_delay = 0;
1627         int rc;
1628         ktime_t t0, t1, t2;
1629
1630         might_sleep();
1631
1632         if (!firmware_has_feature(FW_FEATURE_HPT_RESIZE))
1633                 return -ENODEV;
1634
1635         pr_info("Attempting to resize HPT to shift %lu\n", shift);
1636
1637         t0 = ktime_get();
1638
1639         rc = plpar_resize_hpt_prepare(0, shift);
1640         while (H_IS_LONG_BUSY(rc)) {
1641                 delay = get_longbusy_msecs(rc);
1642                 total_delay += delay;
1643                 if (total_delay > HPT_RESIZE_TIMEOUT) {
1644                         /* prepare with shift==0 cancels an in-progress resize */
1645                         rc = plpar_resize_hpt_prepare(0, 0);
1646                         if (rc != H_SUCCESS)
1647                                 pr_warn("Unexpected error %d cancelling timed out HPT resize\n",
1648                                        rc);
1649                         return -ETIMEDOUT;
1650                 }
1651                 msleep(delay);
1652                 rc = plpar_resize_hpt_prepare(0, shift);
1653         }
1654
1655         switch (rc) {
1656         case H_SUCCESS:
1657                 /* Continue on */
1658                 break;
1659
1660         case H_PARAMETER:
1661                 pr_warn("Invalid argument from H_RESIZE_HPT_PREPARE\n");
1662                 return -EINVAL;
1663         case H_RESOURCE:
1664                 pr_warn("Operation not permitted from H_RESIZE_HPT_PREPARE\n");
1665                 return -EPERM;
1666         default:
1667                 pr_warn("Unexpected error %d from H_RESIZE_HPT_PREPARE\n", rc);
1668                 return -EIO;
1669         }
1670
1671         t1 = ktime_get();
1672
1673         rc = stop_machine_cpuslocked(pseries_lpar_resize_hpt_commit,
1674                                      &state, NULL);
1675
1676         t2 = ktime_get();
1677
1678         if (rc != 0) {
1679                 switch (state.commit_rc) {
1680                 case H_PTEG_FULL:
1681                         return -ENOSPC;
1682
1683                 default:
1684                         pr_warn("Unexpected error %d from H_RESIZE_HPT_COMMIT\n",
1685                                 state.commit_rc);
1686                         return -EIO;
1687                 };
1688         }
1689
1690         pr_info("HPT resize to shift %lu complete (%lld ms / %lld ms)\n",
1691                 shift, (long long) ktime_ms_delta(t1, t0),
1692                 (long long) ktime_ms_delta(t2, t1));
1693
1694         return 0;
1695 }
1696
1697 void __init hpte_init_pseries(void)
1698 {
1699         mmu_hash_ops.hpte_invalidate     = pSeries_lpar_hpte_invalidate;
1700         mmu_hash_ops.hpte_updatepp       = pSeries_lpar_hpte_updatepp;
1701         mmu_hash_ops.hpte_updateboltedpp = pSeries_lpar_hpte_updateboltedpp;
1702         mmu_hash_ops.hpte_insert         = pSeries_lpar_hpte_insert;
1703         mmu_hash_ops.hpte_remove         = pSeries_lpar_hpte_remove;
1704         mmu_hash_ops.hpte_removebolted   = pSeries_lpar_hpte_removebolted;
1705         mmu_hash_ops.flush_hash_range    = pSeries_lpar_flush_hash_range;
1706         mmu_hash_ops.hpte_clear_all      = pseries_hpte_clear_all;
1707         mmu_hash_ops.hugepage_invalidate = pSeries_lpar_hugepage_invalidate;
1708
1709         if (firmware_has_feature(FW_FEATURE_HPT_RESIZE))
1710                 mmu_hash_ops.resize_hpt = pseries_lpar_resize_hpt;
1711
1712         /*
1713          * On POWER9, we need to do a H_REGISTER_PROC_TBL hcall
1714          * to inform the hypervisor that we wish to use the HPT.
1715          */
1716         if (cpu_has_feature(CPU_FTR_ARCH_300))
1717                 pseries_lpar_register_process_table(0, 0, 0);
1718 }
1719 #endif /* CONFIG_PPC_64S_HASH_MMU */
1720
1721 #ifdef CONFIG_PPC_RADIX_MMU
1722 void __init radix_init_pseries(void)
1723 {
1724         pr_info("Using radix MMU under hypervisor\n");
1725
1726         pseries_lpar_register_process_table(__pa(process_tb),
1727                                                 0, PRTB_SIZE_SHIFT - 12);
1728 }
1729 #endif
1730
1731 #ifdef CONFIG_PPC_SMLPAR
1732 #define CMO_FREE_HINT_DEFAULT 1
1733 static int cmo_free_hint_flag = CMO_FREE_HINT_DEFAULT;
1734
1735 static int __init cmo_free_hint(char *str)
1736 {
1737         char *parm;
1738         parm = strstrip(str);
1739
1740         if (strcasecmp(parm, "no") == 0 || strcasecmp(parm, "off") == 0) {
1741                 pr_info("%s: CMO free page hinting is not active.\n", __func__);
1742                 cmo_free_hint_flag = 0;
1743                 return 1;
1744         }
1745
1746         cmo_free_hint_flag = 1;
1747         pr_info("%s: CMO free page hinting is active.\n", __func__);
1748
1749         if (strcasecmp(parm, "yes") == 0 || strcasecmp(parm, "on") == 0)
1750                 return 1;
1751
1752         return 0;
1753 }
1754
1755 __setup("cmo_free_hint=", cmo_free_hint);
1756
1757 static void pSeries_set_page_state(struct page *page, int order,
1758                                    unsigned long state)
1759 {
1760         int i, j;
1761         unsigned long cmo_page_sz, addr;
1762
1763         cmo_page_sz = cmo_get_page_size();
1764         addr = __pa((unsigned long)page_address(page));
1765
1766         for (i = 0; i < (1 << order); i++, addr += PAGE_SIZE) {
1767                 for (j = 0; j < PAGE_SIZE; j += cmo_page_sz)
1768                         plpar_hcall_norets(H_PAGE_INIT, state, addr + j, 0);
1769         }
1770 }
1771
1772 void arch_free_page(struct page *page, int order)
1773 {
1774         if (radix_enabled())
1775                 return;
1776         if (!cmo_free_hint_flag || !firmware_has_feature(FW_FEATURE_CMO))
1777                 return;
1778
1779         pSeries_set_page_state(page, order, H_PAGE_SET_UNUSED);
1780 }
1781 EXPORT_SYMBOL(arch_free_page);
1782
1783 #endif /* CONFIG_PPC_SMLPAR */
1784 #endif /* CONFIG_PPC_BOOK3S_64 */
1785
1786 #ifdef CONFIG_TRACEPOINTS
1787 #ifdef CONFIG_JUMP_LABEL
1788 struct static_key hcall_tracepoint_key = STATIC_KEY_INIT;
1789
1790 int hcall_tracepoint_regfunc(void)
1791 {
1792         static_key_slow_inc(&hcall_tracepoint_key);
1793         return 0;
1794 }
1795
1796 void hcall_tracepoint_unregfunc(void)
1797 {
1798         static_key_slow_dec(&hcall_tracepoint_key);
1799 }
1800 #else
1801 /*
1802  * We optimise our hcall path by placing hcall_tracepoint_refcount
1803  * directly in the TOC so we can check if the hcall tracepoints are
1804  * enabled via a single load.
1805  */
1806
1807 /* NB: reg/unreg are called while guarded with the tracepoints_mutex */
1808 extern long hcall_tracepoint_refcount;
1809
1810 int hcall_tracepoint_regfunc(void)
1811 {
1812         hcall_tracepoint_refcount++;
1813         return 0;
1814 }
1815
1816 void hcall_tracepoint_unregfunc(void)
1817 {
1818         hcall_tracepoint_refcount--;
1819 }
1820 #endif
1821
1822 /*
1823  * Keep track of hcall tracing depth and prevent recursion. Warn if any is
1824  * detected because it may indicate a problem. This will not catch all
1825  * problems with tracing code making hcalls, because the tracing might have
1826  * been invoked from a non-hcall, so the first hcall could recurse into it
1827  * without warning here, but this better than nothing.
1828  *
1829  * Hcalls with specific problems being traced should use the _notrace
1830  * plpar_hcall variants.
1831  */
1832 static DEFINE_PER_CPU(unsigned int, hcall_trace_depth);
1833
1834
1835 notrace void __trace_hcall_entry(unsigned long opcode, unsigned long *args)
1836 {
1837         unsigned long flags;
1838         unsigned int *depth;
1839
1840         local_irq_save(flags);
1841
1842         depth = this_cpu_ptr(&hcall_trace_depth);
1843
1844         if (WARN_ON_ONCE(*depth))
1845                 goto out;
1846
1847         (*depth)++;
1848         preempt_disable();
1849         trace_hcall_entry(opcode, args);
1850         (*depth)--;
1851
1852 out:
1853         local_irq_restore(flags);
1854 }
1855
1856 notrace void __trace_hcall_exit(long opcode, long retval, unsigned long *retbuf)
1857 {
1858         unsigned long flags;
1859         unsigned int *depth;
1860
1861         local_irq_save(flags);
1862
1863         depth = this_cpu_ptr(&hcall_trace_depth);
1864
1865         if (*depth) /* Don't warn again on the way out */
1866                 goto out;
1867
1868         (*depth)++;
1869         trace_hcall_exit(opcode, retval, retbuf);
1870         preempt_enable();
1871         (*depth)--;
1872
1873 out:
1874         local_irq_restore(flags);
1875 }
1876 #endif
1877
1878 /**
1879  * h_get_mpp
1880  * H_GET_MPP hcall returns info in 7 parms
1881  */
1882 int h_get_mpp(struct hvcall_mpp_data *mpp_data)
1883 {
1884         int rc;
1885         unsigned long retbuf[PLPAR_HCALL9_BUFSIZE];
1886
1887         rc = plpar_hcall9(H_GET_MPP, retbuf);
1888
1889         mpp_data->entitled_mem = retbuf[0];
1890         mpp_data->mapped_mem = retbuf[1];
1891
1892         mpp_data->group_num = (retbuf[2] >> 2 * 8) & 0xffff;
1893         mpp_data->pool_num = retbuf[2] & 0xffff;
1894
1895         mpp_data->mem_weight = (retbuf[3] >> 7 * 8) & 0xff;
1896         mpp_data->unallocated_mem_weight = (retbuf[3] >> 6 * 8) & 0xff;
1897         mpp_data->unallocated_entitlement = retbuf[3] & 0xffffffffffffUL;
1898
1899         mpp_data->pool_size = retbuf[4];
1900         mpp_data->loan_request = retbuf[5];
1901         mpp_data->backing_mem = retbuf[6];
1902
1903         return rc;
1904 }
1905 EXPORT_SYMBOL(h_get_mpp);
1906
1907 int h_get_mpp_x(struct hvcall_mpp_x_data *mpp_x_data)
1908 {
1909         int rc;
1910         unsigned long retbuf[PLPAR_HCALL9_BUFSIZE] = { 0 };
1911
1912         rc = plpar_hcall9(H_GET_MPP_X, retbuf);
1913
1914         mpp_x_data->coalesced_bytes = retbuf[0];
1915         mpp_x_data->pool_coalesced_bytes = retbuf[1];
1916         mpp_x_data->pool_purr_cycles = retbuf[2];
1917         mpp_x_data->pool_spurr_cycles = retbuf[3];
1918
1919         return rc;
1920 }
1921
1922 #ifdef CONFIG_PPC_64S_HASH_MMU
1923 static unsigned long __init vsid_unscramble(unsigned long vsid, int ssize)
1924 {
1925         unsigned long protovsid;
1926         unsigned long va_bits = VA_BITS;
1927         unsigned long modinv, vsid_modulus;
1928         unsigned long max_mod_inv, tmp_modinv;
1929
1930         if (!mmu_has_feature(MMU_FTR_68_BIT_VA))
1931                 va_bits = 65;
1932
1933         if (ssize == MMU_SEGSIZE_256M) {
1934                 modinv = VSID_MULINV_256M;
1935                 vsid_modulus = ((1UL << (va_bits - SID_SHIFT)) - 1);
1936         } else {
1937                 modinv = VSID_MULINV_1T;
1938                 vsid_modulus = ((1UL << (va_bits - SID_SHIFT_1T)) - 1);
1939         }
1940
1941         /*
1942          * vsid outside our range.
1943          */
1944         if (vsid >= vsid_modulus)
1945                 return 0;
1946
1947         /*
1948          * If modinv is the modular multiplicate inverse of (x % vsid_modulus)
1949          * and vsid = (protovsid * x) % vsid_modulus, then we say:
1950          *   protovsid = (vsid * modinv) % vsid_modulus
1951          */
1952
1953         /* Check if (vsid * modinv) overflow (63 bits) */
1954         max_mod_inv = 0x7fffffffffffffffull / vsid;
1955         if (modinv < max_mod_inv)
1956                 return (vsid * modinv) % vsid_modulus;
1957
1958         tmp_modinv = modinv/max_mod_inv;
1959         modinv %= max_mod_inv;
1960
1961         protovsid = (((vsid * max_mod_inv) % vsid_modulus) * tmp_modinv) % vsid_modulus;
1962         protovsid = (protovsid + vsid * modinv) % vsid_modulus;
1963
1964         return protovsid;
1965 }
1966
1967 static int __init reserve_vrma_context_id(void)
1968 {
1969         unsigned long protovsid;
1970
1971         /*
1972          * Reserve context ids which map to reserved virtual addresses. For now
1973          * we only reserve the context id which maps to the VRMA VSID. We ignore
1974          * the addresses in "ibm,adjunct-virtual-addresses" because we don't
1975          * enable adjunct support via the "ibm,client-architecture-support"
1976          * interface.
1977          */
1978         protovsid = vsid_unscramble(VRMA_VSID, MMU_SEGSIZE_1T);
1979         hash__reserve_context_id(protovsid >> ESID_BITS_1T);
1980         return 0;
1981 }
1982 machine_device_initcall(pseries, reserve_vrma_context_id);
1983 #endif
1984
1985 #ifdef CONFIG_DEBUG_FS
1986 /* debugfs file interface for vpa data */
1987 static ssize_t vpa_file_read(struct file *filp, char __user *buf, size_t len,
1988                               loff_t *pos)
1989 {
1990         int cpu = (long)filp->private_data;
1991         struct lppaca *lppaca = &lppaca_of(cpu);
1992
1993         return simple_read_from_buffer(buf, len, pos, lppaca,
1994                                 sizeof(struct lppaca));
1995 }
1996
1997 static const struct file_operations vpa_fops = {
1998         .open           = simple_open,
1999         .read           = vpa_file_read,
2000         .llseek         = default_llseek,
2001 };
2002
2003 static int __init vpa_debugfs_init(void)
2004 {
2005         char name[16];
2006         long i;
2007         struct dentry *vpa_dir;
2008
2009         if (!firmware_has_feature(FW_FEATURE_SPLPAR))
2010                 return 0;
2011
2012         vpa_dir = debugfs_create_dir("vpa", arch_debugfs_dir);
2013
2014         /* set up the per-cpu vpa file*/
2015         for_each_possible_cpu(i) {
2016                 sprintf(name, "cpu-%ld", i);
2017                 debugfs_create_file(name, 0400, vpa_dir, (void *)i, &vpa_fops);
2018         }
2019
2020         return 0;
2021 }
2022 machine_arch_initcall(pseries, vpa_debugfs_init);
2023 #endif /* CONFIG_DEBUG_FS */