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