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