~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/arch/powerpc/kvm/book3s_hv.c

Version: ~ [ linux-5.2-rc5 ] ~ [ linux-5.1.12 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.53 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.128 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.182 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.182 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.68 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.102 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.39.4 ] ~ [ linux-2.6.38.8 ] ~ [ linux-2.6.37.6 ] ~ [ linux-2.6.36.4 ] ~ [ linux-2.6.35.14 ] ~ [ linux-2.6.34.15 ] ~ [ linux-2.6.33.20 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 /*
  2  * Copyright 2011 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
  3  * Copyright (C) 2009. SUSE Linux Products GmbH. All rights reserved.
  4  *
  5  * Authors:
  6  *    Paul Mackerras <paulus@au1.ibm.com>
  7  *    Alexander Graf <agraf@suse.de>
  8  *    Kevin Wolf <mail@kevin-wolf.de>
  9  *
 10  * Description: KVM functions specific to running on Book 3S
 11  * processors in hypervisor mode (specifically POWER7 and later).
 12  *
 13  * This file is derived from arch/powerpc/kvm/book3s.c,
 14  * by Alexander Graf <agraf@suse.de>.
 15  *
 16  * This program is free software; you can redistribute it and/or modify
 17  * it under the terms of the GNU General Public License, version 2, as
 18  * published by the Free Software Foundation.
 19  */
 20 
 21 #include <linux/kvm_host.h>
 22 #include <linux/err.h>
 23 #include <linux/slab.h>
 24 #include <linux/preempt.h>
 25 #include <linux/sched.h>
 26 #include <linux/delay.h>
 27 #include <linux/export.h>
 28 #include <linux/fs.h>
 29 #include <linux/anon_inodes.h>
 30 #include <linux/cpu.h>
 31 #include <linux/cpumask.h>
 32 #include <linux/spinlock.h>
 33 #include <linux/page-flags.h>
 34 #include <linux/srcu.h>
 35 #include <linux/miscdevice.h>
 36 #include <linux/debugfs.h>
 37 
 38 #include <asm/reg.h>
 39 #include <asm/cputable.h>
 40 #include <asm/cacheflush.h>
 41 #include <asm/tlbflush.h>
 42 #include <asm/uaccess.h>
 43 #include <asm/io.h>
 44 #include <asm/kvm_ppc.h>
 45 #include <asm/kvm_book3s.h>
 46 #include <asm/mmu_context.h>
 47 #include <asm/lppaca.h>
 48 #include <asm/processor.h>
 49 #include <asm/cputhreads.h>
 50 #include <asm/page.h>
 51 #include <asm/hvcall.h>
 52 #include <asm/switch_to.h>
 53 #include <asm/smp.h>
 54 #include <asm/dbell.h>
 55 #include <asm/hmi.h>
 56 #include <linux/gfp.h>
 57 #include <linux/vmalloc.h>
 58 #include <linux/highmem.h>
 59 #include <linux/hugetlb.h>
 60 #include <linux/module.h>
 61 
 62 #include "book3s.h"
 63 
 64 #define CREATE_TRACE_POINTS
 65 #include "trace_hv.h"
 66 
 67 /* #define EXIT_DEBUG */
 68 /* #define EXIT_DEBUG_SIMPLE */
 69 /* #define EXIT_DEBUG_INT */
 70 
 71 /* Used to indicate that a guest page fault needs to be handled */
 72 #define RESUME_PAGE_FAULT       (RESUME_GUEST | RESUME_FLAG_ARCH1)
 73 
 74 /* Used as a "null" value for timebase values */
 75 #define TB_NIL  (~(u64)0)
 76 
 77 static DECLARE_BITMAP(default_enabled_hcalls, MAX_HCALL_OPCODE/4 + 1);
 78 
 79 static int dynamic_mt_modes = 6;
 80 module_param(dynamic_mt_modes, int, S_IRUGO | S_IWUSR);
 81 MODULE_PARM_DESC(dynamic_mt_modes, "Set of allowed dynamic micro-threading modes: 0 (= none), 2, 4, or 6 (= 2 or 4)");
 82 static int target_smt_mode;
 83 module_param(target_smt_mode, int, S_IRUGO | S_IWUSR);
 84 MODULE_PARM_DESC(target_smt_mode, "Target threads per core (0 = max)");
 85 
 86 #ifdef CONFIG_KVM_XICS
 87 static struct kernel_param_ops module_param_ops = {
 88         .set = param_set_int,
 89         .get = param_get_int,
 90 };
 91 
 92 module_param_cb(h_ipi_redirect, &module_param_ops, &h_ipi_redirect,
 93                                                         S_IRUGO | S_IWUSR);
 94 MODULE_PARM_DESC(h_ipi_redirect, "Redirect H_IPI wakeup to a free host core");
 95 #endif
 96 
 97 static void kvmppc_end_cede(struct kvm_vcpu *vcpu);
 98 static int kvmppc_hv_setup_htab_rma(struct kvm_vcpu *vcpu);
 99 
100 static bool kvmppc_ipi_thread(int cpu)
101 {
102         /* On POWER8 for IPIs to threads in the same core, use msgsnd */
103         if (cpu_has_feature(CPU_FTR_ARCH_207S)) {
104                 preempt_disable();
105                 if (cpu_first_thread_sibling(cpu) ==
106                     cpu_first_thread_sibling(smp_processor_id())) {
107                         unsigned long msg = PPC_DBELL_TYPE(PPC_DBELL_SERVER);
108                         msg |= cpu_thread_in_core(cpu);
109                         smp_mb();
110                         __asm__ __volatile__ (PPC_MSGSND(%0) : : "r" (msg));
111                         preempt_enable();
112                         return true;
113                 }
114                 preempt_enable();
115         }
116 
117 #if defined(CONFIG_PPC_ICP_NATIVE) && defined(CONFIG_SMP)
118         if (cpu >= 0 && cpu < nr_cpu_ids && paca[cpu].kvm_hstate.xics_phys) {
119                 xics_wake_cpu(cpu);
120                 return true;
121         }
122 #endif
123 
124         return false;
125 }
126 
127 static void kvmppc_fast_vcpu_kick_hv(struct kvm_vcpu *vcpu)
128 {
129         int cpu;
130         struct swait_queue_head *wqp;
131 
132         wqp = kvm_arch_vcpu_wq(vcpu);
133         if (swait_active(wqp)) {
134                 swake_up(wqp);
135                 ++vcpu->stat.halt_wakeup;
136         }
137 
138         if (kvmppc_ipi_thread(vcpu->arch.thread_cpu))
139                 return;
140 
141         /* CPU points to the first thread of the core */
142         cpu = vcpu->cpu;
143         if (cpu >= 0 && cpu < nr_cpu_ids && cpu_online(cpu))
144                 smp_send_reschedule(cpu);
145 }
146 
147 /*
148  * We use the vcpu_load/put functions to measure stolen time.
149  * Stolen time is counted as time when either the vcpu is able to
150  * run as part of a virtual core, but the task running the vcore
151  * is preempted or sleeping, or when the vcpu needs something done
152  * in the kernel by the task running the vcpu, but that task is
153  * preempted or sleeping.  Those two things have to be counted
154  * separately, since one of the vcpu tasks will take on the job
155  * of running the core, and the other vcpu tasks in the vcore will
156  * sleep waiting for it to do that, but that sleep shouldn't count
157  * as stolen time.
158  *
159  * Hence we accumulate stolen time when the vcpu can run as part of
160  * a vcore using vc->stolen_tb, and the stolen time when the vcpu
161  * needs its task to do other things in the kernel (for example,
162  * service a page fault) in busy_stolen.  We don't accumulate
163  * stolen time for a vcore when it is inactive, or for a vcpu
164  * when it is in state RUNNING or NOTREADY.  NOTREADY is a bit of
165  * a misnomer; it means that the vcpu task is not executing in
166  * the KVM_VCPU_RUN ioctl, i.e. it is in userspace or elsewhere in
167  * the kernel.  We don't have any way of dividing up that time
168  * between time that the vcpu is genuinely stopped, time that
169  * the task is actively working on behalf of the vcpu, and time
170  * that the task is preempted, so we don't count any of it as
171  * stolen.
172  *
173  * Updates to busy_stolen are protected by arch.tbacct_lock;
174  * updates to vc->stolen_tb are protected by the vcore->stoltb_lock
175  * lock.  The stolen times are measured in units of timebase ticks.
176  * (Note that the != TB_NIL checks below are purely defensive;
177  * they should never fail.)
178  */
179 
180 static void kvmppc_core_start_stolen(struct kvmppc_vcore *vc)
181 {
182         unsigned long flags;
183 
184         spin_lock_irqsave(&vc->stoltb_lock, flags);
185         vc->preempt_tb = mftb();
186         spin_unlock_irqrestore(&vc->stoltb_lock, flags);
187 }
188 
189 static void kvmppc_core_end_stolen(struct kvmppc_vcore *vc)
190 {
191         unsigned long flags;
192 
193         spin_lock_irqsave(&vc->stoltb_lock, flags);
194         if (vc->preempt_tb != TB_NIL) {
195                 vc->stolen_tb += mftb() - vc->preempt_tb;
196                 vc->preempt_tb = TB_NIL;
197         }
198         spin_unlock_irqrestore(&vc->stoltb_lock, flags);
199 }
200 
201 static void kvmppc_core_vcpu_load_hv(struct kvm_vcpu *vcpu, int cpu)
202 {
203         struct kvmppc_vcore *vc = vcpu->arch.vcore;
204         unsigned long flags;
205 
206         /*
207          * We can test vc->runner without taking the vcore lock,
208          * because only this task ever sets vc->runner to this
209          * vcpu, and once it is set to this vcpu, only this task
210          * ever sets it to NULL.
211          */
212         if (vc->runner == vcpu && vc->vcore_state >= VCORE_SLEEPING)
213                 kvmppc_core_end_stolen(vc);
214 
215         spin_lock_irqsave(&vcpu->arch.tbacct_lock, flags);
216         if (vcpu->arch.state == KVMPPC_VCPU_BUSY_IN_HOST &&
217             vcpu->arch.busy_preempt != TB_NIL) {
218                 vcpu->arch.busy_stolen += mftb() - vcpu->arch.busy_preempt;
219                 vcpu->arch.busy_preempt = TB_NIL;
220         }
221         spin_unlock_irqrestore(&vcpu->arch.tbacct_lock, flags);
222 }
223 
224 static void kvmppc_core_vcpu_put_hv(struct kvm_vcpu *vcpu)
225 {
226         struct kvmppc_vcore *vc = vcpu->arch.vcore;
227         unsigned long flags;
228 
229         if (vc->runner == vcpu && vc->vcore_state >= VCORE_SLEEPING)
230                 kvmppc_core_start_stolen(vc);
231 
232         spin_lock_irqsave(&vcpu->arch.tbacct_lock, flags);
233         if (vcpu->arch.state == KVMPPC_VCPU_BUSY_IN_HOST)
234                 vcpu->arch.busy_preempt = mftb();
235         spin_unlock_irqrestore(&vcpu->arch.tbacct_lock, flags);
236 }
237 
238 static void kvmppc_set_msr_hv(struct kvm_vcpu *vcpu, u64 msr)
239 {
240         /*
241          * Check for illegal transactional state bit combination
242          * and if we find it, force the TS field to a safe state.
243          */
244         if ((msr & MSR_TS_MASK) == MSR_TS_MASK)
245                 msr &= ~MSR_TS_MASK;
246         vcpu->arch.shregs.msr = msr;
247         kvmppc_end_cede(vcpu);
248 }
249 
250 static void kvmppc_set_pvr_hv(struct kvm_vcpu *vcpu, u32 pvr)
251 {
252         vcpu->arch.pvr = pvr;
253 }
254 
255 static int kvmppc_set_arch_compat(struct kvm_vcpu *vcpu, u32 arch_compat)
256 {
257         unsigned long pcr = 0;
258         struct kvmppc_vcore *vc = vcpu->arch.vcore;
259 
260         if (arch_compat) {
261                 switch (arch_compat) {
262                 case PVR_ARCH_205:
263                         /*
264                          * If an arch bit is set in PCR, all the defined
265                          * higher-order arch bits also have to be set.
266                          */
267                         pcr = PCR_ARCH_206 | PCR_ARCH_205;
268                         break;
269                 case PVR_ARCH_206:
270                 case PVR_ARCH_206p:
271                         pcr = PCR_ARCH_206;
272                         break;
273                 case PVR_ARCH_207:
274                         break;
275                 default:
276                         return -EINVAL;
277                 }
278 
279                 if (!cpu_has_feature(CPU_FTR_ARCH_207S)) {
280                         /* POWER7 can't emulate POWER8 */
281                         if (!(pcr & PCR_ARCH_206))
282                                 return -EINVAL;
283                         pcr &= ~PCR_ARCH_206;
284                 }
285         }
286 
287         spin_lock(&vc->lock);
288         vc->arch_compat = arch_compat;
289         vc->pcr = pcr;
290         spin_unlock(&vc->lock);
291 
292         return 0;
293 }
294 
295 static void kvmppc_dump_regs(struct kvm_vcpu *vcpu)
296 {
297         int r;
298 
299         pr_err("vcpu %p (%d):\n", vcpu, vcpu->vcpu_id);
300         pr_err("pc  = %.16lx  msr = %.16llx  trap = %x\n",
301                vcpu->arch.pc, vcpu->arch.shregs.msr, vcpu->arch.trap);
302         for (r = 0; r < 16; ++r)
303                 pr_err("r%2d = %.16lx  r%d = %.16lx\n",
304                        r, kvmppc_get_gpr(vcpu, r),
305                        r+16, kvmppc_get_gpr(vcpu, r+16));
306         pr_err("ctr = %.16lx  lr  = %.16lx\n",
307                vcpu->arch.ctr, vcpu->arch.lr);
308         pr_err("srr0 = %.16llx srr1 = %.16llx\n",
309                vcpu->arch.shregs.srr0, vcpu->arch.shregs.srr1);
310         pr_err("sprg0 = %.16llx sprg1 = %.16llx\n",
311                vcpu->arch.shregs.sprg0, vcpu->arch.shregs.sprg1);
312         pr_err("sprg2 = %.16llx sprg3 = %.16llx\n",
313                vcpu->arch.shregs.sprg2, vcpu->arch.shregs.sprg3);
314         pr_err("cr = %.8x  xer = %.16lx  dsisr = %.8x\n",
315                vcpu->arch.cr, vcpu->arch.xer, vcpu->arch.shregs.dsisr);
316         pr_err("dar = %.16llx\n", vcpu->arch.shregs.dar);
317         pr_err("fault dar = %.16lx dsisr = %.8x\n",
318                vcpu->arch.fault_dar, vcpu->arch.fault_dsisr);
319         pr_err("SLB (%d entries):\n", vcpu->arch.slb_max);
320         for (r = 0; r < vcpu->arch.slb_max; ++r)
321                 pr_err("  ESID = %.16llx VSID = %.16llx\n",
322                        vcpu->arch.slb[r].orige, vcpu->arch.slb[r].origv);
323         pr_err("lpcr = %.16lx sdr1 = %.16lx last_inst = %.8x\n",
324                vcpu->arch.vcore->lpcr, vcpu->kvm->arch.sdr1,
325                vcpu->arch.last_inst);
326 }
327 
328 static struct kvm_vcpu *kvmppc_find_vcpu(struct kvm *kvm, int id)
329 {
330         struct kvm_vcpu *ret;
331 
332         mutex_lock(&kvm->lock);
333         ret = kvm_get_vcpu_by_id(kvm, id);
334         mutex_unlock(&kvm->lock);
335         return ret;
336 }
337 
338 static void init_vpa(struct kvm_vcpu *vcpu, struct lppaca *vpa)
339 {
340         vpa->__old_status |= LPPACA_OLD_SHARED_PROC;
341         vpa->yield_count = cpu_to_be32(1);
342 }
343 
344 static int set_vpa(struct kvm_vcpu *vcpu, struct kvmppc_vpa *v,
345                    unsigned long addr, unsigned long len)
346 {
347         /* check address is cacheline aligned */
348         if (addr & (L1_CACHE_BYTES - 1))
349                 return -EINVAL;
350         spin_lock(&vcpu->arch.vpa_update_lock);
351         if (v->next_gpa != addr || v->len != len) {
352                 v->next_gpa = addr;
353                 v->len = addr ? len : 0;
354                 v->update_pending = 1;
355         }
356         spin_unlock(&vcpu->arch.vpa_update_lock);
357         return 0;
358 }
359 
360 /* Length for a per-processor buffer is passed in at offset 4 in the buffer */
361 struct reg_vpa {
362         u32 dummy;
363         union {
364                 __be16 hword;
365                 __be32 word;
366         } length;
367 };
368 
369 static int vpa_is_registered(struct kvmppc_vpa *vpap)
370 {
371         if (vpap->update_pending)
372                 return vpap->next_gpa != 0;
373         return vpap->pinned_addr != NULL;
374 }
375 
376 static unsigned long do_h_register_vpa(struct kvm_vcpu *vcpu,
377                                        unsigned long flags,
378                                        unsigned long vcpuid, unsigned long vpa)
379 {
380         struct kvm *kvm = vcpu->kvm;
381         unsigned long len, nb;
382         void *va;
383         struct kvm_vcpu *tvcpu;
384         int err;
385         int subfunc;
386         struct kvmppc_vpa *vpap;
387 
388         tvcpu = kvmppc_find_vcpu(kvm, vcpuid);
389         if (!tvcpu)
390                 return H_PARAMETER;
391 
392         subfunc = (flags >> H_VPA_FUNC_SHIFT) & H_VPA_FUNC_MASK;
393         if (subfunc == H_VPA_REG_VPA || subfunc == H_VPA_REG_DTL ||
394             subfunc == H_VPA_REG_SLB) {
395                 /* Registering new area - address must be cache-line aligned */
396                 if ((vpa & (L1_CACHE_BYTES - 1)) || !vpa)
397                         return H_PARAMETER;
398 
399                 /* convert logical addr to kernel addr and read length */
400                 va = kvmppc_pin_guest_page(kvm, vpa, &nb);
401                 if (va == NULL)
402                         return H_PARAMETER;
403                 if (subfunc == H_VPA_REG_VPA)
404                         len = be16_to_cpu(((struct reg_vpa *)va)->length.hword);
405                 else
406                         len = be32_to_cpu(((struct reg_vpa *)va)->length.word);
407                 kvmppc_unpin_guest_page(kvm, va, vpa, false);
408 
409                 /* Check length */
410                 if (len > nb || len < sizeof(struct reg_vpa))
411                         return H_PARAMETER;
412         } else {
413                 vpa = 0;
414                 len = 0;
415         }
416 
417         err = H_PARAMETER;
418         vpap = NULL;
419         spin_lock(&tvcpu->arch.vpa_update_lock);
420 
421         switch (subfunc) {
422         case H_VPA_REG_VPA:             /* register VPA */
423                 if (len < sizeof(struct lppaca))
424                         break;
425                 vpap = &tvcpu->arch.vpa;
426                 err = 0;
427                 break;
428 
429         case H_VPA_REG_DTL:             /* register DTL */
430                 if (len < sizeof(struct dtl_entry))
431                         break;
432                 len -= len % sizeof(struct dtl_entry);
433 
434                 /* Check that they have previously registered a VPA */
435                 err = H_RESOURCE;
436                 if (!vpa_is_registered(&tvcpu->arch.vpa))
437                         break;
438 
439                 vpap = &tvcpu->arch.dtl;
440                 err = 0;
441                 break;
442 
443         case H_VPA_REG_SLB:             /* register SLB shadow buffer */
444                 /* Check that they have previously registered a VPA */
445                 err = H_RESOURCE;
446                 if (!vpa_is_registered(&tvcpu->arch.vpa))
447                         break;
448 
449                 vpap = &tvcpu->arch.slb_shadow;
450                 err = 0;
451                 break;
452 
453         case H_VPA_DEREG_VPA:           /* deregister VPA */
454                 /* Check they don't still have a DTL or SLB buf registered */
455                 err = H_RESOURCE;
456                 if (vpa_is_registered(&tvcpu->arch.dtl) ||
457                     vpa_is_registered(&tvcpu->arch.slb_shadow))
458                         break;
459 
460                 vpap = &tvcpu->arch.vpa;
461                 err = 0;
462                 break;
463 
464         case H_VPA_DEREG_DTL:           /* deregister DTL */
465                 vpap = &tvcpu->arch.dtl;
466                 err = 0;
467                 break;
468 
469         case H_VPA_DEREG_SLB:           /* deregister SLB shadow buffer */
470                 vpap = &tvcpu->arch.slb_shadow;
471                 err = 0;
472                 break;
473         }
474 
475         if (vpap) {
476                 vpap->next_gpa = vpa;
477                 vpap->len = len;
478                 vpap->update_pending = 1;
479         }
480 
481         spin_unlock(&tvcpu->arch.vpa_update_lock);
482 
483         return err;
484 }
485 
486 static void kvmppc_update_vpa(struct kvm_vcpu *vcpu, struct kvmppc_vpa *vpap)
487 {
488         struct kvm *kvm = vcpu->kvm;
489         void *va;
490         unsigned long nb;
491         unsigned long gpa;
492 
493         /*
494          * We need to pin the page pointed to by vpap->next_gpa,
495          * but we can't call kvmppc_pin_guest_page under the lock
496          * as it does get_user_pages() and down_read().  So we
497          * have to drop the lock, pin the page, then get the lock
498          * again and check that a new area didn't get registered
499          * in the meantime.
500          */
501         for (;;) {
502                 gpa = vpap->next_gpa;
503                 spin_unlock(&vcpu->arch.vpa_update_lock);
504                 va = NULL;
505                 nb = 0;
506                 if (gpa)
507                         va = kvmppc_pin_guest_page(kvm, gpa, &nb);
508                 spin_lock(&vcpu->arch.vpa_update_lock);
509                 if (gpa == vpap->next_gpa)
510                         break;
511                 /* sigh... unpin that one and try again */
512                 if (va)
513                         kvmppc_unpin_guest_page(kvm, va, gpa, false);
514         }
515 
516         vpap->update_pending = 0;
517         if (va && nb < vpap->len) {
518                 /*
519                  * If it's now too short, it must be that userspace
520                  * has changed the mappings underlying guest memory,
521                  * so unregister the region.
522                  */
523                 kvmppc_unpin_guest_page(kvm, va, gpa, false);
524                 va = NULL;
525         }
526         if (vpap->pinned_addr)
527                 kvmppc_unpin_guest_page(kvm, vpap->pinned_addr, vpap->gpa,
528                                         vpap->dirty);
529         vpap->gpa = gpa;
530         vpap->pinned_addr = va;
531         vpap->dirty = false;
532         if (va)
533                 vpap->pinned_end = va + vpap->len;
534 }
535 
536 static void kvmppc_update_vpas(struct kvm_vcpu *vcpu)
537 {
538         if (!(vcpu->arch.vpa.update_pending ||
539               vcpu->arch.slb_shadow.update_pending ||
540               vcpu->arch.dtl.update_pending))
541                 return;
542 
543         spin_lock(&vcpu->arch.vpa_update_lock);
544         if (vcpu->arch.vpa.update_pending) {
545                 kvmppc_update_vpa(vcpu, &vcpu->arch.vpa);
546                 if (vcpu->arch.vpa.pinned_addr)
547                         init_vpa(vcpu, vcpu->arch.vpa.pinned_addr);
548         }
549         if (vcpu->arch.dtl.update_pending) {
550                 kvmppc_update_vpa(vcpu, &vcpu->arch.dtl);
551                 vcpu->arch.dtl_ptr = vcpu->arch.dtl.pinned_addr;
552                 vcpu->arch.dtl_index = 0;
553         }
554         if (vcpu->arch.slb_shadow.update_pending)
555                 kvmppc_update_vpa(vcpu, &vcpu->arch.slb_shadow);
556         spin_unlock(&vcpu->arch.vpa_update_lock);
557 }
558 
559 /*
560  * Return the accumulated stolen time for the vcore up until `now'.
561  * The caller should hold the vcore lock.
562  */
563 static u64 vcore_stolen_time(struct kvmppc_vcore *vc, u64 now)
564 {
565         u64 p;
566         unsigned long flags;
567 
568         spin_lock_irqsave(&vc->stoltb_lock, flags);
569         p = vc->stolen_tb;
570         if (vc->vcore_state != VCORE_INACTIVE &&
571             vc->preempt_tb != TB_NIL)
572                 p += now - vc->preempt_tb;
573         spin_unlock_irqrestore(&vc->stoltb_lock, flags);
574         return p;
575 }
576 
577 static void kvmppc_create_dtl_entry(struct kvm_vcpu *vcpu,
578                                     struct kvmppc_vcore *vc)
579 {
580         struct dtl_entry *dt;
581         struct lppaca *vpa;
582         unsigned long stolen;
583         unsigned long core_stolen;
584         u64 now;
585 
586         dt = vcpu->arch.dtl_ptr;
587         vpa = vcpu->arch.vpa.pinned_addr;
588         now = mftb();
589         core_stolen = vcore_stolen_time(vc, now);
590         stolen = core_stolen - vcpu->arch.stolen_logged;
591         vcpu->arch.stolen_logged = core_stolen;
592         spin_lock_irq(&vcpu->arch.tbacct_lock);
593         stolen += vcpu->arch.busy_stolen;
594         vcpu->arch.busy_stolen = 0;
595         spin_unlock_irq(&vcpu->arch.tbacct_lock);
596         if (!dt || !vpa)
597                 return;
598         memset(dt, 0, sizeof(struct dtl_entry));
599         dt->dispatch_reason = 7;
600         dt->processor_id = cpu_to_be16(vc->pcpu + vcpu->arch.ptid);
601         dt->timebase = cpu_to_be64(now + vc->tb_offset);
602         dt->enqueue_to_dispatch_time = cpu_to_be32(stolen);
603         dt->srr0 = cpu_to_be64(kvmppc_get_pc(vcpu));
604         dt->srr1 = cpu_to_be64(vcpu->arch.shregs.msr);
605         ++dt;
606         if (dt == vcpu->arch.dtl.pinned_end)
607                 dt = vcpu->arch.dtl.pinned_addr;
608         vcpu->arch.dtl_ptr = dt;
609         /* order writing *dt vs. writing vpa->dtl_idx */
610         smp_wmb();
611         vpa->dtl_idx = cpu_to_be64(++vcpu->arch.dtl_index);
612         vcpu->arch.dtl.dirty = true;
613 }
614 
615 static bool kvmppc_power8_compatible(struct kvm_vcpu *vcpu)
616 {
617         if (vcpu->arch.vcore->arch_compat >= PVR_ARCH_207)
618                 return true;
619         if ((!vcpu->arch.vcore->arch_compat) &&
620             cpu_has_feature(CPU_FTR_ARCH_207S))
621                 return true;
622         return false;
623 }
624 
625 static int kvmppc_h_set_mode(struct kvm_vcpu *vcpu, unsigned long mflags,
626                              unsigned long resource, unsigned long value1,
627                              unsigned long value2)
628 {
629         switch (resource) {
630         case H_SET_MODE_RESOURCE_SET_CIABR:
631                 if (!kvmppc_power8_compatible(vcpu))
632                         return H_P2;
633                 if (value2)
634                         return H_P4;
635                 if (mflags)
636                         return H_UNSUPPORTED_FLAG_START;
637                 /* Guests can't breakpoint the hypervisor */
638                 if ((value1 & CIABR_PRIV) == CIABR_PRIV_HYPER)
639                         return H_P3;
640                 vcpu->arch.ciabr  = value1;
641                 return H_SUCCESS;
642         case H_SET_MODE_RESOURCE_SET_DAWR:
643                 if (!kvmppc_power8_compatible(vcpu))
644                         return H_P2;
645                 if (mflags)
646                         return H_UNSUPPORTED_FLAG_START;
647                 if (value2 & DABRX_HYP)
648                         return H_P4;
649                 vcpu->arch.dawr  = value1;
650                 vcpu->arch.dawrx = value2;
651                 return H_SUCCESS;
652         default:
653                 return H_TOO_HARD;
654         }
655 }
656 
657 static int kvm_arch_vcpu_yield_to(struct kvm_vcpu *target)
658 {
659         struct kvmppc_vcore *vcore = target->arch.vcore;
660 
661         /*
662          * We expect to have been called by the real mode handler
663          * (kvmppc_rm_h_confer()) which would have directly returned
664          * H_SUCCESS if the source vcore wasn't idle (e.g. if it may
665          * have useful work to do and should not confer) so we don't
666          * recheck that here.
667          */
668 
669         spin_lock(&vcore->lock);
670         if (target->arch.state == KVMPPC_VCPU_RUNNABLE &&
671             vcore->vcore_state != VCORE_INACTIVE &&
672             vcore->runner)
673                 target = vcore->runner;
674         spin_unlock(&vcore->lock);
675 
676         return kvm_vcpu_yield_to(target);
677 }
678 
679 static int kvmppc_get_yield_count(struct kvm_vcpu *vcpu)
680 {
681         int yield_count = 0;
682         struct lppaca *lppaca;
683 
684         spin_lock(&vcpu->arch.vpa_update_lock);
685         lppaca = (struct lppaca *)vcpu->arch.vpa.pinned_addr;
686         if (lppaca)
687                 yield_count = be32_to_cpu(lppaca->yield_count);
688         spin_unlock(&vcpu->arch.vpa_update_lock);
689         return yield_count;
690 }
691 
692 int kvmppc_pseries_do_hcall(struct kvm_vcpu *vcpu)
693 {
694         unsigned long req = kvmppc_get_gpr(vcpu, 3);
695         unsigned long target, ret = H_SUCCESS;
696         int yield_count;
697         struct kvm_vcpu *tvcpu;
698         int idx, rc;
699 
700         if (req <= MAX_HCALL_OPCODE &&
701             !test_bit(req/4, vcpu->kvm->arch.enabled_hcalls))
702                 return RESUME_HOST;
703 
704         switch (req) {
705         case H_CEDE:
706                 break;
707         case H_PROD:
708                 target = kvmppc_get_gpr(vcpu, 4);
709                 tvcpu = kvmppc_find_vcpu(vcpu->kvm, target);
710                 if (!tvcpu) {
711                         ret = H_PARAMETER;
712                         break;
713                 }
714                 tvcpu->arch.prodded = 1;
715                 smp_mb();
716                 if (vcpu->arch.ceded) {
717                         if (swait_active(&vcpu->wq)) {
718                                 swake_up(&vcpu->wq);
719                                 vcpu->stat.halt_wakeup++;
720                         }
721                 }
722                 break;
723         case H_CONFER:
724                 target = kvmppc_get_gpr(vcpu, 4);
725                 if (target == -1)
726                         break;
727                 tvcpu = kvmppc_find_vcpu(vcpu->kvm, target);
728                 if (!tvcpu) {
729                         ret = H_PARAMETER;
730                         break;
731                 }
732                 yield_count = kvmppc_get_gpr(vcpu, 5);
733                 if (kvmppc_get_yield_count(tvcpu) != yield_count)
734                         break;
735                 kvm_arch_vcpu_yield_to(tvcpu);
736                 break;
737         case H_REGISTER_VPA:
738                 ret = do_h_register_vpa(vcpu, kvmppc_get_gpr(vcpu, 4),
739                                         kvmppc_get_gpr(vcpu, 5),
740                                         kvmppc_get_gpr(vcpu, 6));
741                 break;
742         case H_RTAS:
743                 if (list_empty(&vcpu->kvm->arch.rtas_tokens))
744                         return RESUME_HOST;
745 
746                 idx = srcu_read_lock(&vcpu->kvm->srcu);
747                 rc = kvmppc_rtas_hcall(vcpu);
748                 srcu_read_unlock(&vcpu->kvm->srcu, idx);
749 
750                 if (rc == -ENOENT)
751                         return RESUME_HOST;
752                 else if (rc == 0)
753                         break;
754 
755                 /* Send the error out to userspace via KVM_RUN */
756                 return rc;
757         case H_LOGICAL_CI_LOAD:
758                 ret = kvmppc_h_logical_ci_load(vcpu);
759                 if (ret == H_TOO_HARD)
760                         return RESUME_HOST;
761                 break;
762         case H_LOGICAL_CI_STORE:
763                 ret = kvmppc_h_logical_ci_store(vcpu);
764                 if (ret == H_TOO_HARD)
765                         return RESUME_HOST;
766                 break;
767         case H_SET_MODE:
768                 ret = kvmppc_h_set_mode(vcpu, kvmppc_get_gpr(vcpu, 4),
769                                         kvmppc_get_gpr(vcpu, 5),
770                                         kvmppc_get_gpr(vcpu, 6),
771                                         kvmppc_get_gpr(vcpu, 7));
772                 if (ret == H_TOO_HARD)
773                         return RESUME_HOST;
774                 break;
775         case H_XIRR:
776         case H_CPPR:
777         case H_EOI:
778         case H_IPI:
779         case H_IPOLL:
780         case H_XIRR_X:
781                 if (kvmppc_xics_enabled(vcpu)) {
782                         ret = kvmppc_xics_hcall(vcpu, req);
783                         break;
784                 }
785                 return RESUME_HOST;
786         case H_PUT_TCE:
787                 ret = kvmppc_h_put_tce(vcpu, kvmppc_get_gpr(vcpu, 4),
788                                                 kvmppc_get_gpr(vcpu, 5),
789                                                 kvmppc_get_gpr(vcpu, 6));
790                 if (ret == H_TOO_HARD)
791                         return RESUME_HOST;
792                 break;
793         case H_PUT_TCE_INDIRECT:
794                 ret = kvmppc_h_put_tce_indirect(vcpu, kvmppc_get_gpr(vcpu, 4),
795                                                 kvmppc_get_gpr(vcpu, 5),
796                                                 kvmppc_get_gpr(vcpu, 6),
797                                                 kvmppc_get_gpr(vcpu, 7));
798                 if (ret == H_TOO_HARD)
799                         return RESUME_HOST;
800                 break;
801         case H_STUFF_TCE:
802                 ret = kvmppc_h_stuff_tce(vcpu, kvmppc_get_gpr(vcpu, 4),
803                                                 kvmppc_get_gpr(vcpu, 5),
804                                                 kvmppc_get_gpr(vcpu, 6),
805                                                 kvmppc_get_gpr(vcpu, 7));
806                 if (ret == H_TOO_HARD)
807                         return RESUME_HOST;
808                 break;
809         default:
810                 return RESUME_HOST;
811         }
812         kvmppc_set_gpr(vcpu, 3, ret);
813         vcpu->arch.hcall_needed = 0;
814         return RESUME_GUEST;
815 }
816 
817 static int kvmppc_hcall_impl_hv(unsigned long cmd)
818 {
819         switch (cmd) {
820         case H_CEDE:
821         case H_PROD:
822         case H_CONFER:
823         case H_REGISTER_VPA:
824         case H_SET_MODE:
825         case H_LOGICAL_CI_LOAD:
826         case H_LOGICAL_CI_STORE:
827 #ifdef CONFIG_KVM_XICS
828         case H_XIRR:
829         case H_CPPR:
830         case H_EOI:
831         case H_IPI:
832         case H_IPOLL:
833         case H_XIRR_X:
834 #endif
835                 return 1;
836         }
837 
838         /* See if it's in the real-mode table */
839         return kvmppc_hcall_impl_hv_realmode(cmd);
840 }
841 
842 static int kvmppc_emulate_debug_inst(struct kvm_run *run,
843                                         struct kvm_vcpu *vcpu)
844 {
845         u32 last_inst;
846 
847         if (kvmppc_get_last_inst(vcpu, INST_GENERIC, &last_inst) !=
848                                         EMULATE_DONE) {
849                 /*
850                  * Fetch failed, so return to guest and
851                  * try executing it again.
852                  */
853                 return RESUME_GUEST;
854         }
855 
856         if (last_inst == KVMPPC_INST_SW_BREAKPOINT) {
857                 run->exit_reason = KVM_EXIT_DEBUG;
858                 run->debug.arch.address = kvmppc_get_pc(vcpu);
859                 return RESUME_HOST;
860         } else {
861                 kvmppc_core_queue_program(vcpu, SRR1_PROGILL);
862                 return RESUME_GUEST;
863         }
864 }
865 
866 static int kvmppc_handle_exit_hv(struct kvm_run *run, struct kvm_vcpu *vcpu,
867                                  struct task_struct *tsk)
868 {
869         int r = RESUME_HOST;
870 
871         vcpu->stat.sum_exits++;
872 
873         /*
874          * This can happen if an interrupt occurs in the last stages
875          * of guest entry or the first stages of guest exit (i.e. after
876          * setting paca->kvm_hstate.in_guest to KVM_GUEST_MODE_GUEST_HV
877          * and before setting it to KVM_GUEST_MODE_HOST_HV).
878          * That can happen due to a bug, or due to a machine check
879          * occurring at just the wrong time.
880          */
881         if (vcpu->arch.shregs.msr & MSR_HV) {
882                 printk(KERN_EMERG "KVM trap in HV mode!\n");
883                 printk(KERN_EMERG "trap=0x%x | pc=0x%lx | msr=0x%llx\n",
884                         vcpu->arch.trap, kvmppc_get_pc(vcpu),
885                         vcpu->arch.shregs.msr);
886                 kvmppc_dump_regs(vcpu);
887                 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
888                 run->hw.hardware_exit_reason = vcpu->arch.trap;
889                 return RESUME_HOST;
890         }
891         run->exit_reason = KVM_EXIT_UNKNOWN;
892         run->ready_for_interrupt_injection = 1;
893         switch (vcpu->arch.trap) {
894         /* We're good on these - the host merely wanted to get our attention */
895         case BOOK3S_INTERRUPT_HV_DECREMENTER:
896                 vcpu->stat.dec_exits++;
897                 r = RESUME_GUEST;
898                 break;
899         case BOOK3S_INTERRUPT_EXTERNAL:
900         case BOOK3S_INTERRUPT_H_DOORBELL:
901                 vcpu->stat.ext_intr_exits++;
902                 r = RESUME_GUEST;
903                 break;
904         /* HMI is hypervisor interrupt and host has handled it. Resume guest.*/
905         case BOOK3S_INTERRUPT_HMI:
906         case BOOK3S_INTERRUPT_PERFMON:
907                 r = RESUME_GUEST;
908                 break;
909         case BOOK3S_INTERRUPT_MACHINE_CHECK:
910                 /*
911                  * Deliver a machine check interrupt to the guest.
912                  * We have to do this, even if the host has handled the
913                  * machine check, because machine checks use SRR0/1 and
914                  * the interrupt might have trashed guest state in them.
915                  */
916                 kvmppc_book3s_queue_irqprio(vcpu,
917                                             BOOK3S_INTERRUPT_MACHINE_CHECK);
918                 r = RESUME_GUEST;
919                 break;
920         case BOOK3S_INTERRUPT_PROGRAM:
921         {
922                 ulong flags;
923                 /*
924                  * Normally program interrupts are delivered directly
925                  * to the guest by the hardware, but we can get here
926                  * as a result of a hypervisor emulation interrupt
927                  * (e40) getting turned into a 700 by BML RTAS.
928                  */
929                 flags = vcpu->arch.shregs.msr & 0x1f0000ull;
930                 kvmppc_core_queue_program(vcpu, flags);
931                 r = RESUME_GUEST;
932                 break;
933         }
934         case BOOK3S_INTERRUPT_SYSCALL:
935         {
936                 /* hcall - punt to userspace */
937                 int i;
938 
939                 /* hypercall with MSR_PR has already been handled in rmode,
940                  * and never reaches here.
941                  */
942 
943                 run->papr_hcall.nr = kvmppc_get_gpr(vcpu, 3);
944                 for (i = 0; i < 9; ++i)
945                         run->papr_hcall.args[i] = kvmppc_get_gpr(vcpu, 4 + i);
946                 run->exit_reason = KVM_EXIT_PAPR_HCALL;
947                 vcpu->arch.hcall_needed = 1;
948                 r = RESUME_HOST;
949                 break;
950         }
951         /*
952          * We get these next two if the guest accesses a page which it thinks
953          * it has mapped but which is not actually present, either because
954          * it is for an emulated I/O device or because the corresonding
955          * host page has been paged out.  Any other HDSI/HISI interrupts
956          * have been handled already.
957          */
958         case BOOK3S_INTERRUPT_H_DATA_STORAGE:
959                 r = RESUME_PAGE_FAULT;
960                 break;
961         case BOOK3S_INTERRUPT_H_INST_STORAGE:
962                 vcpu->arch.fault_dar = kvmppc_get_pc(vcpu);
963                 vcpu->arch.fault_dsisr = 0;
964                 r = RESUME_PAGE_FAULT;
965                 break;
966         /*
967          * This occurs if the guest executes an illegal instruction.
968          * If the guest debug is disabled, generate a program interrupt
969          * to the guest. If guest debug is enabled, we need to check
970          * whether the instruction is a software breakpoint instruction.
971          * Accordingly return to Guest or Host.
972          */
973         case BOOK3S_INTERRUPT_H_EMUL_ASSIST:
974                 if (vcpu->arch.emul_inst != KVM_INST_FETCH_FAILED)
975                         vcpu->arch.last_inst = kvmppc_need_byteswap(vcpu) ?
976                                 swab32(vcpu->arch.emul_inst) :
977                                 vcpu->arch.emul_inst;
978                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP) {
979                         r = kvmppc_emulate_debug_inst(run, vcpu);
980                 } else {
981                         kvmppc_core_queue_program(vcpu, SRR1_PROGILL);
982                         r = RESUME_GUEST;
983                 }
984                 break;
985         /*
986          * This occurs if the guest (kernel or userspace), does something that
987          * is prohibited by HFSCR.  We just generate a program interrupt to
988          * the guest.
989          */
990         case BOOK3S_INTERRUPT_H_FAC_UNAVAIL:
991                 kvmppc_core_queue_program(vcpu, SRR1_PROGILL);
992                 r = RESUME_GUEST;
993                 break;
994         default:
995                 kvmppc_dump_regs(vcpu);
996                 printk(KERN_EMERG "trap=0x%x | pc=0x%lx | msr=0x%llx\n",
997                         vcpu->arch.trap, kvmppc_get_pc(vcpu),
998                         vcpu->arch.shregs.msr);
999                 run->hw.hardware_exit_reason = vcpu->arch.trap;
1000                 r = RESUME_HOST;
1001                 break;
1002         }
1003 
1004         return r;
1005 }
1006 
1007 static int kvm_arch_vcpu_ioctl_get_sregs_hv(struct kvm_vcpu *vcpu,
1008                                             struct kvm_sregs *sregs)
1009 {
1010         int i;
1011 
1012         memset(sregs, 0, sizeof(struct kvm_sregs));
1013         sregs->pvr = vcpu->arch.pvr;
1014         for (i = 0; i < vcpu->arch.slb_max; i++) {
1015                 sregs->u.s.ppc64.slb[i].slbe = vcpu->arch.slb[i].orige;
1016                 sregs->u.s.ppc64.slb[i].slbv = vcpu->arch.slb[i].origv;
1017         }
1018 
1019         return 0;
1020 }
1021 
1022 static int kvm_arch_vcpu_ioctl_set_sregs_hv(struct kvm_vcpu *vcpu,
1023                                             struct kvm_sregs *sregs)
1024 {
1025         int i, j;
1026 
1027         /* Only accept the same PVR as the host's, since we can't spoof it */
1028         if (sregs->pvr != vcpu->arch.pvr)
1029                 return -EINVAL;
1030 
1031         j = 0;
1032         for (i = 0; i < vcpu->arch.slb_nr; i++) {
1033                 if (sregs->u.s.ppc64.slb[i].slbe & SLB_ESID_V) {
1034                         vcpu->arch.slb[j].orige = sregs->u.s.ppc64.slb[i].slbe;
1035                         vcpu->arch.slb[j].origv = sregs->u.s.ppc64.slb[i].slbv;
1036                         ++j;
1037                 }
1038         }
1039         vcpu->arch.slb_max = j;
1040 
1041         return 0;
1042 }
1043 
1044 static void kvmppc_set_lpcr(struct kvm_vcpu *vcpu, u64 new_lpcr,
1045                 bool preserve_top32)
1046 {
1047         struct kvm *kvm = vcpu->kvm;
1048         struct kvmppc_vcore *vc = vcpu->arch.vcore;
1049         u64 mask;
1050 
1051         mutex_lock(&kvm->lock);
1052         spin_lock(&vc->lock);
1053         /*
1054          * If ILE (interrupt little-endian) has changed, update the
1055          * MSR_LE bit in the intr_msr for each vcpu in this vcore.
1056          */
1057         if ((new_lpcr & LPCR_ILE) != (vc->lpcr & LPCR_ILE)) {
1058                 struct kvm_vcpu *vcpu;
1059                 int i;
1060 
1061                 kvm_for_each_vcpu(i, vcpu, kvm) {
1062                         if (vcpu->arch.vcore != vc)
1063                                 continue;
1064                         if (new_lpcr & LPCR_ILE)
1065                                 vcpu->arch.intr_msr |= MSR_LE;
1066                         else
1067                                 vcpu->arch.intr_msr &= ~MSR_LE;
1068                 }
1069         }
1070 
1071         /*
1072          * Userspace can only modify DPFD (default prefetch depth),
1073          * ILE (interrupt little-endian) and TC (translation control).
1074          * On POWER8 userspace can also modify AIL (alt. interrupt loc.)
1075          */
1076         mask = LPCR_DPFD | LPCR_ILE | LPCR_TC;
1077         if (cpu_has_feature(CPU_FTR_ARCH_207S))
1078                 mask |= LPCR_AIL;
1079 
1080         /* Broken 32-bit version of LPCR must not clear top bits */
1081         if (preserve_top32)
1082                 mask &= 0xFFFFFFFF;
1083         vc->lpcr = (vc->lpcr & ~mask) | (new_lpcr & mask);
1084         spin_unlock(&vc->lock);
1085         mutex_unlock(&kvm->lock);
1086 }
1087 
1088 static int kvmppc_get_one_reg_hv(struct kvm_vcpu *vcpu, u64 id,
1089                                  union kvmppc_one_reg *val)
1090 {
1091         int r = 0;
1092         long int i;
1093 
1094         switch (id) {
1095         case KVM_REG_PPC_DEBUG_INST:
1096                 *val = get_reg_val(id, KVMPPC_INST_SW_BREAKPOINT);
1097                 break;
1098         case KVM_REG_PPC_HIOR:
1099                 *val = get_reg_val(id, 0);
1100                 break;
1101         case KVM_REG_PPC_DABR:
1102                 *val = get_reg_val(id, vcpu->arch.dabr);
1103                 break;
1104         case KVM_REG_PPC_DABRX:
1105                 *val = get_reg_val(id, vcpu->arch.dabrx);
1106                 break;
1107         case KVM_REG_PPC_DSCR:
1108                 *val = get_reg_val(id, vcpu->arch.dscr);
1109                 break;
1110         case KVM_REG_PPC_PURR:
1111                 *val = get_reg_val(id, vcpu->arch.purr);
1112                 break;
1113         case KVM_REG_PPC_SPURR:
1114                 *val = get_reg_val(id, vcpu->arch.spurr);
1115                 break;
1116         case KVM_REG_PPC_AMR:
1117                 *val = get_reg_val(id, vcpu->arch.amr);
1118                 break;
1119         case KVM_REG_PPC_UAMOR:
1120                 *val = get_reg_val(id, vcpu->arch.uamor);
1121                 break;
1122         case KVM_REG_PPC_MMCR0 ... KVM_REG_PPC_MMCRS:
1123                 i = id - KVM_REG_PPC_MMCR0;
1124                 *val = get_reg_val(id, vcpu->arch.mmcr[i]);
1125                 break;
1126         case KVM_REG_PPC_PMC1 ... KVM_REG_PPC_PMC8:
1127                 i = id - KVM_REG_PPC_PMC1;
1128                 *val = get_reg_val(id, vcpu->arch.pmc[i]);
1129                 break;
1130         case KVM_REG_PPC_SPMC1 ... KVM_REG_PPC_SPMC2:
1131                 i = id - KVM_REG_PPC_SPMC1;
1132                 *val = get_reg_val(id, vcpu->arch.spmc[i]);
1133                 break;
1134         case KVM_REG_PPC_SIAR:
1135                 *val = get_reg_val(id, vcpu->arch.siar);
1136                 break;
1137         case KVM_REG_PPC_SDAR:
1138                 *val = get_reg_val(id, vcpu->arch.sdar);
1139                 break;
1140         case KVM_REG_PPC_SIER:
1141                 *val = get_reg_val(id, vcpu->arch.sier);
1142                 break;
1143         case KVM_REG_PPC_IAMR:
1144                 *val = get_reg_val(id, vcpu->arch.iamr);
1145                 break;
1146         case KVM_REG_PPC_PSPB:
1147                 *val = get_reg_val(id, vcpu->arch.pspb);
1148                 break;
1149         case KVM_REG_PPC_DPDES:
1150                 *val = get_reg_val(id, vcpu->arch.vcore->dpdes);
1151                 break;
1152         case KVM_REG_PPC_DAWR:
1153                 *val = get_reg_val(id, vcpu->arch.dawr);
1154                 break;
1155         case KVM_REG_PPC_DAWRX:
1156                 *val = get_reg_val(id, vcpu->arch.dawrx);
1157                 break;
1158         case KVM_REG_PPC_CIABR:
1159                 *val = get_reg_val(id, vcpu->arch.ciabr);
1160                 break;
1161         case KVM_REG_PPC_CSIGR:
1162                 *val = get_reg_val(id, vcpu->arch.csigr);
1163                 break;
1164         case KVM_REG_PPC_TACR:
1165                 *val = get_reg_val(id, vcpu->arch.tacr);
1166                 break;
1167         case KVM_REG_PPC_TCSCR:
1168                 *val = get_reg_val(id, vcpu->arch.tcscr);
1169                 break;
1170         case KVM_REG_PPC_PID:
1171                 *val = get_reg_val(id, vcpu->arch.pid);
1172                 break;
1173         case KVM_REG_PPC_ACOP:
1174                 *val = get_reg_val(id, vcpu->arch.acop);
1175                 break;
1176         case KVM_REG_PPC_WORT:
1177                 *val = get_reg_val(id, vcpu->arch.wort);
1178                 break;
1179         case KVM_REG_PPC_VPA_ADDR:
1180                 spin_lock(&vcpu->arch.vpa_update_lock);
1181                 *val = get_reg_val(id, vcpu->arch.vpa.next_gpa);
1182                 spin_unlock(&vcpu->arch.vpa_update_lock);
1183                 break;
1184         case KVM_REG_PPC_VPA_SLB:
1185                 spin_lock(&vcpu->arch.vpa_update_lock);
1186                 val->vpaval.addr = vcpu->arch.slb_shadow.next_gpa;
1187                 val->vpaval.length = vcpu->arch.slb_shadow.len;
1188                 spin_unlock(&vcpu->arch.vpa_update_lock);
1189                 break;
1190         case KVM_REG_PPC_VPA_DTL:
1191                 spin_lock(&vcpu->arch.vpa_update_lock);
1192                 val->vpaval.addr = vcpu->arch.dtl.next_gpa;
1193                 val->vpaval.length = vcpu->arch.dtl.len;
1194                 spin_unlock(&vcpu->arch.vpa_update_lock);
1195                 break;
1196         case KVM_REG_PPC_TB_OFFSET:
1197                 *val = get_reg_val(id, vcpu->arch.vcore->tb_offset);
1198                 break;
1199         case KVM_REG_PPC_LPCR:
1200         case KVM_REG_PPC_LPCR_64:
1201                 *val = get_reg_val(id, vcpu->arch.vcore->lpcr);
1202                 break;
1203         case KVM_REG_PPC_PPR:
1204                 *val = get_reg_val(id, vcpu->arch.ppr);
1205                 break;
1206 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1207         case KVM_REG_PPC_TFHAR:
1208                 *val = get_reg_val(id, vcpu->arch.tfhar);
1209                 break;
1210         case KVM_REG_PPC_TFIAR:
1211                 *val = get_reg_val(id, vcpu->arch.tfiar);
1212                 break;
1213         case KVM_REG_PPC_TEXASR:
1214                 *val = get_reg_val(id, vcpu->arch.texasr);
1215                 break;
1216         case KVM_REG_PPC_TM_GPR0 ... KVM_REG_PPC_TM_GPR31:
1217                 i = id - KVM_REG_PPC_TM_GPR0;
1218                 *val = get_reg_val(id, vcpu->arch.gpr_tm[i]);
1219                 break;
1220         case KVM_REG_PPC_TM_VSR0 ... KVM_REG_PPC_TM_VSR63:
1221         {
1222                 int j;
1223                 i = id - KVM_REG_PPC_TM_VSR0;
1224                 if (i < 32)
1225                         for (j = 0; j < TS_FPRWIDTH; j++)
1226                                 val->vsxval[j] = vcpu->arch.fp_tm.fpr[i][j];
1227                 else {
1228                         if (cpu_has_feature(CPU_FTR_ALTIVEC))
1229                                 val->vval = vcpu->arch.vr_tm.vr[i-32];
1230                         else
1231                                 r = -ENXIO;
1232                 }
1233                 break;
1234         }
1235         case KVM_REG_PPC_TM_CR:
1236                 *val = get_reg_val(id, vcpu->arch.cr_tm);
1237                 break;
1238         case KVM_REG_PPC_TM_XER:
1239                 *val = get_reg_val(id, vcpu->arch.xer_tm);
1240                 break;
1241         case KVM_REG_PPC_TM_LR:
1242                 *val = get_reg_val(id, vcpu->arch.lr_tm);
1243                 break;
1244         case KVM_REG_PPC_TM_CTR:
1245                 *val = get_reg_val(id, vcpu->arch.ctr_tm);
1246                 break;
1247         case KVM_REG_PPC_TM_FPSCR:
1248                 *val = get_reg_val(id, vcpu->arch.fp_tm.fpscr);
1249                 break;
1250         case KVM_REG_PPC_TM_AMR:
1251                 *val = get_reg_val(id, vcpu->arch.amr_tm);
1252                 break;
1253         case KVM_REG_PPC_TM_PPR:
1254                 *val = get_reg_val(id, vcpu->arch.ppr_tm);
1255                 break;
1256         case KVM_REG_PPC_TM_VRSAVE:
1257                 *val = get_reg_val(id, vcpu->arch.vrsave_tm);
1258                 break;
1259         case KVM_REG_PPC_TM_VSCR:
1260                 if (cpu_has_feature(CPU_FTR_ALTIVEC))
1261                         *val = get_reg_val(id, vcpu->arch.vr_tm.vscr.u[3]);
1262                 else
1263                         r = -ENXIO;
1264                 break;
1265         case KVM_REG_PPC_TM_DSCR:
1266                 *val = get_reg_val(id, vcpu->arch.dscr_tm);
1267                 break;
1268         case KVM_REG_PPC_TM_TAR:
1269                 *val = get_reg_val(id, vcpu->arch.tar_tm);
1270                 break;
1271 #endif
1272         case KVM_REG_PPC_ARCH_COMPAT:
1273                 *val = get_reg_val(id, vcpu->arch.vcore->arch_compat);
1274                 break;
1275         default:
1276                 r = -EINVAL;
1277                 break;
1278         }
1279 
1280         return r;
1281 }
1282 
1283 static int kvmppc_set_one_reg_hv(struct kvm_vcpu *vcpu, u64 id,
1284                                  union kvmppc_one_reg *val)
1285 {
1286         int r = 0;
1287         long int i;
1288         unsigned long addr, len;
1289 
1290         switch (id) {
1291         case KVM_REG_PPC_HIOR:
1292                 /* Only allow this to be set to zero */
1293                 if (set_reg_val(id, *val))
1294                         r = -EINVAL;
1295                 break;
1296         case KVM_REG_PPC_DABR:
1297                 vcpu->arch.dabr = set_reg_val(id, *val);
1298                 break;
1299         case KVM_REG_PPC_DABRX:
1300                 vcpu->arch.dabrx = set_reg_val(id, *val) & ~DABRX_HYP;
1301                 break;
1302         case KVM_REG_PPC_DSCR:
1303                 vcpu->arch.dscr = set_reg_val(id, *val);
1304                 break;
1305         case KVM_REG_PPC_PURR:
1306                 vcpu->arch.purr = set_reg_val(id, *val);
1307                 break;
1308         case KVM_REG_PPC_SPURR:
1309                 vcpu->arch.spurr = set_reg_val(id, *val);
1310                 break;
1311         case KVM_REG_PPC_AMR:
1312                 vcpu->arch.amr = set_reg_val(id, *val);
1313                 break;
1314         case KVM_REG_PPC_UAMOR:
1315                 vcpu->arch.uamor = set_reg_val(id, *val);
1316                 break;
1317         case KVM_REG_PPC_MMCR0 ... KVM_REG_PPC_MMCRS:
1318                 i = id - KVM_REG_PPC_MMCR0;
1319                 vcpu->arch.mmcr[i] = set_reg_val(id, *val);
1320                 break;
1321         case KVM_REG_PPC_PMC1 ... KVM_REG_PPC_PMC8:
1322                 i = id - KVM_REG_PPC_PMC1;
1323                 vcpu->arch.pmc[i] = set_reg_val(id, *val);
1324                 break;
1325         case KVM_REG_PPC_SPMC1 ... KVM_REG_PPC_SPMC2:
1326                 i = id - KVM_REG_PPC_SPMC1;
1327                 vcpu->arch.spmc[i] = set_reg_val(id, *val);
1328                 break;
1329         case KVM_REG_PPC_SIAR:
1330                 vcpu->arch.siar = set_reg_val(id, *val);
1331                 break;
1332         case KVM_REG_PPC_SDAR:
1333                 vcpu->arch.sdar = set_reg_val(id, *val);
1334                 break;
1335         case KVM_REG_PPC_SIER:
1336                 vcpu->arch.sier = set_reg_val(id, *val);
1337                 break;
1338         case KVM_REG_PPC_IAMR:
1339                 vcpu->arch.iamr = set_reg_val(id, *val);
1340                 break;
1341         case KVM_REG_PPC_PSPB:
1342                 vcpu->arch.pspb = set_reg_val(id, *val);
1343                 break;
1344         case KVM_REG_PPC_DPDES:
1345                 vcpu->arch.vcore->dpdes = set_reg_val(id, *val);
1346                 break;
1347         case KVM_REG_PPC_DAWR:
1348                 vcpu->arch.dawr = set_reg_val(id, *val);
1349                 break;
1350         case KVM_REG_PPC_DAWRX:
1351                 vcpu->arch.dawrx = set_reg_val(id, *val) & ~DAWRX_HYP;
1352                 break;
1353         case KVM_REG_PPC_CIABR:
1354                 vcpu->arch.ciabr = set_reg_val(id, *val);
1355                 /* Don't allow setting breakpoints in hypervisor code */
1356                 if ((vcpu->arch.ciabr & CIABR_PRIV) == CIABR_PRIV_HYPER)
1357                         vcpu->arch.ciabr &= ~CIABR_PRIV;        /* disable */
1358                 break;
1359         case KVM_REG_PPC_CSIGR:
1360                 vcpu->arch.csigr = set_reg_val(id, *val);
1361                 break;
1362         case KVM_REG_PPC_TACR:
1363                 vcpu->arch.tacr = set_reg_val(id, *val);
1364                 break;
1365         case KVM_REG_PPC_TCSCR:
1366                 vcpu->arch.tcscr = set_reg_val(id, *val);
1367                 break;
1368         case KVM_REG_PPC_PID:
1369                 vcpu->arch.pid = set_reg_val(id, *val);
1370                 break;
1371         case KVM_REG_PPC_ACOP:
1372                 vcpu->arch.acop = set_reg_val(id, *val);
1373                 break;
1374         case KVM_REG_PPC_WORT:
1375                 vcpu->arch.wort = set_reg_val(id, *val);
1376                 break;
1377         case KVM_REG_PPC_VPA_ADDR:
1378                 addr = set_reg_val(id, *val);
1379                 r = -EINVAL;
1380                 if (!addr && (vcpu->arch.slb_shadow.next_gpa ||
1381                               vcpu->arch.dtl.next_gpa))
1382                         break;
1383                 r = set_vpa(vcpu, &vcpu->arch.vpa, addr, sizeof(struct lppaca));
1384                 break;
1385         case KVM_REG_PPC_VPA_SLB:
1386                 addr = val->vpaval.addr;
1387                 len = val->vpaval.length;
1388                 r = -EINVAL;
1389                 if (addr && !vcpu->arch.vpa.next_gpa)
1390                         break;
1391                 r = set_vpa(vcpu, &vcpu->arch.slb_shadow, addr, len);
1392                 break;
1393         case KVM_REG_PPC_VPA_DTL:
1394                 addr = val->vpaval.addr;
1395                 len = val->vpaval.length;
1396                 r = -EINVAL;
1397                 if (addr && (len < sizeof(struct dtl_entry) ||
1398                              !vcpu->arch.vpa.next_gpa))
1399                         break;
1400                 len -= len % sizeof(struct dtl_entry);
1401                 r = set_vpa(vcpu, &vcpu->arch.dtl, addr, len);
1402                 break;
1403         case KVM_REG_PPC_TB_OFFSET:
1404                 /* round up to multiple of 2^24 */
1405                 vcpu->arch.vcore->tb_offset =
1406                         ALIGN(set_reg_val(id, *val), 1UL << 24);
1407                 break;
1408         case KVM_REG_PPC_LPCR:
1409                 kvmppc_set_lpcr(vcpu, set_reg_val(id, *val), true);
1410                 break;
1411         case KVM_REG_PPC_LPCR_64:
1412                 kvmppc_set_lpcr(vcpu, set_reg_val(id, *val), false);
1413                 break;
1414         case KVM_REG_PPC_PPR:
1415                 vcpu->arch.ppr = set_reg_val(id, *val);
1416                 break;
1417 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1418         case KVM_REG_PPC_TFHAR:
1419                 vcpu->arch.tfhar = set_reg_val(id, *val);
1420                 break;
1421         case KVM_REG_PPC_TFIAR:
1422                 vcpu->arch.tfiar = set_reg_val(id, *val);
1423                 break;
1424         case KVM_REG_PPC_TEXASR:
1425                 vcpu->arch.texasr = set_reg_val(id, *val);
1426                 break;
1427         case KVM_REG_PPC_TM_GPR0 ... KVM_REG_PPC_TM_GPR31:
1428                 i = id - KVM_REG_PPC_TM_GPR0;
1429                 vcpu->arch.gpr_tm[i] = set_reg_val(id, *val);
1430                 break;
1431         case KVM_REG_PPC_TM_VSR0 ... KVM_REG_PPC_TM_VSR63:
1432         {
1433                 int j;
1434                 i = id - KVM_REG_PPC_TM_VSR0;
1435                 if (i < 32)
1436                         for (j = 0; j < TS_FPRWIDTH; j++)
1437                                 vcpu->arch.fp_tm.fpr[i][j] = val->vsxval[j];
1438                 else
1439                         if (cpu_has_feature(CPU_FTR_ALTIVEC))
1440                                 vcpu->arch.vr_tm.vr[i-32] = val->vval;
1441                         else
1442                                 r = -ENXIO;
1443                 break;
1444         }
1445         case KVM_REG_PPC_TM_CR:
1446                 vcpu->arch.cr_tm = set_reg_val(id, *val);
1447                 break;
1448         case KVM_REG_PPC_TM_XER:
1449                 vcpu->arch.xer_tm = set_reg_val(id, *val);
1450                 break;
1451         case KVM_REG_PPC_TM_LR:
1452                 vcpu->arch.lr_tm = set_reg_val(id, *val);
1453                 break;
1454         case KVM_REG_PPC_TM_CTR:
1455                 vcpu->arch.ctr_tm = set_reg_val(id, *val);
1456                 break;
1457         case KVM_REG_PPC_TM_FPSCR:
1458                 vcpu->arch.fp_tm.fpscr = set_reg_val(id, *val);
1459                 break;
1460         case KVM_REG_PPC_TM_AMR:
1461                 vcpu->arch.amr_tm = set_reg_val(id, *val);
1462                 break;
1463         case KVM_REG_PPC_TM_PPR:
1464                 vcpu->arch.ppr_tm = set_reg_val(id, *val);
1465                 break;
1466         case KVM_REG_PPC_TM_VRSAVE:
1467                 vcpu->arch.vrsave_tm = set_reg_val(id, *val);
1468                 break;
1469         case KVM_REG_PPC_TM_VSCR:
1470                 if (cpu_has_feature(CPU_FTR_ALTIVEC))
1471                         vcpu->arch.vr.vscr.u[3] = set_reg_val(id, *val);
1472                 else
1473                         r = - ENXIO;
1474                 break;
1475         case KVM_REG_PPC_TM_DSCR:
1476                 vcpu->arch.dscr_tm = set_reg_val(id, *val);
1477                 break;
1478         case KVM_REG_PPC_TM_TAR:
1479                 vcpu->arch.tar_tm = set_reg_val(id, *val);
1480                 break;
1481 #endif
1482         case KVM_REG_PPC_ARCH_COMPAT:
1483                 r = kvmppc_set_arch_compat(vcpu, set_reg_val(id, *val));
1484                 break;
1485         default:
1486                 r = -EINVAL;
1487                 break;
1488         }
1489 
1490         return r;
1491 }
1492 
1493 static struct kvmppc_vcore *kvmppc_vcore_create(struct kvm *kvm, int core)
1494 {
1495         struct kvmppc_vcore *vcore;
1496 
1497         vcore = kzalloc(sizeof(struct kvmppc_vcore), GFP_KERNEL);
1498 
1499         if (vcore == NULL)
1500                 return NULL;
1501 
1502         INIT_LIST_HEAD(&vcore->runnable_threads);
1503         spin_lock_init(&vcore->lock);
1504         spin_lock_init(&vcore->stoltb_lock);
1505         init_swait_queue_head(&vcore->wq);
1506         vcore->preempt_tb = TB_NIL;
1507         vcore->lpcr = kvm->arch.lpcr;
1508         vcore->first_vcpuid = core * threads_per_subcore;
1509         vcore->kvm = kvm;
1510         INIT_LIST_HEAD(&vcore->preempt_list);
1511 
1512         return vcore;
1513 }
1514 
1515 #ifdef CONFIG_KVM_BOOK3S_HV_EXIT_TIMING
1516 static struct debugfs_timings_element {
1517         const char *name;
1518         size_t offset;
1519 } timings[] = {
1520         {"rm_entry",    offsetof(struct kvm_vcpu, arch.rm_entry)},
1521         {"rm_intr",     offsetof(struct kvm_vcpu, arch.rm_intr)},
1522         {"rm_exit",     offsetof(struct kvm_vcpu, arch.rm_exit)},
1523         {"guest",       offsetof(struct kvm_vcpu, arch.guest_time)},
1524         {"cede",        offsetof(struct kvm_vcpu, arch.cede_time)},
1525 };
1526 
1527 #define N_TIMINGS       (sizeof(timings) / sizeof(timings[0]))
1528 
1529 struct debugfs_timings_state {
1530         struct kvm_vcpu *vcpu;
1531         unsigned int    buflen;
1532         char            buf[N_TIMINGS * 100];
1533 };
1534 
1535 static int debugfs_timings_open(struct inode *inode, struct file *file)
1536 {
1537         struct kvm_vcpu *vcpu = inode->i_private;
1538         struct debugfs_timings_state *p;
1539 
1540         p = kzalloc(sizeof(*p), GFP_KERNEL);
1541         if (!p)
1542                 return -ENOMEM;
1543 
1544         kvm_get_kvm(vcpu->kvm);
1545         p->vcpu = vcpu;
1546         file->private_data = p;
1547 
1548         return nonseekable_open(inode, file);
1549 }
1550 
1551 static int debugfs_timings_release(struct inode *inode, struct file *file)
1552 {
1553         struct debugfs_timings_state *p = file->private_data;
1554 
1555         kvm_put_kvm(p->vcpu->kvm);
1556         kfree(p);
1557         return 0;
1558 }
1559 
1560 static ssize_t debugfs_timings_read(struct file *file, char __user *buf,
1561                                     size_t len, loff_t *ppos)
1562 {
1563         struct debugfs_timings_state *p = file->private_data;
1564         struct kvm_vcpu *vcpu = p->vcpu;
1565         char *s, *buf_end;
1566         struct kvmhv_tb_accumulator tb;
1567         u64 count;
1568         loff_t pos;
1569         ssize_t n;
1570         int i, loops;
1571         bool ok;
1572 
1573         if (!p->buflen) {
1574                 s = p->buf;
1575                 buf_end = s + sizeof(p->buf);
1576                 for (i = 0; i < N_TIMINGS; ++i) {
1577                         struct kvmhv_tb_accumulator *acc;
1578 
1579                         acc = (struct kvmhv_tb_accumulator *)
1580                                 ((unsigned long)vcpu + timings[i].offset);
1581                         ok = false;
1582                         for (loops = 0; loops < 1000; ++loops) {
1583                                 count = acc->seqcount;
1584                                 if (!(count & 1)) {
1585                                         smp_rmb();
1586                                         tb = *acc;
1587                                         smp_rmb();
1588                                         if (count == acc->seqcount) {
1589                                                 ok = true;
1590                                                 break;
1591                                         }
1592                                 }
1593                                 udelay(1);
1594                         }
1595                         if (!ok)
1596                                 snprintf(s, buf_end - s, "%s: stuck\n",
1597                                         timings[i].name);
1598                         else
1599                                 snprintf(s, buf_end - s,
1600                                         "%s: %llu %llu %llu %llu\n",
1601                                         timings[i].name, count / 2,
1602                                         tb_to_ns(tb.tb_total),
1603                                         tb_to_ns(tb.tb_min),
1604                                         tb_to_ns(tb.tb_max));
1605                         s += strlen(s);
1606                 }
1607                 p->buflen = s - p->buf;
1608         }
1609 
1610         pos = *ppos;
1611         if (pos >= p->buflen)
1612                 return 0;
1613         if (len > p->buflen - pos)
1614                 len = p->buflen - pos;
1615         n = copy_to_user(buf, p->buf + pos, len);
1616         if (n) {
1617                 if (n == len)
1618                         return -EFAULT;
1619                 len -= n;
1620         }
1621         *ppos = pos + len;
1622         return len;
1623 }
1624 
1625 static ssize_t debugfs_timings_write(struct file *file, const char __user *buf,
1626                                      size_t len, loff_t *ppos)
1627 {
1628         return -EACCES;
1629 }
1630 
1631 static const struct file_operations debugfs_timings_ops = {
1632         .owner   = THIS_MODULE,
1633         .open    = debugfs_timings_open,
1634         .release = debugfs_timings_release,
1635         .read    = debugfs_timings_read,
1636         .write   = debugfs_timings_write,
1637         .llseek  = generic_file_llseek,
1638 };
1639 
1640 /* Create a debugfs directory for the vcpu */
1641 static void debugfs_vcpu_init(struct kvm_vcpu *vcpu, unsigned int id)
1642 {
1643         char buf[16];
1644         struct kvm *kvm = vcpu->kvm;
1645 
1646         snprintf(buf, sizeof(buf), "vcpu%u", id);
1647         if (IS_ERR_OR_NULL(kvm->arch.debugfs_dir))
1648                 return;
1649         vcpu->arch.debugfs_dir = debugfs_create_dir(buf, kvm->arch.debugfs_dir);
1650         if (IS_ERR_OR_NULL(vcpu->arch.debugfs_dir))
1651                 return;
1652         vcpu->arch.debugfs_timings =
1653                 debugfs_create_file("timings", 0444, vcpu->arch.debugfs_dir,
1654                                     vcpu, &debugfs_timings_ops);
1655 }
1656 
1657 #else /* CONFIG_KVM_BOOK3S_HV_EXIT_TIMING */
1658 static void debugfs_vcpu_init(struct kvm_vcpu *vcpu, unsigned int id)
1659 {
1660 }
1661 #endif /* CONFIG_KVM_BOOK3S_HV_EXIT_TIMING */
1662 
1663 static struct kvm_vcpu *kvmppc_core_vcpu_create_hv(struct kvm *kvm,
1664                                                    unsigned int id)
1665 {
1666         struct kvm_vcpu *vcpu;
1667         int err = -EINVAL;
1668         int core;
1669         struct kvmppc_vcore *vcore;
1670 
1671         core = id / threads_per_subcore;
1672         if (core >= KVM_MAX_VCORES)
1673                 goto out;
1674 
1675         err = -ENOMEM;
1676         vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
1677         if (!vcpu)
1678                 goto out;
1679 
1680         err = kvm_vcpu_init(vcpu, kvm, id);
1681         if (err)
1682                 goto free_vcpu;
1683 
1684         vcpu->arch.shared = &vcpu->arch.shregs;
1685 #ifdef CONFIG_KVM_BOOK3S_PR_POSSIBLE
1686         /*
1687          * The shared struct is never shared on HV,
1688          * so we can always use host endianness
1689          */
1690 #ifdef __BIG_ENDIAN__
1691         vcpu->arch.shared_big_endian = true;
1692 #else
1693         vcpu->arch.shared_big_endian = false;
1694 #endif
1695 #endif
1696         vcpu->arch.mmcr[0] = MMCR0_FC;
1697         vcpu->arch.ctrl = CTRL_RUNLATCH;
1698         /* default to host PVR, since we can't spoof it */
1699         kvmppc_set_pvr_hv(vcpu, mfspr(SPRN_PVR));
1700         spin_lock_init(&vcpu->arch.vpa_update_lock);
1701         spin_lock_init(&vcpu->arch.tbacct_lock);
1702         vcpu->arch.busy_preempt = TB_NIL;
1703         vcpu->arch.intr_msr = MSR_SF | MSR_ME;
1704 
1705         kvmppc_mmu_book3s_hv_init(vcpu);
1706 
1707         vcpu->arch.state = KVMPPC_VCPU_NOTREADY;
1708 
1709         init_waitqueue_head(&vcpu->arch.cpu_run);
1710 
1711         mutex_lock(&kvm->lock);
1712         vcore = kvm->arch.vcores[core];
1713         if (!vcore) {
1714                 vcore = kvmppc_vcore_create(kvm, core);
1715                 kvm->arch.vcores[core] = vcore;
1716                 kvm->arch.online_vcores++;
1717         }
1718         mutex_unlock(&kvm->lock);
1719 
1720         if (!vcore)
1721                 goto free_vcpu;
1722 
1723         spin_lock(&vcore->lock);
1724         ++vcore->num_threads;
1725         spin_unlock(&vcore->lock);
1726         vcpu->arch.vcore = vcore;
1727         vcpu->arch.ptid = vcpu->vcpu_id - vcore->first_vcpuid;
1728         vcpu->arch.thread_cpu = -1;
1729 
1730         vcpu->arch.cpu_type = KVM_CPU_3S_64;
1731         kvmppc_sanity_check(vcpu);
1732 
1733         debugfs_vcpu_init(vcpu, id);
1734 
1735         return vcpu;
1736 
1737 free_vcpu:
1738         kmem_cache_free(kvm_vcpu_cache, vcpu);
1739 out:
1740         return ERR_PTR(err);
1741 }
1742 
1743 static void unpin_vpa(struct kvm *kvm, struct kvmppc_vpa *vpa)
1744 {
1745         if (vpa->pinned_addr)
1746                 kvmppc_unpin_guest_page(kvm, vpa->pinned_addr, vpa->gpa,
1747                                         vpa->dirty);
1748 }
1749 
1750 static void kvmppc_core_vcpu_free_hv(struct kvm_vcpu *vcpu)
1751 {
1752         spin_lock(&vcpu->arch.vpa_update_lock);
1753         unpin_vpa(vcpu->kvm, &vcpu->arch.dtl);
1754         unpin_vpa(vcpu->kvm, &vcpu->arch.slb_shadow);
1755         unpin_vpa(vcpu->kvm, &vcpu->arch.vpa);
1756         spin_unlock(&vcpu->arch.vpa_update_lock);
1757         kvm_vcpu_uninit(vcpu);
1758         kmem_cache_free(kvm_vcpu_cache, vcpu);
1759 }
1760 
1761 static int kvmppc_core_check_requests_hv(struct kvm_vcpu *vcpu)
1762 {
1763         /* Indicate we want to get back into the guest */
1764         return 1;
1765 }
1766 
1767 static void kvmppc_set_timer(struct kvm_vcpu *vcpu)
1768 {
1769         unsigned long dec_nsec, now;
1770 
1771         now = get_tb();
1772         if (now > vcpu->arch.dec_expires) {
1773                 /* decrementer has already gone negative */
1774                 kvmppc_core_queue_dec(vcpu);
1775                 kvmppc_core_prepare_to_enter(vcpu);
1776                 return;
1777         }
1778         dec_nsec = (vcpu->arch.dec_expires - now) * NSEC_PER_SEC
1779                    / tb_ticks_per_sec;
1780         hrtimer_start(&vcpu->arch.dec_timer, ktime_set(0, dec_nsec),
1781                       HRTIMER_MODE_REL);
1782         vcpu->arch.timer_running = 1;
1783 }
1784 
1785 static void kvmppc_end_cede(struct kvm_vcpu *vcpu)
1786 {
1787         vcpu->arch.ceded = 0;
1788         if (vcpu->arch.timer_running) {
1789                 hrtimer_try_to_cancel(&vcpu->arch.dec_timer);
1790                 vcpu->arch.timer_running = 0;
1791         }
1792 }
1793 
1794 extern void __kvmppc_vcore_entry(void);
1795 
1796 static void kvmppc_remove_runnable(struct kvmppc_vcore *vc,
1797                                    struct kvm_vcpu *vcpu)
1798 {
1799         u64 now;
1800 
1801         if (vcpu->arch.state != KVMPPC_VCPU_RUNNABLE)
1802                 return;
1803         spin_lock_irq(&vcpu->arch.tbacct_lock);
1804         now = mftb();
1805         vcpu->arch.busy_stolen += vcore_stolen_time(vc, now) -
1806                 vcpu->arch.stolen_logged;
1807         vcpu->arch.busy_preempt = now;
1808         vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST;
1809         spin_unlock_irq(&vcpu->arch.tbacct_lock);
1810         --vc->n_runnable;
1811         list_del(&vcpu->arch.run_list);
1812 }
1813 
1814 static int kvmppc_grab_hwthread(int cpu)
1815 {
1816         struct paca_struct *tpaca;
1817         long timeout = 10000;
1818 
1819         tpaca = &paca[cpu];
1820 
1821         /* Ensure the thread won't go into the kernel if it wakes */
1822         tpaca->kvm_hstate.kvm_vcpu = NULL;
1823         tpaca->kvm_hstate.kvm_vcore = NULL;
1824         tpaca->kvm_hstate.napping = 0;
1825         smp_wmb();
1826         tpaca->kvm_hstate.hwthread_req = 1;
1827 
1828         /*
1829          * If the thread is already executing in the kernel (e.g. handling
1830          * a stray interrupt), wait for it to get back to nap mode.
1831          * The smp_mb() is to ensure that our setting of hwthread_req
1832          * is visible before we look at hwthread_state, so if this
1833          * races with the code at system_reset_pSeries and the thread
1834          * misses our setting of hwthread_req, we are sure to see its
1835          * setting of hwthread_state, and vice versa.
1836          */
1837         smp_mb();
1838         while (tpaca->kvm_hstate.hwthread_state == KVM_HWTHREAD_IN_KERNEL) {
1839                 if (--timeout <= 0) {
1840                         pr_err("KVM: couldn't grab cpu %d\n", cpu);
1841                         return -EBUSY;
1842                 }
1843                 udelay(1);
1844         }
1845         return 0;
1846 }
1847 
1848 static void kvmppc_release_hwthread(int cpu)
1849 {
1850         struct paca_struct *tpaca;
1851 
1852         tpaca = &paca[cpu];
1853         tpaca->kvm_hstate.hwthread_req = 0;
1854         tpaca->kvm_hstate.kvm_vcpu = NULL;
1855         tpaca->kvm_hstate.kvm_vcore = NULL;
1856         tpaca->kvm_hstate.kvm_split_mode = NULL;
1857 }
1858 
1859 static void kvmppc_start_thread(struct kvm_vcpu *vcpu, struct kvmppc_vcore *vc)
1860 {
1861         int cpu;
1862         struct paca_struct *tpaca;
1863         struct kvmppc_vcore *mvc = vc->master_vcore;
1864 
1865         cpu = vc->pcpu;
1866         if (vcpu) {
1867                 if (vcpu->arch.timer_running) {
1868                         hrtimer_try_to_cancel(&vcpu->arch.dec_timer);
1869                         vcpu->arch.timer_running = 0;
1870                 }
1871                 cpu += vcpu->arch.ptid;
1872                 vcpu->cpu = mvc->pcpu;
1873                 vcpu->arch.thread_cpu = cpu;
1874         }
1875         tpaca = &paca[cpu];
1876         tpaca->kvm_hstate.kvm_vcpu = vcpu;
1877         tpaca->kvm_hstate.ptid = cpu - mvc->pcpu;
1878         /* Order stores to hstate.kvm_vcpu etc. before store to kvm_vcore */
1879         smp_wmb();
1880         tpaca->kvm_hstate.kvm_vcore = mvc;
1881         if (cpu != smp_processor_id())
1882                 kvmppc_ipi_thread(cpu);
1883 }
1884 
1885 static void kvmppc_wait_for_nap(void)
1886 {
1887         int cpu = smp_processor_id();
1888         int i, loops;
1889 
1890         for (loops = 0; loops < 1000000; ++loops) {
1891                 /*
1892                  * Check if all threads are finished.
1893                  * We set the vcore pointer when starting a thread
1894                  * and the thread clears it when finished, so we look
1895                  * for any threads that still have a non-NULL vcore ptr.
1896                  */
1897                 for (i = 1; i < threads_per_subcore; ++i)
1898                         if (paca[cpu + i].kvm_hstate.kvm_vcore)
1899                                 break;
1900                 if (i == threads_per_subcore) {
1901                         HMT_medium();
1902                         return;
1903                 }
1904                 HMT_low();
1905         }
1906         HMT_medium();
1907         for (i = 1; i < threads_per_subcore; ++i)
1908                 if (paca[cpu + i].kvm_hstate.kvm_vcore)
1909                         pr_err("KVM: CPU %d seems to be stuck\n", cpu + i);
1910 }
1911 
1912 /*
1913  * Check that we are on thread 0 and that any other threads in
1914  * this core are off-line.  Then grab the threads so they can't
1915  * enter the kernel.
1916  */
1917 static int on_primary_thread(void)
1918 {
1919         int cpu = smp_processor_id();
1920         int thr;
1921 
1922         /* Are we on a primary subcore? */
1923         if (cpu_thread_in_subcore(cpu))
1924                 return 0;
1925 
1926         thr = 0;
1927         while (++thr < threads_per_subcore)
1928                 if (cpu_online(cpu + thr))
1929                         return 0;
1930 
1931         /* Grab all hw threads so they can't go into the kernel */
1932         for (thr = 1; thr < threads_per_subcore; ++thr) {
1933                 if (kvmppc_grab_hwthread(cpu + thr)) {
1934                         /* Couldn't grab one; let the others go */
1935                         do {
1936                                 kvmppc_release_hwthread(cpu + thr);
1937                         } while (--thr > 0);
1938                         return 0;
1939                 }
1940         }
1941         return 1;
1942 }
1943 
1944 /*
1945  * A list of virtual cores for each physical CPU.
1946  * These are vcores that could run but their runner VCPU tasks are
1947  * (or may be) preempted.
1948  */
1949 struct preempted_vcore_list {
1950         struct list_head        list;
1951         spinlock_t              lock;
1952 };
1953 
1954 static DEFINE_PER_CPU(struct preempted_vcore_list, preempted_vcores);
1955 
1956 static void init_vcore_lists(void)
1957 {
1958         int cpu;
1959 
1960         for_each_possible_cpu(cpu) {
1961                 struct preempted_vcore_list *lp = &per_cpu(preempted_vcores, cpu);
1962                 spin_lock_init(&lp->lock);
1963                 INIT_LIST_HEAD(&lp->list);
1964         }
1965 }
1966 
1967 static void kvmppc_vcore_preempt(struct kvmppc_vcore *vc)
1968 {
1969         struct preempted_vcore_list *lp = this_cpu_ptr(&preempted_vcores);
1970 
1971         vc->vcore_state = VCORE_PREEMPT;
1972         vc->pcpu = smp_processor_id();
1973         if (vc->num_threads < threads_per_subcore) {
1974                 spin_lock(&lp->lock);
1975                 list_add_tail(&vc->preempt_list, &lp->list);
1976                 spin_unlock(&lp->lock);
1977         }
1978 
1979         /* Start accumulating stolen time */
1980         kvmppc_core_start_stolen(vc);
1981 }
1982 
1983 static void kvmppc_vcore_end_preempt(struct kvmppc_vcore *vc)
1984 {
1985         struct preempted_vcore_list *lp;
1986 
1987         kvmppc_core_end_stolen(vc);
1988         if (!list_empty(&vc->preempt_list)) {
1989                 lp = &per_cpu(preempted_vcores, vc->pcpu);
1990                 spin_lock(&lp->lock);
1991                 list_del_init(&vc->preempt_list);
1992                 spin_unlock(&lp->lock);
1993         }
1994         vc->vcore_state = VCORE_INACTIVE;
1995 }
1996 
1997 /*
1998  * This stores information about the virtual cores currently
1999  * assigned to a physical core.
2000  */
2001 struct core_info {
2002         int             n_subcores;
2003         int             max_subcore_threads;
2004         int             total_threads;
2005         int             subcore_threads[MAX_SUBCORES];
2006         struct kvm      *subcore_vm[MAX_SUBCORES];
2007         struct list_head vcs[MAX_SUBCORES];
2008 };
2009 
2010 /*
2011  * This mapping means subcores 0 and 1 can use threads 0-3 and 4-7
2012  * respectively in 2-way micro-threading (split-core) mode.
2013  */
2014 static int subcore_thread_map[MAX_SUBCORES] = { 0, 4, 2, 6 };
2015 
2016 static void init_core_info(struct core_info *cip, struct kvmppc_vcore *vc)
2017 {
2018         int sub;
2019 
2020         memset(cip, 0, sizeof(*cip));
2021         cip->n_subcores = 1;
2022         cip->max_subcore_threads = vc->num_threads;
2023         cip->total_threads = vc->num_threads;
2024         cip->subcore_threads[0] = vc->num_threads;
2025         cip->subcore_vm[0] = vc->kvm;
2026         for (sub = 0; sub < MAX_SUBCORES; ++sub)
2027                 INIT_LIST_HEAD(&cip->vcs[sub]);
2028         list_add_tail(&vc->preempt_list, &cip->vcs[0]);
2029 }
2030 
2031 static bool subcore_config_ok(int n_subcores, int n_threads)
2032 {
2033         /* Can only dynamically split if unsplit to begin with */
2034         if (n_subcores > 1 && threads_per_subcore < MAX_SMT_THREADS)
2035                 return false;
2036         if (n_subcores > MAX_SUBCORES)
2037                 return false;
2038         if (n_subcores > 1) {
2039                 if (!(dynamic_mt_modes & 2))
2040                         n_subcores = 4;
2041                 if (n_subcores > 2 && !(dynamic_mt_modes & 4))
2042                         return false;
2043         }
2044 
2045         return n_subcores * roundup_pow_of_two(n_threads) <= MAX_SMT_THREADS;
2046 }
2047 
2048 static void init_master_vcore(struct kvmppc_vcore *vc)
2049 {
2050         vc->master_vcore = vc;
2051         vc->entry_exit_map = 0;
2052         vc->in_guest = 0;
2053         vc->napping_threads = 0;
2054         vc->conferring_threads = 0;
2055 }
2056 
2057 /*
2058  * See if the existing subcores can be split into 3 (or fewer) subcores
2059  * of at most two threads each, so we can fit in another vcore.  This
2060  * assumes there are at most two subcores and at most 6 threads in total.
2061  */
2062 static bool can_split_piggybacked_subcores(struct core_info *cip)
2063 {
2064         int sub, new_sub;
2065         int large_sub = -1;
2066         int thr;
2067         int n_subcores = cip->n_subcores;
2068         struct kvmppc_vcore *vc, *vcnext;
2069         struct kvmppc_vcore *master_vc = NULL;
2070 
2071         for (sub = 0; sub < cip->n_subcores; ++sub) {
2072                 if (cip->subcore_threads[sub] <= 2)
2073                         continue;
2074                 if (large_sub >= 0)
2075                         return false;
2076                 large_sub = sub;
2077                 vc = list_first_entry(&cip->vcs[sub], struct kvmppc_vcore,
2078                                       preempt_list);
2079                 if (vc->num_threads > 2)
2080                         return false;
2081                 n_subcores += (cip->subcore_threads[sub] - 1) >> 1;
2082         }
2083         if (large_sub < 0 || !subcore_config_ok(n_subcores + 1, 2))
2084                 return false;
2085 
2086         /*
2087          * Seems feasible, so go through and move vcores to new subcores.
2088          * Note that when we have two or more vcores in one subcore,
2089          * all those vcores must have only one thread each.
2090          */
2091         new_sub = cip->n_subcores;
2092         thr = 0;
2093         sub = large_sub;
2094         list_for_each_entry_safe(vc, vcnext, &cip->vcs[sub], preempt_list) {
2095                 if (thr >= 2) {
2096                         list_del(&vc->preempt_list);
2097                         list_add_tail(&vc->preempt_list, &cip->vcs[new_sub]);
2098                         /* vc->num_threads must be 1 */
2099                         if (++cip->subcore_threads[new_sub] == 1) {
2100                                 cip->subcore_vm[new_sub] = vc->kvm;
2101                                 init_master_vcore(vc);
2102                                 master_vc = vc;
2103                                 ++cip->n_subcores;
2104                         } else {
2105                                 vc->master_vcore = master_vc;
2106                                 ++new_sub;
2107                         }
2108                 }
2109                 thr += vc->num_threads;
2110         }
2111         cip->subcore_threads[large_sub] = 2;
2112         cip->max_subcore_threads = 2;
2113 
2114         return true;
2115 }
2116 
2117 static bool can_dynamic_split(struct kvmppc_vcore *vc, struct core_info *cip)
2118 {
2119         int n_threads = vc->num_threads;
2120         int sub;
2121 
2122         if (!cpu_has_feature(CPU_FTR_ARCH_207S))
2123                 return false;
2124 
2125         if (n_threads < cip->max_subcore_threads)
2126                 n_threads = cip->max_subcore_threads;
2127         if (subcore_config_ok(cip->n_subcores + 1, n_threads)) {
2128                 cip->max_subcore_threads = n_threads;
2129         } else if (cip->n_subcores <= 2 && cip->total_threads <= 6 &&
2130                    vc->num_threads <= 2) {
2131                 /*
2132                  * We may be able to fit another subcore in by
2133                  * splitting an existing subcore with 3 or 4
2134                  * threads into two 2-thread subcores, or one
2135                  * with 5 or 6 threads into three subcores.
2136                  * We can only do this if those subcores have
2137                  * piggybacked virtual cores.
2138                  */
2139                 if (!can_split_piggybacked_subcores(cip))
2140                         return false;
2141         } else {
2142                 return false;
2143         }
2144 
2145         sub = cip->n_subcores;
2146         ++cip->n_subcores;
2147         cip->total_threads += vc->num_threads;
2148         cip->subcore_threads[sub] = vc->num_threads;
2149         cip->subcore_vm[sub] = vc->kvm;
2150         init_master_vcore(vc);
2151         list_del(&vc->preempt_list);
2152         list_add_tail(&vc->preempt_list, &cip->vcs[sub]);
2153 
2154         return true;
2155 }
2156 
2157 static bool can_piggyback_subcore(struct kvmppc_vcore *pvc,
2158                                   struct core_info *cip, int sub)
2159 {
2160         struct kvmppc_vcore *vc;
2161         int n_thr;
2162 
2163         vc = list_first_entry(&cip->vcs[sub], struct kvmppc_vcore,
2164                               preempt_list);
2165 
2166         /* require same VM and same per-core reg values */
2167         if (pvc->kvm != vc->kvm ||
2168             pvc->tb_offset != vc->tb_offset ||
2169             pvc->pcr != vc->pcr ||
2170             pvc->lpcr != vc->lpcr)
2171                 return false;
2172 
2173         /* P8 guest with > 1 thread per core would see wrong TIR value */
2174         if (cpu_has_feature(CPU_FTR_ARCH_207S) &&
2175             (vc->num_threads > 1 || pvc->num_threads > 1))
2176                 return false;
2177 
2178         n_thr = cip->subcore_threads[sub] + pvc->num_threads;
2179         if (n_thr > cip->max_subcore_threads) {
2180                 if (!subcore_config_ok(cip->n_subcores, n_thr))
2181                         return false;
2182                 cip->max_subcore_threads = n_thr;
2183         }
2184 
2185         cip->total_threads += pvc->num_threads;
2186         cip->subcore_threads[sub] = n_thr;
2187         pvc->master_vcore = vc;
2188         list_del(&pvc->preempt_list);
2189         list_add_tail(&pvc->preempt_list, &cip->vcs[sub]);
2190 
2191         return true;
2192 }
2193 
2194 /*
2195  * Work out whether it is possible to piggyback the execution of
2196  * vcore *pvc onto the execution of the other vcores described in *cip.
2197  */
2198 static bool can_piggyback(struct kvmppc_vcore *pvc, struct core_info *cip,
2199                           int target_threads)
2200 {
2201         int sub;
2202 
2203         if (cip->total_threads + pvc->num_threads > target_threads)
2204                 return false;
2205         for (sub = 0; sub < cip->n_subcores; ++sub)
2206                 if (cip->subcore_threads[sub] &&
2207                     can_piggyback_subcore(pvc, cip, sub))
2208                         return true;
2209 
2210         if (can_dynamic_split(pvc, cip))
2211                 return true;
2212 
2213         return false;
2214 }
2215 
2216 static void prepare_threads(struct kvmppc_vcore *vc)
2217 {
2218         struct kvm_vcpu *vcpu, *vnext;
2219 
2220         list_for_each_entry_safe(vcpu, vnext, &vc->runnable_threads,
2221                                  arch.run_list) {
2222                 if (signal_pending(vcpu->arch.run_task))
2223                         vcpu->arch.ret = -EINTR;
2224                 else if (vcpu->arch.vpa.update_pending ||
2225                          vcpu->arch.slb_shadow.update_pending ||
2226                          vcpu->arch.dtl.update_pending)
2227                         vcpu->arch.ret = RESUME_GUEST;
2228                 else
2229                         continue;
2230                 kvmppc_remove_runnable(vc, vcpu);
2231                 wake_up(&vcpu->arch.cpu_run);
2232         }
2233 }
2234 
2235 static void collect_piggybacks(struct core_info *cip, int target_threads)
2236 {
2237         struct preempted_vcore_list *lp = this_cpu_ptr(&preempted_vcores);
2238         struct kvmppc_vcore *pvc, *vcnext;
2239 
2240         spin_lock(&lp->lock);
2241         list_for_each_entry_safe(pvc, vcnext, &lp->list, preempt_list) {
2242                 if (!spin_trylock(&pvc->lock))
2243                         continue;
2244                 prepare_threads(pvc);
2245                 if (!pvc->n_runnable) {
2246                         list_del_init(&pvc->preempt_list);
2247                         if (pvc->runner == NULL) {
2248                                 pvc->vcore_state = VCORE_INACTIVE;
2249                                 kvmppc_core_end_stolen(pvc);
2250                         }
2251                         spin_unlock(&pvc->lock);
2252                         continue;
2253                 }
2254                 if (!can_piggyback(pvc, cip, target_threads)) {
2255                         spin_unlock(&pvc->lock);
2256                         continue;
2257                 }
2258                 kvmppc_core_end_stolen(pvc);
2259                 pvc->vcore_state = VCORE_PIGGYBACK;
2260                 if (cip->total_threads >= target_threads)
2261                         break;
2262         }
2263         spin_unlock(&lp->lock);
2264 }
2265 
2266 static void post_guest_process(struct kvmppc_vcore *vc, bool is_master)
2267 {
2268         int still_running = 0;
2269         u64 now;
2270         long ret;
2271         struct kvm_vcpu *vcpu, *vnext;
2272 
2273         spin_lock(&vc->lock);
2274         now = get_tb();
2275         list_for_each_entry_safe(vcpu, vnext, &vc->runnable_threads,
2276                                  arch.run_list) {
2277                 /* cancel pending dec exception if dec is positive */
2278                 if (now < vcpu->arch.dec_expires &&
2279                     kvmppc_core_pending_dec(vcpu))
2280                         kvmppc_core_dequeue_dec(vcpu);
2281 
2282                 trace_kvm_guest_exit(vcpu);
2283 
2284                 ret = RESUME_GUEST;
2285                 if (vcpu->arch.trap)
2286                         ret = kvmppc_handle_exit_hv(vcpu->arch.kvm_run, vcpu,
2287                                                     vcpu->arch.run_task);
2288 
2289                 vcpu->arch.ret = ret;
2290                 vcpu->arch.trap = 0;
2291 
2292                 if (is_kvmppc_resume_guest(vcpu->arch.ret)) {
2293                         if (vcpu->arch.pending_exceptions)
2294                                 kvmppc_core_prepare_to_enter(vcpu);
2295                         if (vcpu->arch.ceded)
2296                                 kvmppc_set_timer(vcpu);
2297                         else
2298                                 ++still_running;
2299                 } else {
2300                         kvmppc_remove_runnable(vc, vcpu);
2301                         wake_up(&vcpu->arch.cpu_run);
2302                 }
2303         }
2304         list_del_init(&vc->preempt_list);
2305         if (!is_master) {
2306                 if (still_running > 0) {
2307                         kvmppc_vcore_preempt(vc);
2308                 } else if (vc->runner) {
2309                         vc->vcore_state = VCORE_PREEMPT;
2310                         kvmppc_core_start_stolen(vc);
2311                 } else {
2312                         vc->vcore_state = VCORE_INACTIVE;
2313                 }
2314                 if (vc->n_runnable > 0 && vc->runner == NULL) {
2315                         /* make sure there's a candidate runner awake */
2316                         vcpu = list_first_entry(&vc->runnable_threads,
2317                                                 struct kvm_vcpu, arch.run_list);
2318                         wake_up(&vcpu->arch.cpu_run);
2319                 }
2320         }
2321         spin_unlock(&vc->lock);
2322 }
2323 
2324 /*
2325  * Clear core from the list of active host cores as we are about to
2326  * enter the guest. Only do this if it is the primary thread of the
2327  * core (not if a subcore) that is entering the guest.
2328  */
2329 static inline void kvmppc_clear_host_core(int cpu)
2330 {
2331         int core;
2332 
2333         if (!kvmppc_host_rm_ops_hv || cpu_thread_in_core(cpu))
2334                 return;
2335         /*
2336          * Memory barrier can be omitted here as we will do a smp_wmb()
2337          * later in kvmppc_start_thread and we need ensure that state is
2338          * visible to other CPUs only after we enter guest.
2339          */
2340         core = cpu >> threads_shift;
2341         kvmppc_host_rm_ops_hv->rm_core[core].rm_state.in_host = 0;
2342 }
2343 
2344 /*
2345  * Advertise this core as an active host core since we exited the guest
2346  * Only need to do this if it is the primary thread of the core that is
2347  * exiting.
2348  */
2349 static inline void kvmppc_set_host_core(int cpu)
2350 {
2351         int core;
2352 
2353         if (!kvmppc_host_rm_ops_hv || cpu_thread_in_core(cpu))
2354                 return;
2355 
2356         /*
2357          * Memory barrier can be omitted here because we do a spin_unlock
2358          * immediately after this which provides the memory barrier.
2359          */
2360         core = cpu >> threads_shift;
2361         kvmppc_host_rm_ops_hv->rm_core[core].rm_state.in_host = 1;
2362 }
2363 
2364 /*
2365  * Run a set of guest threads on a physical core.
2366  * Called with vc->lock held.
2367  */
2368 static noinline void kvmppc_run_core(struct kvmppc_vcore *vc)
2369 {
2370         struct kvm_vcpu *vcpu, *vnext;
2371         int i;
2372         int srcu_idx;
2373         struct core_info core_info;
2374         struct kvmppc_vcore *pvc, *vcnext;
2375         struct kvm_split_mode split_info, *sip;
2376         int split, subcore_size, active;
2377         int sub;
2378         bool thr0_done;
2379         unsigned long cmd_bit, stat_bit;
2380         int pcpu, thr;
2381         int target_threads;
2382 
2383         /*
2384          * Remove from the list any threads that have a signal pending
2385          * or need a VPA update done
2386          */
2387         prepare_threads(vc);
2388 
2389         /* if the runner is no longer runnable, let the caller pick a new one */
2390         if (vc->runner->arch.state != KVMPPC_VCPU_RUNNABLE)
2391                 return;
2392 
2393         /*
2394          * Initialize *vc.
2395          */
2396         init_master_vcore(vc);
2397         vc->preempt_tb = TB_NIL;
2398 
2399         /*
2400          * Make sure we are running on primary threads, and that secondary
2401          * threads are offline.  Also check if the number of threads in this
2402          * guest are greater than the current system threads per guest.
2403          */
2404         if ((threads_per_core > 1) &&
2405             ((vc->num_threads > threads_per_subcore) || !on_primary_thread())) {
2406                 list_for_each_entry_safe(vcpu, vnext, &vc->runnable_threads,
2407                                          arch.run_list) {
2408                         vcpu->arch.ret = -EBUSY;
2409                         kvmppc_remove_runnable(vc, vcpu);
2410                         wake_up(&vcpu->arch.cpu_run);
2411                 }
2412                 goto out;
2413         }
2414 
2415         /*
2416          * See if we could run any other vcores on the physical core
2417          * along with this one.
2418          */
2419         init_core_info(&core_info, vc);
2420         pcpu = smp_processor_id();
2421         target_threads = threads_per_subcore;
2422         if (target_smt_mode && target_smt_mode < target_threads)
2423                 target_threads = target_smt_mode;
2424         if (vc->num_threads < target_threads)
2425                 collect_piggybacks(&core_info, target_threads);
2426 
2427         /* Decide on micro-threading (split-core) mode */
2428         subcore_size = threads_per_subcore;
2429         cmd_bit = stat_bit = 0;
2430         split = core_info.n_subcores;
2431         sip = NULL;
2432         if (split > 1) {
2433                 /* threads_per_subcore must be MAX_SMT_THREADS (8) here */
2434                 if (split == 2 && (dynamic_mt_modes & 2)) {
2435                         cmd_bit = HID0_POWER8_1TO2LPAR;
2436                         stat_bit = HID0_POWER8_2LPARMODE;
2437                 } else {
2438                         split = 4;
2439                         cmd_bit = HID0_POWER8_1TO4LPAR;
2440                         stat_bit = HID0_POWER8_4LPARMODE;
2441                 }
2442                 subcore_size = MAX_SMT_THREADS / split;
2443                 sip = &split_info;
2444                 memset(&split_info, 0, sizeof(split_info));
2445                 split_info.rpr = mfspr(SPRN_RPR);
2446                 split_info.pmmar = mfspr(SPRN_PMMAR);
2447                 split_info.ldbar = mfspr(SPRN_LDBAR);
2448                 split_info.subcore_size = subcore_size;
2449                 for (sub = 0; sub < core_info.n_subcores; ++sub)
2450                         split_info.master_vcs[sub] =
2451                                 list_first_entry(&core_info.vcs[sub],
2452                                         struct kvmppc_vcore, preempt_list);
2453                 /* order writes to split_info before kvm_split_mode pointer */
2454                 smp_wmb();
2455         }
2456         pcpu = smp_processor_id();
2457         for (thr = 0; thr < threads_per_subcore; ++thr)
2458                 paca[pcpu + thr].kvm_hstate.kvm_split_mode = sip;
2459 
2460         /* Initiate micro-threading (split-core) if required */
2461         if (cmd_bit) {
2462                 unsigned long hid0 = mfspr(SPRN_HID0);
2463 
2464                 hid0 |= cmd_bit | HID0_POWER8_DYNLPARDIS;
2465                 mb();
2466                 mtspr(SPRN_HID0, hid0);
2467                 isync();
2468                 for (;;) {
2469                         hid0 = mfspr(SPRN_HID0);
2470                         if (hid0 & stat_bit)
2471                                 break;
2472                         cpu_relax();
2473                 }
2474         }
2475 
2476         kvmppc_clear_host_core(pcpu);
2477 
2478         /* Start all the threads */
2479         active = 0;
2480         for (sub = 0; sub < core_info.n_subcores; ++sub) {
2481                 thr = subcore_thread_map[sub];
2482                 thr0_done = false;
2483                 active |= 1 << thr;
2484                 list_for_each_entry(pvc, &core_info.vcs[sub], preempt_list) {
2485                         pvc->pcpu = pcpu + thr;
2486                         list_for_each_entry(vcpu, &pvc->runnable_threads,
2487                                             arch.run_list) {
2488                                 kvmppc_start_thread(vcpu, pvc);
2489                                 kvmppc_create_dtl_entry(vcpu, pvc);
2490                                 trace_kvm_guest_enter(vcpu);
2491                                 if (!vcpu->arch.ptid)
2492                                         thr0_done = true;
2493                                 active |= 1 << (thr + vcpu->arch.ptid);
2494                         }
2495                         /*
2496                          * We need to start the first thread of each subcore
2497                          * even if it doesn't have a vcpu.
2498                          */
2499                         if (pvc->master_vcore == pvc && !thr0_done)
2500                                 kvmppc_start_thread(NULL, pvc);
2501                         thr += pvc->num_threads;
2502                 }
2503         }
2504 
2505         /*
2506          * Ensure that split_info.do_nap is set after setting
2507          * the vcore pointer in the PACA of the secondaries.
2508          */
2509         smp_mb();
2510         if (cmd_bit)
2511                 split_info.do_nap = 1;  /* ask secondaries to nap when done */
2512 
2513         /*
2514          * When doing micro-threading, poke the inactive threads as well.
2515          * This gets them to the nap instruction after kvm_do_nap,
2516          * which reduces the time taken to unsplit later.
2517          */
2518         if (split > 1)
2519                 for (thr = 1; thr < threads_per_subcore; ++thr)
2520                         if (!(active & (1 << thr)))
2521                                 kvmppc_ipi_thread(pcpu + thr);
2522 
2523         vc->vcore_state = VCORE_RUNNING;
2524         preempt_disable();
2525 
2526         trace_kvmppc_run_core(vc, 0);
2527 
2528         for (sub = 0; sub < core_info.n_subcores; ++sub)
2529                 list_for_each_entry(pvc, &core_info.vcs[sub], preempt_list)
2530                         spin_unlock(&pvc->lock);
2531 
2532         guest_enter();
2533 
2534         srcu_idx = srcu_read_lock(&vc->kvm->srcu);
2535 
2536         __kvmppc_vcore_entry();
2537 
2538         srcu_read_unlock(&vc->kvm->srcu, srcu_idx);
2539 
2540         spin_lock(&vc->lock);
2541         /* prevent other vcpu threads from doing kvmppc_start_thread() now */
2542         vc->vcore_state = VCORE_EXITING;
2543 
2544         /* wait for secondary threads to finish writing their state to memory */
2545         kvmppc_wait_for_nap();
2546 
2547         /* Return to whole-core mode if we split the core earlier */
2548         if (split > 1) {
2549                 unsigned long hid0 = mfspr(SPRN_HID0);
2550                 unsigned long loops = 0;
2551 
2552                 hid0 &= ~HID0_POWER8_DYNLPARDIS;
2553                 stat_bit = HID0_POWER8_2LPARMODE | HID0_POWER8_4LPARMODE;
2554                 mb();
2555                 mtspr(SPRN_HID0, hid0);
2556                 isync();
2557                 for (;;) {
2558                         hid0 = mfspr(SPRN_HID0);
2559                         if (!(hid0 & stat_bit))
2560                                 break;
2561                         cpu_relax();
2562                         ++loops;
2563                 }
2564                 split_info.do_nap = 0;
2565         }
2566 
2567         /* Let secondaries go back to the offline loop */
2568         for (i = 0; i < threads_per_subcore; ++i) {
2569                 kvmppc_release_hwthread(pcpu + i);
2570                 if (sip && sip->napped[i])
2571                         kvmppc_ipi_thread(pcpu + i);
2572         }
2573 
2574         kvmppc_set_host_core(pcpu);
2575 
2576         spin_unlock(&vc->lock);
2577 
2578         /* make sure updates to secondary vcpu structs are visible now */
2579         smp_mb();
2580         guest_exit();
2581 
2582         for (sub = 0; sub < core_info.n_subcores; ++sub)
2583                 list_for_each_entry_safe(pvc, vcnext, &core_info.vcs[sub],
2584                                          preempt_list)
2585                         post_guest_process(pvc, pvc == vc);
2586 
2587         spin_lock(&vc->lock);
2588         preempt_enable();
2589 
2590  out:
2591         vc->vcore_state = VCORE_INACTIVE;
2592         trace_kvmppc_run_core(vc, 1);
2593 }
2594 
2595 /*
2596  * Wait for some other vcpu thread to execute us, and
2597  * wake us up when we need to handle something in the host.
2598  */
2599 static void kvmppc_wait_for_exec(struct kvmppc_vcore *vc,
2600                                  struct kvm_vcpu *vcpu, int wait_state)
2601 {
2602         DEFINE_WAIT(wait);
2603 
2604         prepare_to_wait(&vcpu->arch.cpu_run, &wait, wait_state);
2605         if (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE) {
2606                 spin_unlock(&vc->lock);
2607                 schedule();
2608                 spin_lock(&vc->lock);
2609         }
2610         finish_wait(&vcpu->arch.cpu_run, &wait);
2611 }
2612 
2613 /*
2614  * All the vcpus in this vcore are idle, so wait for a decrementer
2615  * or external interrupt to one of the vcpus.  vc->lock is held.
2616  */
2617 static void kvmppc_vcore_blocked(struct kvmppc_vcore *vc)
2618 {
2619         struct kvm_vcpu *vcpu;
2620         int do_sleep = 1;
2621         DECLARE_SWAITQUEUE(wait);
2622 
2623         prepare_to_swait(&vc->wq, &wait, TASK_INTERRUPTIBLE);
2624 
2625         /*
2626          * Check one last time for pending exceptions and ceded state after
2627          * we put ourselves on the wait queue
2628          */
2629         list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list) {
2630                 if (vcpu->arch.pending_exceptions || !vcpu->arch.ceded) {
2631                         do_sleep = 0;
2632                         break;
2633                 }
2634         }
2635 
2636         if (!do_sleep) {
2637                 finish_swait(&vc->wq, &wait);
2638                 return;
2639         }
2640 
2641         vc->vcore_state = VCORE_SLEEPING;
2642         trace_kvmppc_vcore_blocked(vc, 0);
2643         spin_unlock(&vc->lock);
2644         schedule();
2645         finish_swait(&vc->wq, &wait);
2646         spin_lock(&vc->lock);
2647         vc->vcore_state = VCORE_INACTIVE;
2648         trace_kvmppc_vcore_blocked(vc, 1);
2649 }
2650 
2651 static int kvmppc_run_vcpu(struct kvm_run *kvm_run, struct kvm_vcpu *vcpu)
2652 {
2653         int n_ceded;
2654         struct kvmppc_vcore *vc;
2655         struct kvm_vcpu *v, *vn;
2656 
2657         trace_kvmppc_run_vcpu_enter(vcpu);
2658 
2659         kvm_run->exit_reason = 0;
2660         vcpu->arch.ret = RESUME_GUEST;
2661         vcpu->arch.trap = 0;
2662         kvmppc_update_vpas(vcpu);
2663 
2664         /*
2665          * Synchronize with other threads in this virtual core
2666          */
2667         vc = vcpu->arch.vcore;
2668         spin_lock(&vc->lock);
2669         vcpu->arch.ceded = 0;
2670         vcpu->arch.run_task = current;
2671         vcpu->arch.kvm_run = kvm_run;
2672         vcpu->arch.stolen_logged = vcore_stolen_time(vc, mftb());
2673         vcpu->arch.state = KVMPPC_VCPU_RUNNABLE;
2674         vcpu->arch.busy_preempt = TB_NIL;
2675         list_add_tail(&vcpu->arch.run_list, &vc->runnable_threads);
2676         ++vc->n_runnable;
2677 
2678         /*
2679          * This happens the first time this is called for a vcpu.
2680          * If the vcore is already running, we may be able to start
2681          * this thread straight away and have it join in.
2682          */
2683         if (!signal_pending(current)) {
2684                 if (vc->vcore_state == VCORE_PIGGYBACK) {
2685                         struct kvmppc_vcore *mvc = vc->master_vcore;
2686                         if (spin_trylock(&mvc->lock)) {
2687                                 if (mvc->vcore_state == VCORE_RUNNING &&
2688                                     !VCORE_IS_EXITING(mvc)) {
2689                                         kvmppc_create_dtl_entry(vcpu, vc);
2690                                         kvmppc_start_thread(vcpu, vc);
2691                                         trace_kvm_guest_enter(vcpu);
2692                                 }
2693                                 spin_unlock(&mvc->lock);
2694                         }
2695                 } else if (vc->vcore_state == VCORE_RUNNING &&
2696                            !VCORE_IS_EXITING(vc)) {
2697                         kvmppc_create_dtl_entry(vcpu, vc);
2698                         kvmppc_start_thread(vcpu, vc);
2699                         trace_kvm_guest_enter(vcpu);
2700                 } else if (vc->vcore_state == VCORE_SLEEPING) {
2701                         swake_up(&vc->wq);
2702                 }
2703 
2704         }
2705 
2706         while (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE &&
2707                !signal_pending(current)) {
2708                 if (vc->vcore_state == VCORE_PREEMPT && vc->runner == NULL)
2709                         kvmppc_vcore_end_preempt(vc);
2710 
2711                 if (vc->vcore_state != VCORE_INACTIVE) {
2712                         kvmppc_wait_for_exec(vc, vcpu, TASK_INTERRUPTIBLE);
2713                         continue;
2714                 }
2715                 list_for_each_entry_safe(v, vn, &vc->runnable_threads,
2716                                          arch.run_list) {
2717                         kvmppc_core_prepare_to_enter(v);
2718                         if (signal_pending(v->arch.run_task)) {
2719                                 kvmppc_remove_runnable(vc, v);
2720                                 v->stat.signal_exits++;
2721                                 v->arch.kvm_run->exit_reason = KVM_EXIT_INTR;
2722                                 v->arch.ret = -EINTR;
2723                                 wake_up(&v->arch.cpu_run);
2724                         }
2725                 }
2726                 if (!vc->n_runnable || vcpu->arch.state != KVMPPC_VCPU_RUNNABLE)
2727                         break;
2728                 n_ceded = 0;
2729                 list_for_each_entry(v, &vc->runnable_threads, arch.run_list) {
2730                         if (!v->arch.pending_exceptions)
2731                                 n_ceded += v->arch.ceded;
2732                         else
2733                                 v->arch.ceded = 0;
2734                 }
2735                 vc->runner = vcpu;
2736                 if (n_ceded == vc->n_runnable) {
2737                         kvmppc_vcore_blocked(vc);
2738                 } else if (need_resched()) {
2739                         kvmppc_vcore_preempt(vc);
2740                         /* Let something else run */
2741                         cond_resched_lock(&vc->lock);
2742                         if (vc->vcore_state == VCORE_PREEMPT)
2743                                 kvmppc_vcore_end_preempt(vc);
2744                 } else {
2745                         kvmppc_run_core(vc);
2746                 }
2747                 vc->runner = NULL;
2748         }
2749 
2750         while (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE &&
2751                (vc->vcore_state == VCORE_RUNNING ||
2752                 vc->vcore_state == VCORE_EXITING ||
2753                 vc->vcore_state == VCORE_PIGGYBACK))
2754                 kvmppc_wait_for_exec(vc, vcpu, TASK_UNINTERRUPTIBLE);
2755 
2756         if (vc->vcore_state == VCORE_PREEMPT && vc->runner == NULL)
2757                 kvmppc_vcore_end_preempt(vc);
2758 
2759         if (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE) {
2760                 kvmppc_remove_runnable(vc, vcpu);
2761                 vcpu->stat.signal_exits++;
2762                 kvm_run->exit_reason = KVM_EXIT_INTR;
2763                 vcpu->arch.ret = -EINTR;
2764         }
2765 
2766         if (vc->n_runnable && vc->vcore_state == VCORE_INACTIVE) {
2767                 /* Wake up some vcpu to run the core */
2768                 v = list_first_entry(&vc->runnable_threads,
2769                                      struct kvm_vcpu, arch.run_list);
2770                 wake_up(&v->arch.cpu_run);
2771         }
2772 
2773         trace_kvmppc_run_vcpu_exit(vcpu, kvm_run);
2774         spin_unlock(&vc->lock);
2775         return vcpu->arch.ret;
2776 }
2777 
2778 static int kvmppc_vcpu_run_hv(struct kvm_run *run, struct kvm_vcpu *vcpu)
2779 {
2780         int r;
2781         int srcu_idx;
2782 
2783         if (!vcpu->arch.sane) {
2784                 run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
2785                 return -EINVAL;
2786         }
2787 
2788         kvmppc_core_prepare_to_enter(vcpu);
2789 
2790         /* No need to go into the guest when all we'll do is come back out */
2791         if (signal_pending(current)) {
2792                 run->exit_reason = KVM_EXIT_INTR;
2793                 return -EINTR;
2794         }
2795 
2796         atomic_inc(&vcpu->kvm->arch.vcpus_running);
2797         /* Order vcpus_running vs. hpte_setup_done, see kvmppc_alloc_reset_hpt */
2798         smp_mb();
2799 
2800         /* On the first time here, set up HTAB and VRMA */
2801         if (!vcpu->kvm->arch.hpte_setup_done) {
2802                 r = kvmppc_hv_setup_htab_rma(vcpu);
2803                 if (r)
2804                         goto out;
2805         }
2806 
2807         flush_all_to_thread(current);
2808 
2809         vcpu->arch.wqp = &vcpu->arch.vcore->wq;
2810         vcpu->arch.pgdir = current->mm->pgd;
2811         vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST;
2812 
2813         do {
2814                 r = kvmppc_run_vcpu(run, vcpu);
2815 
2816                 if (run->exit_reason == KVM_EXIT_PAPR_HCALL &&
2817                     !(vcpu->arch.shregs.msr & MSR_PR)) {
2818                         trace_kvm_hcall_enter(vcpu);
2819                         r = kvmppc_pseries_do_hcall(vcpu);
2820                         trace_kvm_hcall_exit(vcpu, r);
2821                         kvmppc_core_prepare_to_enter(vcpu);
2822                 } else if (r == RESUME_PAGE_FAULT) {
2823                         srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
2824                         r = kvmppc_book3s_hv_page_fault(run, vcpu,
2825                                 vcpu->arch.fault_dar, vcpu->arch.fault_dsisr);
2826                         srcu_read_unlock(&vcpu->kvm->srcu, srcu_idx);
2827                 }
2828         } while (is_kvmppc_resume_guest(r));
2829 
2830  out:
2831         vcpu->arch.state = KVMPPC_VCPU_NOTREADY;
2832         atomic_dec(&vcpu->kvm->arch.vcpus_running);
2833         return r;
2834 }
2835 
2836 static void kvmppc_add_seg_page_size(struct kvm_ppc_one_seg_page_size **sps,
2837                                      int linux_psize)
2838 {
2839         struct mmu_psize_def *def = &mmu_psize_defs[linux_psize];
2840 
2841         if (!def->shift)
2842                 return;
2843         (*sps)->page_shift = def->shift;
2844         (*sps)->slb_enc = def->sllp;
2845         (*sps)->enc[0].page_shift = def->shift;
2846         (*sps)->enc[0].pte_enc = def->penc[linux_psize];
2847         /*
2848          * Add 16MB MPSS support if host supports it
2849          */
2850         if (linux_psize != MMU_PAGE_16M && def->penc[MMU_PAGE_16M] != -1) {
2851                 (*sps)->enc[1].page_shift = 24;
2852                 (*sps)->enc[1].pte_enc = def->penc[MMU_PAGE_16M];
2853         }
2854         (*sps)++;
2855 }
2856 
2857 static int kvm_vm_ioctl_get_smmu_info_hv(struct kvm *kvm,
2858                                          struct kvm_ppc_smmu_info *info)
2859 {
2860         struct kvm_ppc_one_seg_page_size *sps;
2861 
2862         info->flags = KVM_PPC_PAGE_SIZES_REAL;
2863         if (mmu_has_feature(MMU_FTR_1T_SEGMENT))
2864                 info->flags |= KVM_PPC_1T_SEGMENTS;
2865         info->slb_size = mmu_slb_size;
2866 
2867         /* We only support these sizes for now, and no muti-size segments */
2868         sps = &info->sps[0];
2869         kvmppc_add_seg_page_size(&sps, MMU_PAGE_4K);
2870         kvmppc_add_seg_page_size(&sps, MMU_PAGE_64K);
2871         kvmppc_add_seg_page_size(&sps, MMU_PAGE_16M);
2872 
2873         return 0;
2874 }
2875 
2876 /*
2877  * Get (and clear) the dirty memory log for a memory slot.
2878  */
2879 static int kvm_vm_ioctl_get_dirty_log_hv(struct kvm *kvm,
2880                                          struct kvm_dirty_log *log)
2881 {
2882         struct kvm_memslots *slots;
2883         struct kvm_memory_slot *memslot;
2884         int r;
2885         unsigned long n;
2886 
2887         mutex_lock(&kvm->slots_lock);
2888 
2889         r = -EINVAL;
2890         if (log->slot >= KVM_USER_MEM_SLOTS)
2891                 goto out;
2892 
2893         slots = kvm_memslots(kvm);
2894         memslot = id_to_memslot(slots, log->slot);
2895         r = -ENOENT;
2896         if (!memslot->dirty_bitmap)
2897                 goto out;
2898 
2899         n = kvm_dirty_bitmap_bytes(memslot);
2900         memset(memslot->dirty_bitmap, 0, n);
2901 
2902         r = kvmppc_hv_get_dirty_log(kvm, memslot, memslot->dirty_bitmap);
2903         if (r)
2904                 goto out;
2905 
2906         r = -EFAULT;
2907         if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
2908                 goto out;
2909 
2910         r = 0;
2911 out:
2912         mutex_unlock(&kvm->slots_lock);
2913         return r;
2914 }
2915 
2916 static void kvmppc_core_free_memslot_hv(struct kvm_memory_slot *free,
2917                                         struct kvm_memory_slot *dont)
2918 {
2919         if (!dont || free->arch.rmap != dont->arch.rmap) {
2920                 vfree(free->arch.rmap);
2921                 free->arch.rmap = NULL;
2922         }
2923 }
2924 
2925 static int kvmppc_core_create_memslot_hv(struct kvm_memory_slot *slot,
2926                                          unsigned long npages)
2927 {
2928         slot->arch.rmap = vzalloc(npages * sizeof(*slot->arch.rmap));
2929         if (!slot->arch.rmap)
2930                 return -ENOMEM;
2931 
2932         return 0;
2933 }
2934 
2935 static int kvmppc_core_prepare_memory_region_hv(struct kvm *kvm,
2936                                         struct kvm_memory_slot *memslot,
2937                                         const struct kvm_userspace_memory_region *mem)
2938 {
2939         return 0;
2940 }
2941 
2942 static void kvmppc_core_commit_memory_region_hv(struct kvm *kvm,
2943                                 const struct kvm_userspace_memory_region *mem,
2944                                 const struct kvm_memory_slot *old,
2945                                 const struct kvm_memory_slot *new)
2946 {
2947         unsigned long npages = mem->memory_size >> PAGE_SHIFT;
2948         struct kvm_memslots *slots;
2949         struct kvm_memory_slot *memslot;
2950 
2951         if (npages && old->npages) {
2952                 /*
2953                  * If modifying a memslot, reset all the rmap dirty bits.
2954                  * If this is a new memslot, we don't need to do anything
2955                  * since the rmap array starts out as all zeroes,
2956                  * i.e. no pages are dirty.
2957                  */
2958                 slots = kvm_memslots(kvm);
2959                 memslot = id_to_memslot(slots, mem->slot);
2960                 kvmppc_hv_get_dirty_log(kvm, memslot, NULL);
2961         }
2962 }
2963 
2964 /*
2965  * Update LPCR values in kvm->arch and in vcores.
2966  * Caller must hold kvm->lock.
2967  */
2968 void kvmppc_update_lpcr(struct kvm *kvm, unsigned long lpcr, unsigned long mask)
2969 {
2970         long int i;
2971         u32 cores_done = 0;
2972 
2973         if ((kvm->arch.lpcr & mask) == lpcr)
2974                 return;
2975 
2976         kvm->arch.lpcr = (kvm->arch.lpcr & ~mask) | lpcr;
2977 
2978         for (i = 0; i < KVM_MAX_VCORES; ++i) {
2979                 struct kvmppc_vcore *vc = kvm->arch.vcores[i];
2980                 if (!vc)
2981                         continue;
2982                 spin_lock(&vc->lock);
2983                 vc->lpcr = (vc->lpcr & ~mask) | lpcr;
2984                 spin_unlock(&vc->lock);
2985                 if (++cores_done >= kvm->arch.online_vcores)
2986                         break;
2987         }
2988 }
2989 
2990 static void kvmppc_mmu_destroy_hv(struct kvm_vcpu *vcpu)
2991 {
2992         return;
2993 }
2994 
2995 static int kvmppc_hv_setup_htab_rma(struct kvm_vcpu *vcpu)
2996 {
2997         int err = 0;
2998         struct kvm *kvm = vcpu->kvm;
2999         unsigned long hva;
3000         struct kvm_memory_slot *memslot;
3001         struct vm_area_struct *vma;
3002         unsigned long lpcr = 0, senc;
3003         unsigned long psize, porder;
3004         int srcu_idx;
3005 
3006         mutex_lock(&kvm->lock);
3007         if (kvm->arch.hpte_setup_done)
3008                 goto out;       /* another vcpu beat us to it */
3009 
3010         /* Allocate hashed page table (if not done already) and reset it */
3011         if (!kvm->arch.hpt_virt) {
3012                 err = kvmppc_alloc_hpt(kvm, NULL);
3013                 if (err) {
3014                         pr_err("KVM: Couldn't alloc HPT\n");
3015                         goto out;
3016                 }
3017         }
3018 
3019         /* Look up the memslot for guest physical address 0 */
3020         srcu_idx = srcu_read_lock(&kvm->srcu);
3021         memslot = gfn_to_memslot(kvm, 0);
3022 
3023         /* We must have some memory at 0 by now */
3024         err = -EINVAL;
3025         if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID))
3026                 goto out_srcu;
3027 
3028         /* Look up the VMA for the start of this memory slot */
3029         hva = memslot->userspace_addr;
3030         down_read(&current->mm->mmap_sem);
3031         vma = find_vma(current->mm, hva);
3032         if (!vma || vma->vm_start > hva || (vma->vm_flags & VM_IO))
3033                 goto up_out;
3034 
3035         psize = vma_kernel_pagesize(vma);
3036         porder = __ilog2(psize);
3037 
3038         up_read(&current->mm->mmap_sem);
3039 
3040         /* We can handle 4k, 64k or 16M pages in the VRMA */
3041         err = -EINVAL;
3042         if (!(psize == 0x1000 || psize == 0x10000 ||
3043               psize == 0x1000000))
3044                 goto out_srcu;
3045 
3046         /* Update VRMASD field in the LPCR */
3047         senc = slb_pgsize_encoding(psize);
3048         kvm->arch.vrma_slb_v = senc | SLB_VSID_B_1T |
3049                 (VRMA_VSID << SLB_VSID_SHIFT_1T);
3050         /* the -4 is to account for senc values starting at 0x10 */
3051         lpcr = senc << (LPCR_VRMASD_SH - 4);
3052 
3053         /* Create HPTEs in the hash page table for the VRMA */
3054         kvmppc_map_vrma(vcpu, memslot, porder);
3055 
3056         kvmppc_update_lpcr(kvm, lpcr, LPCR_VRMASD);
3057 
3058         /* Order updates to kvm->arch.lpcr etc. vs. hpte_setup_done */
3059         smp_wmb();
3060         kvm->arch.hpte_setup_done = 1;
3061         err = 0;
3062  out_srcu:
3063         srcu_read_unlock(&kvm->srcu, srcu_idx);
3064  out:
3065         mutex_unlock(&kvm->lock);
3066         return err;
3067 
3068  up_out:
3069         up_read(&current->mm->mmap_sem);
3070         goto out_srcu;
3071 }
3072 
3073 #ifdef CONFIG_KVM_XICS
3074 static int kvmppc_cpu_notify(struct notifier_block *self, unsigned long action,
3075                         void *hcpu)
3076 {
3077         unsigned long cpu = (long)hcpu;
3078 
3079         switch (action) {
3080         case CPU_UP_PREPARE:
3081         case CPU_UP_PREPARE_FROZEN:
3082                 kvmppc_set_host_core(cpu);
3083                 break;
3084 
3085 #ifdef CONFIG_HOTPLUG_CPU
3086         case CPU_DEAD:
3087         case CPU_DEAD_FROZEN:
3088         case CPU_UP_CANCELED:
3089         case CPU_UP_CANCELED_FROZEN:
3090                 kvmppc_clear_host_core(cpu);
3091                 break;
3092 #endif
3093         default:
3094                 break;
3095         }
3096 
3097         return NOTIFY_OK;
3098 }
3099 
3100 static struct notifier_block kvmppc_cpu_notifier = {
3101             .notifier_call = kvmppc_cpu_notify,
3102 };
3103 
3104 /*
3105  * Allocate a per-core structure for managing state about which cores are
3106  * running in the host versus the guest and for exchanging data between
3107  * real mode KVM and CPU running in the host.
3108  * This is only done for the first VM.
3109  * The allocated structure stays even if all VMs have stopped.
3110  * It is only freed when the kvm-hv module is unloaded.
3111  * It's OK for this routine to fail, we just don't support host
3112  * core operations like redirecting H_IPI wakeups.
3113  */
3114 void kvmppc_alloc_host_rm_ops(void)
3115 {
3116         struct kvmppc_host_rm_ops *ops;
3117         unsigned long l_ops;
3118         int cpu, core;
3119         int size;
3120 
3121         /* Not the first time here ? */
3122         if (kvmppc_host_rm_ops_hv != NULL)
3123                 return;
3124 
3125         ops = kzalloc(sizeof(struct kvmppc_host_rm_ops), GFP_KERNEL);
3126         if (!ops)
3127                 return;
3128 
3129         size = cpu_nr_cores() * sizeof(struct kvmppc_host_rm_core);
3130         ops->rm_core = kzalloc(size, GFP_KERNEL);
3131 
3132         if (!ops->rm_core) {
3133                 kfree(ops);
3134                 return;
3135         }
3136 
3137         get_online_cpus();
3138 
3139         for (cpu = 0; cpu < nr_cpu_ids; cpu += threads_per_core) {
3140                 if (!cpu_online(cpu))
3141                         continue;
3142 
3143                 core = cpu >> threads_shift;
3144                 ops->rm_core[core].rm_state.in_host = 1;
3145         }
3146 
3147         ops->vcpu_kick = kvmppc_fast_vcpu_kick_hv;
3148 
3149         /*
3150          * Make the contents of the kvmppc_host_rm_ops structure visible
3151          * to other CPUs before we assign it to the global variable.
3152          * Do an atomic assignment (no locks used here), but if someone
3153          * beats us to it, just free our copy and return.
3154          */
3155         smp_wmb();
3156         l_ops = (unsigned long) ops;
3157 
3158         if (cmpxchg64((unsigned long *)&kvmppc_host_rm_ops_hv, 0, l_ops)) {
3159                 put_online_cpus();
3160                 kfree(ops->rm_core);
3161                 kfree(ops);
3162                 return;
3163         }
3164 
3165         register_cpu_notifier(&kvmppc_cpu_notifier);
3166 
3167         put_online_cpus();
3168 }
3169 
3170 void kvmppc_free_host_rm_ops(void)
3171 {
3172         if (kvmppc_host_rm_ops_hv) {
3173                 unregister_cpu_notifier(&kvmppc_cpu_notifier);
3174                 kfree(kvmppc_host_rm_ops_hv->rm_core);
3175                 kfree(kvmppc_host_rm_ops_hv);
3176                 kvmppc_host_rm_ops_hv = NULL;
3177         }
3178 }
3179 #endif
3180 
3181 static int kvmppc_core_init_vm_hv(struct kvm *kvm)
3182 {
3183         unsigned long lpcr, lpid;
3184         char buf[32];
3185 
3186         /* Allocate the guest's logical partition ID */
3187 
3188         lpid = kvmppc_alloc_lpid();
3189         if ((long)lpid < 0)
3190                 return -ENOMEM;
3191         kvm->arch.lpid = lpid;
3192 
3193         kvmppc_alloc_host_rm_ops();
3194 
3195         /*
3196          * Since we don't flush the TLB when tearing down a VM,
3197          * and this lpid might have previously been used,
3198          * make sure we flush on each core before running the new VM.
3199          */
3200         cpumask_setall(&kvm->arch.need_tlb_flush);
3201 
3202         /* Start out with the default set of hcalls enabled */
3203         memcpy(kvm->arch.enabled_hcalls, default_enabled_hcalls,
3204                sizeof(kvm->arch.enabled_hcalls));
3205 
3206         kvm->arch.host_sdr1 = mfspr(SPRN_SDR1);
3207 
3208         /* Init LPCR for virtual RMA mode */
3209         kvm->arch.host_lpid = mfspr(SPRN_LPID);
3210         kvm->arch.host_lpcr = lpcr = mfspr(SPRN_LPCR);
3211         lpcr &= LPCR_PECE | LPCR_LPES;
3212         lpcr |= (4UL << LPCR_DPFD_SH) | LPCR_HDICE |
3213                 LPCR_VPM0 | LPCR_VPM1;
3214         kvm->arch.vrma_slb_v = SLB_VSID_B_1T |
3215                 (VRMA_VSID << SLB_VSID_SHIFT_1T);
3216         /* On POWER8 turn on online bit to enable PURR/SPURR */
3217         if (cpu_has_feature(CPU_FTR_ARCH_207S))
3218                 lpcr |= LPCR_ONL;
3219         kvm->arch.lpcr = lpcr;
3220 
3221         /*
3222          * Track that we now have a HV mode VM active. This blocks secondary
3223          * CPU threads from coming online.
3224          */
3225         kvm_hv_vm_activated();
3226 
3227         /*
3228          * Create a debugfs directory for the VM
3229          */
3230         snprintf(buf, sizeof(buf), "vm%d", current->pid);
3231         kvm->arch.debugfs_dir = debugfs_create_dir(buf, kvm_debugfs_dir);
3232         if (!IS_ERR_OR_NULL(kvm->arch.debugfs_dir))
3233                 kvmppc_mmu_debugfs_init(kvm);
3234 
3235         return 0;
3236 }
3237 
3238 static void kvmppc_free_vcores(struct kvm *kvm)
3239 {
3240         long int i;
3241 
3242         for (i = 0; i < KVM_MAX_VCORES; ++i)
3243                 kfree(kvm->arch.vcores[i]);
3244         kvm->arch.online_vcores = 0;
3245 }
3246 
3247 static void kvmppc_core_destroy_vm_hv(struct kvm *kvm)
3248 {
3249         debugfs_remove_recursive(kvm->arch.debugfs_dir);
3250 
3251         kvm_hv_vm_deactivated();
3252 
3253         kvmppc_free_vcores(kvm);
3254 
3255         kvmppc_free_hpt(kvm);
3256 }
3257 
3258 /* We don't need to emulate any privileged instructions or dcbz */
3259 static int kvmppc_core_emulate_op_hv(struct kvm_run *run, struct kvm_vcpu *vcpu,
3260                                      unsigned int inst, int *advance)
3261 {
3262         return EMULATE_FAIL;
3263 }
3264 
3265 static int kvmppc_core_emulate_mtspr_hv(struct kvm_vcpu *vcpu, int sprn,
3266                                         ulong spr_val)
3267 {
3268         return EMULATE_FAIL;
3269 }
3270 
3271 static int kvmppc_core_emulate_mfspr_hv(struct kvm_vcpu *vcpu, int sprn,
3272                                         ulong *spr_val)
3273 {
3274         return EMULATE_FAIL;
3275 }
3276 
3277 static int kvmppc_core_check_processor_compat_hv(void)
3278 {
3279         if (!cpu_has_feature(CPU_FTR_HVMODE) ||
3280             !cpu_has_feature(CPU_FTR_ARCH_206))
3281                 return -EIO;
3282         /*
3283          * Disable KVM for Power9, untill the required bits merged.
3284          */
3285         if (cpu_has_feature(CPU_FTR_ARCH_300))
3286                 return -EIO;
3287 
3288         return 0;
3289 }
3290 
3291 static long kvm_arch_vm_ioctl_hv(struct file *filp,
3292                                  unsigned int ioctl, unsigned long arg)
3293 {
3294         struct kvm *kvm __maybe_unused = filp->private_data;
3295         void __user *argp = (void __user *)arg;
3296         long r;
3297 
3298         switch (ioctl) {
3299 
3300         case KVM_PPC_ALLOCATE_HTAB: {
3301                 u32 htab_order;
3302 
3303                 r = -EFAULT;
3304                 if (get_user(htab_order, (u32 __user *)argp))
3305                         break;
3306                 r = kvmppc_alloc_reset_hpt(kvm, &htab_order);
3307                 if (r)
3308                         break;
3309                 r = -EFAULT;
3310                 if (put_user(htab_order, (u32 __user *)argp))
3311                         break;
3312                 r = 0;
3313                 break;
3314         }
3315 
3316         case KVM_PPC_GET_HTAB_FD: {
3317                 struct kvm_get_htab_fd ghf;
3318 
3319                 r = -EFAULT;
3320                 if (copy_from_user(&ghf, argp, sizeof(ghf)))
3321                         break;
3322                 r = kvm_vm_ioctl_get_htab_fd(kvm, &ghf);
3323                 break;
3324         }
3325 
3326         default:
3327                 r = -ENOTTY;
3328         }
3329 
3330         return r;
3331 }
3332 
3333 /*
3334  * List of hcall numbers to enable by default.
3335  * For compatibility with old userspace, we enable by default
3336  * all hcalls that were implemented before the hcall-enabling
3337  * facility was added.  Note this list should not include H_RTAS.
3338  */
3339 static unsigned int default_hcall_list[] = {
3340         H_REMOVE,
3341         H_ENTER,
3342         H_READ,
3343         H_PROTECT,
3344         H_BULK_REMOVE,
3345         H_GET_TCE,
3346         H_PUT_TCE,
3347         H_SET_DABR,
3348         H_SET_XDABR,
3349         H_CEDE,
3350         H_PROD,
3351         H_CONFER,
3352         H_REGISTER_VPA,
3353 #ifdef CONFIG_KVM_XICS
3354         H_EOI,
3355         H_CPPR,
3356         H_IPI,
3357         H_IPOLL,
3358         H_XIRR,
3359         H_XIRR_X,
3360 #endif
3361         0
3362 };
3363 
3364 static void init_default_hcalls(void)
3365 {
3366         int i;
3367         unsigned int hcall;
3368 
3369         for (i = 0; default_hcall_list[i]; ++i) {
3370                 hcall = default_hcall_list[i];
3371                 WARN_ON(!kvmppc_hcall_impl_hv(hcall));
3372                 __set_bit(hcall / 4, default_enabled_hcalls);
3373         }
3374 }
3375 
3376 static struct kvmppc_ops kvm_ops_hv = {
3377         .get_sregs = kvm_arch_vcpu_ioctl_get_sregs_hv,
3378         .set_sregs = kvm_arch_vcpu_ioctl_set_sregs_hv,
3379         .get_one_reg = kvmppc_get_one_reg_hv,
3380         .set_one_reg = kvmppc_set_one_reg_hv,
3381         .vcpu_load   = kvmppc_core_vcpu_load_hv,
3382         .vcpu_put    = kvmppc_core_vcpu_put_hv,
3383         .set_msr     = kvmppc_set_msr_hv,
3384         .vcpu_run    = kvmppc_vcpu_run_hv,
3385         .vcpu_create = kvmppc_core_vcpu_create_hv,
3386         .vcpu_free   = kvmppc_core_vcpu_free_hv,
3387         .check_requests = kvmppc_core_check_requests_hv,
3388         .get_dirty_log  = kvm_vm_ioctl_get_dirty_log_hv,
3389         .flush_memslot  = kvmppc_core_flush_memslot_hv,
3390         .prepare_memory_region = kvmppc_core_prepare_memory_region_hv,
3391         .commit_memory_region  = kvmppc_core_commit_memory_region_hv,
3392         .unmap_hva = kvm_unmap_hva_hv,
3393         .unmap_hva_range = kvm_unmap_hva_range_hv,
3394         .age_hva  = kvm_age_hva_hv,
3395         .test_age_hva = kvm_test_age_hva_hv,
3396         .set_spte_hva = kvm_set_spte_hva_hv,
3397         .mmu_destroy  = kvmppc_mmu_destroy_hv,
3398         .free_memslot = kvmppc_core_free_memslot_hv,
3399         .create_memslot = kvmppc_core_create_memslot_hv,
3400         .init_vm =  kvmppc_core_init_vm_hv,
3401         .destroy_vm = kvmppc_core_destroy_vm_hv,
3402         .get_smmu_info = kvm_vm_ioctl_get_smmu_info_hv,
3403         .emulate_op = kvmppc_core_emulate_op_hv,
3404         .emulate_mtspr = kvmppc_core_emulate_mtspr_hv,
3405         .emulate_mfspr = kvmppc_core_emulate_mfspr_hv,
3406         .fast_vcpu_kick = kvmppc_fast_vcpu_kick_hv,
3407         .arch_vm_ioctl  = kvm_arch_vm_ioctl_hv,
3408         .hcall_implemented = kvmppc_hcall_impl_hv,
3409 };
3410 
3411 static int kvm_init_subcore_bitmap(void)
3412 {
3413         int i, j;
3414         int nr_cores = cpu_nr_cores();
3415         struct sibling_subcore_state *sibling_subcore_state;
3416 
3417         for (i = 0; i < nr_cores; i++) {
3418                 int first_cpu = i * threads_per_core;
3419                 int node = cpu_to_node(first_cpu);
3420 
3421                 /* Ignore if it is already allocated. */
3422                 if (paca[first_cpu].sibling_subcore_state)
3423                         continue;
3424 
3425                 sibling_subcore_state =
3426                         kmalloc_node(sizeof(struct sibling_subcore_state),
3427                                                         GFP_KERNEL, node);
3428                 if (!sibling_subcore_state)
3429                         return -ENOMEM;
3430 
3431                 memset(sibling_subcore_state, 0,
3432                                 sizeof(struct sibling_subcore_state));
3433 
3434                 for (j = 0; j < threads_per_core; j++) {
3435                         int cpu = first_cpu + j;
3436 
3437                         paca[cpu].sibling_subcore_state = sibling_subcore_state;
3438                 }
3439         }
3440         return 0;
3441 }
3442 
3443 static int kvmppc_book3s_init_hv(void)
3444 {
3445         int r;
3446         /*
3447          * FIXME!! Do we need to check on all cpus ?
3448          */
3449         r = kvmppc_core_check_processor_compat_hv();
3450         if (r < 0)
3451                 return -ENODEV;
3452 
3453         r = kvm_init_subcore_bitmap();
3454         if (r)
3455                 return r;
3456 
3457         kvm_ops_hv.owner = THIS_MODULE;
3458         kvmppc_hv_ops = &kvm_ops_hv;
3459 
3460         init_default_hcalls();
3461 
3462         init_vcore_lists();
3463 
3464         r = kvmppc_mmu_hv_init();
3465         return r;
3466 }
3467 
3468 static void kvmppc_book3s_exit_hv(void)
3469 {
3470         kvmppc_free_host_rm_ops();
3471         kvmppc_hv_ops = NULL;
3472 }
3473 
3474 module_init(kvmppc_book3s_init_hv);
3475 module_exit(kvmppc_book3s_exit_hv);
3476 MODULE_LICENSE("GPL");
3477 MODULE_ALIAS_MISCDEV(KVM_MINOR);
3478 MODULE_ALIAS("devname:kvm");
3479 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp