gem5  v20.0.0.3
base.cc
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2012, 2015, 2017 ARM Limited
3  * All rights reserved
4  *
5  * The license below extends only to copyright in the software and shall
6  * not be construed as granting a license to any other intellectual
7  * property including but not limited to intellectual property relating
8  * to a hardware implementation of the functionality of the software
9  * licensed hereunder. You may use the software subject to the license
10  * terms below provided that you ensure that this notice is replicated
11  * unmodified and in its entirety in all distributions of the software,
12  * modified or unmodified, in source code or in binary form.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions are
16  * met: redistributions of source code must retain the above copyright
17  * notice, this list of conditions and the following disclaimer;
18  * redistributions in binary form must reproduce the above copyright
19  * notice, this list of conditions and the following disclaimer in the
20  * documentation and/or other materials provided with the distribution;
21  * neither the name of the copyright holders nor the names of its
22  * contributors may be used to endorse or promote products derived from
23  * this software without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 #include "cpu/kvm/base.hh"
39 
40 #include <linux/kvm.h>
41 #include <sys/ioctl.h>
42 #include <sys/mman.h>
43 #include <unistd.h>
44 
45 #include <cerrno>
46 #include <csignal>
47 #include <ostream>
48 
49 #include "arch/utility.hh"
50 #include "debug/Checkpoint.hh"
51 #include "debug/Drain.hh"
52 #include "debug/Kvm.hh"
53 #include "debug/KvmIO.hh"
54 #include "debug/KvmRun.hh"
55 #include "params/BaseKvmCPU.hh"
56 #include "sim/process.hh"
57 #include "sim/system.hh"
58 
59 /* Used by some KVM macros */
60 #define PAGE_SIZE pageSize
61 
62 BaseKvmCPU::BaseKvmCPU(BaseKvmCPUParams *params)
63  : BaseCPU(params),
64  vm(*params->system->getKvmVM()),
65  _status(Idle),
66  dataPort(name() + ".dcache_port", this),
67  instPort(name() + ".icache_port", this),
68  alwaysSyncTC(params->alwaysSyncTC),
69  threadContextDirty(true),
70  kvmStateDirty(false),
71  vcpuID(vm.allocVCPUID()), vcpuFD(-1), vcpuMMapSize(0),
72  _kvmRun(NULL), mmioRing(NULL),
73  pageSize(sysconf(_SC_PAGE_SIZE)),
74  tickEvent([this]{ tick(); }, "BaseKvmCPU tick",
75  false, Event::CPU_Tick_Pri),
77  perfControlledByTimer(params->usePerfOverflow),
78  hostFactor(params->hostFactor),
79  ctrInsts(0)
80 {
81  if (pageSize == -1)
82  panic("KVM: Failed to determine host page size (%i)\n",
83  errno);
84 
85  if (FullSystem)
86  thread = new SimpleThread(this, 0, params->system, params->itb, params->dtb,
87  params->isa[0]);
88  else
89  thread = new SimpleThread(this, /* thread_num */ 0, params->system,
90  params->workload[0], params->itb,
91  params->dtb, params->isa[0]);
92 
94  tc = thread->getTC();
95  threadContexts.push_back(tc);
96 }
97 
99 {
100  if (_kvmRun)
101  munmap(_kvmRun, vcpuMMapSize);
102  close(vcpuFD);
103 }
104 
105 void
107 {
108  BaseCPU::init();
109 
110  if (numThreads != 1)
111  fatal("KVM: Multithreading not supported");
112 
113  tc->initMemProxies(tc);
114 }
115 
116 void
118 {
119  const BaseKvmCPUParams * const p(
120  dynamic_cast<const BaseKvmCPUParams *>(params()));
121 
122  Kvm &kvm(*vm.kvm);
123 
125 
126  assert(vcpuFD == -1);
127 
128  // Tell the VM that a CPU is about to start.
129  vm.cpuStartup();
130 
131  // We can't initialize KVM CPUs in BaseKvmCPU::init() since we are
132  // not guaranteed that the parent KVM VM has initialized at that
133  // point. Initialize virtual CPUs here instead.
135 
136  // Map the KVM run structure */
138  _kvmRun = (struct kvm_run *)mmap(0, vcpuMMapSize,
139  PROT_READ | PROT_WRITE, MAP_SHARED,
140  vcpuFD, 0);
141  if (_kvmRun == MAP_FAILED)
142  panic("KVM: Failed to map run data structure\n");
143 
144  // Setup a pointer to the MMIO ring buffer if coalesced MMIO is
145  // available. The offset into the KVM's communication page is
146  // provided by the coalesced MMIO capability.
147  int mmioOffset(kvm.capCoalescedMMIO());
148  if (!p->useCoalescedMMIO) {
149  inform("KVM: Coalesced MMIO disabled by config.\n");
150  } else if (mmioOffset) {
151  inform("KVM: Coalesced IO available\n");
152  mmioRing = (struct kvm_coalesced_mmio_ring *)(
153  (char *)_kvmRun + (mmioOffset * pageSize));
154  } else {
155  inform("KVM: Coalesced not supported by host OS\n");
156  }
157 
158  thread->startup();
159 
160  Event *startupEvent(
161  new EventFunctionWrapper([this]{ startupThread(); }, name(), true));
162  schedule(startupEvent, curTick());
163 }
164 
167 {
168  return (activeMMIOReqs || pendingMMIOPkts.size())
170 }
171 
172 Tick
174 {
175  if (cpu->system->isAtomicMode()) {
176  Tick delay = sendAtomic(pkt);
177  delete pkt;
178  return delay;
179  } else {
180  if (pendingMMIOPkts.empty() && sendTimingReq(pkt)) {
181  activeMMIOReqs++;
182  } else {
183  pendingMMIOPkts.push(pkt);
184  }
185  // Return value is irrelevant for timing-mode accesses.
186  return 0;
187  }
188 }
189 
190 bool
192 {
193  DPRINTF(KvmIO, "KVM: Finished timing request\n");
194 
195  delete pkt;
196  activeMMIOReqs--;
197 
198  // We can switch back into KVM when all pending and in-flight MMIO
199  // operations have completed.
200  if (!(activeMMIOReqs || pendingMMIOPkts.size())) {
201  DPRINTF(KvmIO, "KVM: Finished all outstanding timing requests\n");
202  cpu->finishMMIOPending();
203  }
204  return true;
205 }
206 
207 void
209 {
210  DPRINTF(KvmIO, "KVM: Retry for timing request\n");
211 
212  assert(pendingMMIOPkts.size());
213 
214  // Assuming that we can issue infinite requests this cycle is a bit
215  // unrealistic, but it's not worth modeling something more complex in
216  // KVM.
217  while (pendingMMIOPkts.size() && sendTimingReq(pendingMMIOPkts.front())) {
218  pendingMMIOPkts.pop();
219  activeMMIOReqs++;
220  }
221 }
222 
223 void
225 {
226  assert(_status = RunningMMIOPending);
227  assert(!tickEvent.scheduled());
228 
231 }
232 
233 void
235 {
236  // Do thread-specific initialization. We need to setup signal
237  // delivery for counters and timers from within the thread that
238  // will execute the event queue to ensure that signals are
239  // delivered to the right threads.
240  const BaseKvmCPUParams * const p(
241  dynamic_cast<const BaseKvmCPUParams *>(params()));
242 
243  vcpuThread = pthread_self();
244 
245  // Setup signal handlers. This has to be done after the vCPU is
246  // created since it manipulates the vCPU signal mask.
248 
249  setupCounters();
250 
251  if (p->usePerfOverflow)
252  runTimer.reset(new PerfKvmTimer(hwCycles,
254  p->hostFactor,
255  p->hostFreq));
256  else
257  runTimer.reset(new PosixKvmTimer(KVM_KICK_SIGNAL, CLOCK_MONOTONIC,
258  p->hostFactor,
259  p->hostFreq));
260 
261 }
262 
263 void
265 {
266  using namespace Stats;
267 
269 
270  numInsts
271  .name(name() + ".committedInsts")
272  .desc("Number of instructions committed")
273  ;
274 
275  numVMExits
276  .name(name() + ".numVMExits")
277  .desc("total number of KVM exits")
278  ;
279 
281  .name(name() + ".numVMHalfEntries")
282  .desc("number of KVM entries to finalize pending operations")
283  ;
284 
286  .name(name() + ".numExitSignal")
287  .desc("exits due to signal delivery")
288  ;
289 
290  numMMIO
291  .name(name() + ".numMMIO")
292  .desc("number of VM exits due to memory mapped IO")
293  ;
294 
296  .name(name() + ".numCoalescedMMIO")
297  .desc("number of coalesced memory mapped IO requests")
298  ;
299 
300  numIO
301  .name(name() + ".numIO")
302  .desc("number of VM exits due to legacy IO")
303  ;
304 
305  numHalt
306  .name(name() + ".numHalt")
307  .desc("number of VM exits due to wait for interrupt instructions")
308  ;
309 
311  .name(name() + ".numInterrupts")
312  .desc("number of interrupts delivered")
313  ;
314 
316  .name(name() + ".numHypercalls")
317  .desc("number of hypercalls")
318  ;
319 }
320 
321 void
323 {
324  if (DTRACE(Checkpoint)) {
325  DPRINTF(Checkpoint, "KVM: Serializing thread %i:\n", tid);
326  dump();
327  }
328 
329  assert(tid == 0);
330  assert(_status == Idle);
331  thread->serialize(cp);
332 }
333 
334 void
336 {
337  DPRINTF(Checkpoint, "KVM: Unserialize thread %i:\n", tid);
338 
339  assert(tid == 0);
340  assert(_status == Idle);
341  thread->unserialize(cp);
342  threadContextDirty = true;
343 }
344 
347 {
348  if (switchedOut())
349  return DrainState::Drained;
350 
351  DPRINTF(Drain, "BaseKvmCPU::drain\n");
352 
353  // The event queue won't be locked when calling drain since that's
354  // not done from an event. Lock the event queue here to make sure
355  // that scoped migrations continue to work if we need to
356  // synchronize the thread context.
357  std::lock_guard<EventQueue> lock(*this->eventQueue());
358 
359  switch (_status) {
360  case Running:
361  // The base KVM code is normally ready when it is in the
362  // Running state, but the architecture specific code might be
363  // of a different opinion. This may happen when the CPU been
364  // notified of an event that hasn't been accepted by the vCPU
365  // yet.
366  if (!archIsDrained())
367  return DrainState::Draining;
368 
369  // The state of the CPU is consistent, so we don't need to do
370  // anything special to drain it. We simply de-schedule the
371  // tick event and enter the Idle state to prevent nasty things
372  // like MMIOs from happening.
373  if (tickEvent.scheduled())
375  _status = Idle;
376 
378  case Idle:
379  // Idle, no need to drain
380  assert(!tickEvent.scheduled());
381 
382  // Sync the thread context here since we'll need it when we
383  // switch CPUs or checkpoint the CPU.
385 
386  return DrainState::Drained;
387 
389  // The CPU has just requested a service that was handled in
390  // the RunningService state, but the results have still not
391  // been reported to the CPU. Now, we /could/ probably just
392  // update the register state ourselves instead of letting KVM
393  // handle it, but that would be tricky. Instead, we enter KVM
394  // and let it do its stuff.
395  DPRINTF(Drain, "KVM CPU is waiting for service completion, "
396  "requesting drain.\n");
397  return DrainState::Draining;
398 
399  case RunningMMIOPending:
400  // We need to drain since there are in-flight timing accesses
401  DPRINTF(Drain, "KVM CPU is waiting for timing accesses to complete, "
402  "requesting drain.\n");
403  return DrainState::Draining;
404 
405  case RunningService:
406  // We need to drain since the CPU is waiting for service (e.g., MMIOs)
407  DPRINTF(Drain, "KVM CPU is waiting for service, requesting drain.\n");
408  return DrainState::Draining;
409 
410  default:
411  panic("KVM: Unhandled CPU state in drain()\n");
412  return DrainState::Drained;
413  }
414 }
415 
416 void
418 {
419  assert(!tickEvent.scheduled());
420 
421  // We might have been switched out. In that case, we don't need to
422  // do anything.
423  if (switchedOut())
424  return;
425 
426  DPRINTF(Kvm, "drainResume\n");
428 
429  // The tick event is de-scheduled as a part of the draining
430  // process. Re-schedule it if the thread context is active.
431  if (tc->status() == ThreadContext::Active) {
433  _status = Running;
434  } else {
435  _status = Idle;
436  }
437 }
438 
439 void
441 {
442  // We should have drained prior to forking, which means that the
443  // tick event shouldn't be scheduled and the CPU is idle.
444  assert(!tickEvent.scheduled());
445  assert(_status == Idle);
446 
447  if (vcpuFD != -1) {
448  if (close(vcpuFD) == -1)
449  warn("kvm CPU: notifyFork failed to close vcpuFD\n");
450 
451  if (_kvmRun)
452  munmap(_kvmRun, vcpuMMapSize);
453 
454  vcpuFD = -1;
455  _kvmRun = NULL;
456 
458  hwCycles.detach();
459  }
460 }
461 
462 void
464 {
465  DPRINTF(Kvm, "switchOut\n");
466 
468 
469  // We should have drained prior to executing a switchOut, which
470  // means that the tick event shouldn't be scheduled and the CPU is
471  // idle.
472  assert(!tickEvent.scheduled());
473  assert(_status == Idle);
474 }
475 
476 void
478 {
479  DPRINTF(Kvm, "takeOverFrom\n");
480 
482 
483  // We should have drained prior to executing a switchOut, which
484  // means that the tick event shouldn't be scheduled and the CPU is
485  // idle.
486  assert(!tickEvent.scheduled());
487  assert(_status == Idle);
488  assert(threadContexts.size() == 1);
489 
490  // Force an update of the KVM state here instead of flagging the
491  // TC as dirty. This is not ideal from a performance point of
492  // view, but it makes debugging easier as it allows meaningful KVM
493  // state to be dumped before and after a takeover.
494  updateKvmState();
495  threadContextDirty = false;
496 }
497 
498 void
500 {
501  if (!(system->bypassCaches())) {
502  fatal("The KVM-based CPUs requires the memory system to be in the "
503  "'noncaching' mode.\n");
504  }
505 }
506 
507 void
509 {
510  DPRINTF(Kvm, "wakeup()\n");
511  // This method might have been called from another
512  // context. Migrate to this SimObject's event queue when
513  // delivering the wakeup signal.
515 
516  // Kick the vCPU to get it to come out of KVM.
517  kick();
518 
520  return;
521 
522  thread->activate();
523 }
524 
525 void
527 {
528  DPRINTF(Kvm, "ActivateContext %d\n", thread_num);
529 
530  assert(thread_num == 0);
531  assert(thread);
532 
533  assert(_status == Idle);
534  assert(!tickEvent.scheduled());
535 
537 
539  _status = Running;
540 }
541 
542 
543 void
545 {
546  DPRINTF(Kvm, "SuspendContext %d\n", thread_num);
547 
548  assert(thread_num == 0);
549  assert(thread);
550 
551  if (_status == Idle)
552  return;
553 
555 
556  // The tick event may no be scheduled if the quest has requested
557  // the monitor to wait for interrupts. The normal CPU models can
558  // get their tick events descheduled by quiesce instructions, but
559  // that can't happen here.
560  if (tickEvent.scheduled())
562 
563  _status = Idle;
564 }
565 
566 void
568 {
569  // for now, these are equivalent
570  suspendContext(thread_num);
571 }
572 
573 void
575 {
576  // for now, these are equivalent
577  suspendContext(thread_num);
579 }
580 
583 {
584  assert(tn == 0);
586  return tc;
587 }
588 
589 
590 Counter
592 {
593  return ctrInsts;
594 }
595 
596 Counter
598 {
599  hack_once("Pretending totalOps is equivalent to totalInsts()\n");
600  return ctrInsts;
601 }
602 
603 void
605 {
606  inform("State dumping not implemented.");
607 }
608 
609 void
611 {
612  Tick delay(0);
613  assert(_status != Idle && _status != RunningMMIOPending);
614 
615  switch (_status) {
616  case RunningService:
617  // handleKvmExit() will determine the next state of the CPU
618  delay = handleKvmExit();
619 
620  if (tryDrain())
621  _status = Idle;
622  break;
623 
625  case Running: {
626  auto &queue = thread->comInstEventQueue;
627  const uint64_t nextInstEvent(
628  queue.empty() ? MaxTick : queue.nextTick());
629  // Enter into KVM and complete pending IO instructions if we
630  // have an instruction event pending.
631  const Tick ticksToExecute(
632  nextInstEvent > ctrInsts ?
633  curEventQueue()->nextTick() - curTick() : 0);
634 
635  if (alwaysSyncTC)
636  threadContextDirty = true;
637 
638  // We might need to update the KVM state.
639  syncKvmState();
640 
641  // Setup any pending instruction count breakpoints using
642  // PerfEvent if we are going to execute more than just an IO
643  // completion.
644  if (ticksToExecute > 0)
645  setupInstStop();
646 
647  DPRINTF(KvmRun, "Entering KVM...\n");
648  if (drainState() == DrainState::Draining) {
649  // Force an immediate exit from KVM after completing
650  // pending operations. The architecture-specific code
651  // takes care to run until it is in a state where it can
652  // safely be drained.
653  delay = kvmRunDrain();
654  } else {
655  delay = kvmRun(ticksToExecute);
656  }
657 
658  // The CPU might have been suspended before entering into
659  // KVM. Assume that the CPU was suspended /before/ entering
660  // into KVM and skip the exit handling.
661  if (_status == Idle)
662  break;
663 
664  // Entering into KVM implies that we'll have to reload the thread
665  // context from KVM if we want to access it. Flag the KVM state as
666  // dirty with respect to the cached thread context.
667  kvmStateDirty = true;
668 
669  if (alwaysSyncTC)
671 
672  // Enter into the RunningService state unless the
673  // simulation was stopped by a timer.
674  if (_kvmRun->exit_reason != KVM_EXIT_INTR) {
676  } else {
677  ++numExitSignal;
678  _status = Running;
679  }
680 
681  // Service any pending instruction events. The vCPU should
682  // have exited in time for the event using the instruction
683  // counter configured by setupInstStop().
684  queue.serviceEvents(ctrInsts);
685 
686  if (tryDrain())
687  _status = Idle;
688  } break;
689 
690  default:
691  panic("BaseKvmCPU entered tick() in an illegal state (%i)\n",
692  _status);
693  }
694 
695  // Schedule a new tick if we are still running
696  if (_status != Idle && _status != RunningMMIOPending)
698 }
699 
700 Tick
702 {
703  // By default, the only thing we need to drain is a pending IO
704  // operation which assumes that we are in the
705  // RunningServiceCompletion or RunningMMIOPending state.
706  assert(_status == RunningServiceCompletion ||
708 
709  // Deliver the data from the pending IO operation and immediately
710  // exit.
711  return kvmRun(0);
712 }
713 
714 uint64_t
716 {
717  return hwCycles.read();
718 }
719 
720 Tick
722 {
723  Tick ticksExecuted;
724  fatal_if(vcpuFD == -1,
725  "Trying to run a KVM CPU in a forked child process. "
726  "This is not supported.\n");
727  DPRINTF(KvmRun, "KVM: Executing for %i ticks\n", ticks);
728 
729  if (ticks == 0) {
730  // Settings ticks == 0 is a special case which causes an entry
731  // into KVM that finishes pending operations (e.g., IO) and
732  // then immediately exits.
733  DPRINTF(KvmRun, "KVM: Delivering IO without full guest entry\n");
734 
736 
737  // Send a KVM_KICK_SIGNAL to the vCPU thread (i.e., this
738  // thread). The KVM control signal is masked while executing
739  // in gem5 and gets unmasked temporarily as when entering
740  // KVM. See setSignalMask() and setupSignalHandler().
741  kick();
742 
743  // Start the vCPU. KVM will check for signals after completing
744  // pending operations (IO). Since the KVM_KICK_SIGNAL is
745  // pending, this forces an immediate exit to gem5 again. We
746  // don't bother to setup timers since this shouldn't actually
747  // execute any code (other than completing half-executed IO
748  // instructions) in the guest.
749  ioctlRun();
750 
751  // We always execute at least one cycle to prevent the
752  // BaseKvmCPU::tick() to be rescheduled on the same tick
753  // twice.
754  ticksExecuted = clockPeriod();
755  } else {
756  // This method is executed as a result of a tick event. That
757  // means that the event queue will be locked when entering the
758  // method. We temporarily unlock the event queue to allow
759  // other threads to steal control of this thread to inject
760  // interrupts. They will typically lock the queue and then
761  // force an exit from KVM by kicking the vCPU.
763 
764  if (ticks < runTimer->resolution()) {
765  DPRINTF(KvmRun, "KVM: Adjusting tick count (%i -> %i)\n",
766  ticks, runTimer->resolution());
767  ticks = runTimer->resolution();
768  }
769 
770  // Get hardware statistics after synchronizing contexts. The KVM
771  // state update might affect guest cycle counters.
772  uint64_t baseCycles(getHostCycles());
773  uint64_t baseInstrs(hwInstructions.read());
774 
775  // Arm the run timer and start the cycle timer if it isn't
776  // controlled by the overflow timer. Starting/stopping the cycle
777  // timer automatically starts the other perf timers as they are in
778  // the same counter group.
779  runTimer->arm(ticks);
781  hwCycles.start();
782 
783  ioctlRun();
784 
785  runTimer->disarm();
787  hwCycles.stop();
788 
789  // The control signal may have been delivered after we exited
790  // from KVM. It will be pending in that case since it is
791  // masked when we aren't executing in KVM. Discard it to make
792  // sure we don't deliver it immediately next time we try to
793  // enter into KVM.
795 
796  const uint64_t hostCyclesExecuted(getHostCycles() - baseCycles);
797  const uint64_t simCyclesExecuted(hostCyclesExecuted * hostFactor);
798  const uint64_t instsExecuted(hwInstructions.read() - baseInstrs);
799  ticksExecuted = runTimer->ticksFromHostCycles(hostCyclesExecuted);
800 
801  /* Update statistics */
802  numCycles += simCyclesExecuted;;
803  numInsts += instsExecuted;
804  ctrInsts += instsExecuted;
805  system->totalNumInsts += instsExecuted;
806 
807  DPRINTF(KvmRun,
808  "KVM: Executed %i instructions in %i cycles "
809  "(%i ticks, sim cycles: %i).\n",
810  instsExecuted, hostCyclesExecuted, ticksExecuted, simCyclesExecuted);
811  }
812 
813  ++numVMExits;
814 
815  return ticksExecuted + flushCoalescedMMIO();
816 }
817 
818 void
820 {
821  ++numInterrupts;
822  if (ioctl(KVM_NMI) == -1)
823  panic("KVM: Failed to deliver NMI to virtual CPU\n");
824 }
825 
826 void
827 BaseKvmCPU::kvmInterrupt(const struct kvm_interrupt &interrupt)
828 {
829  ++numInterrupts;
830  if (ioctl(KVM_INTERRUPT, (void *)&interrupt) == -1)
831  panic("KVM: Failed to deliver interrupt to virtual CPU\n");
832 }
833 
834 void
835 BaseKvmCPU::getRegisters(struct kvm_regs &regs) const
836 {
837  if (ioctl(KVM_GET_REGS, &regs) == -1)
838  panic("KVM: Failed to get guest registers\n");
839 }
840 
841 void
842 BaseKvmCPU::setRegisters(const struct kvm_regs &regs)
843 {
844  if (ioctl(KVM_SET_REGS, (void *)&regs) == -1)
845  panic("KVM: Failed to set guest registers\n");
846 }
847 
848 void
849 BaseKvmCPU::getSpecialRegisters(struct kvm_sregs &regs) const
850 {
851  if (ioctl(KVM_GET_SREGS, &regs) == -1)
852  panic("KVM: Failed to get guest special registers\n");
853 }
854 
855 void
856 BaseKvmCPU::setSpecialRegisters(const struct kvm_sregs &regs)
857 {
858  if (ioctl(KVM_SET_SREGS, (void *)&regs) == -1)
859  panic("KVM: Failed to set guest special registers\n");
860 }
861 
862 void
863 BaseKvmCPU::getFPUState(struct kvm_fpu &state) const
864 {
865  if (ioctl(KVM_GET_FPU, &state) == -1)
866  panic("KVM: Failed to get guest FPU state\n");
867 }
868 
869 void
870 BaseKvmCPU::setFPUState(const struct kvm_fpu &state)
871 {
872  if (ioctl(KVM_SET_FPU, (void *)&state) == -1)
873  panic("KVM: Failed to set guest FPU state\n");
874 }
875 
876 
877 void
878 BaseKvmCPU::setOneReg(uint64_t id, const void *addr)
879 {
880 #ifdef KVM_SET_ONE_REG
881  struct kvm_one_reg reg;
882  reg.id = id;
883  reg.addr = (uint64_t)addr;
884 
885  if (ioctl(KVM_SET_ONE_REG, &reg) == -1) {
886  panic("KVM: Failed to set register (0x%x) value (errno: %i)\n",
887  id, errno);
888  }
889 #else
890  panic("KVM_SET_ONE_REG is unsupported on this platform.\n");
891 #endif
892 }
893 
894 void
895 BaseKvmCPU::getOneReg(uint64_t id, void *addr) const
896 {
897 #ifdef KVM_GET_ONE_REG
898  struct kvm_one_reg reg;
899  reg.id = id;
900  reg.addr = (uint64_t)addr;
901 
902  if (ioctl(KVM_GET_ONE_REG, &reg) == -1) {
903  panic("KVM: Failed to get register (0x%x) value (errno: %i)\n",
904  id, errno);
905  }
906 #else
907  panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
908 #endif
909 }
910 
911 std::string
913 {
914 #ifdef KVM_GET_ONE_REG
915  std::ostringstream ss;
916 
917  ss.setf(std::ios::hex, std::ios::basefield);
918  ss.setf(std::ios::showbase);
919 #define HANDLE_INTTYPE(len) \
920  case KVM_REG_SIZE_U ## len: { \
921  uint ## len ## _t value; \
922  getOneReg(id, &value); \
923  ss << value; \
924  } break
925 
926 #define HANDLE_ARRAY(len) \
927  case KVM_REG_SIZE_U ## len: { \
928  uint8_t value[len / 8]; \
929  getOneReg(id, value); \
930  ccprintf(ss, "[0x%x", value[0]); \
931  for (int i = 1; i < len / 8; ++i) \
932  ccprintf(ss, ", 0x%x", value[i]); \
933  ccprintf(ss, "]"); \
934  } break
935 
936  switch (id & KVM_REG_SIZE_MASK) {
937  HANDLE_INTTYPE(8);
938  HANDLE_INTTYPE(16);
939  HANDLE_INTTYPE(32);
940  HANDLE_INTTYPE(64);
941  HANDLE_ARRAY(128);
942  HANDLE_ARRAY(256);
943  HANDLE_ARRAY(512);
944  HANDLE_ARRAY(1024);
945  default:
946  ss << "??";
947  }
948 
949 #undef HANDLE_INTTYPE
950 #undef HANDLE_ARRAY
951 
952  return ss.str();
953 #else
954  panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
955 #endif
956 }
957 
958 void
960 {
961  if (!kvmStateDirty)
962  return;
963 
964  assert(!threadContextDirty);
965 
967  kvmStateDirty = false;
968 }
969 
970 void
972 {
973  if (!threadContextDirty)
974  return;
975 
976  assert(!kvmStateDirty);
977 
978  updateKvmState();
979  threadContextDirty = false;
980 }
981 
982 Tick
984 {
985  DPRINTF(KvmRun, "handleKvmExit (exit_reason: %i)\n", _kvmRun->exit_reason);
986  assert(_status == RunningService);
987 
988  // Switch into the running state by default. Individual handlers
989  // can override this.
990  _status = Running;
991  switch (_kvmRun->exit_reason) {
992  case KVM_EXIT_UNKNOWN:
993  return handleKvmExitUnknown();
994 
995  case KVM_EXIT_EXCEPTION:
996  return handleKvmExitException();
997 
998  case KVM_EXIT_IO:
999  {
1000  ++numIO;
1001  Tick ticks = handleKvmExitIO();
1003  return ticks;
1004  }
1005 
1006  case KVM_EXIT_HYPERCALL:
1007  ++numHypercalls;
1008  return handleKvmExitHypercall();
1009 
1010  case KVM_EXIT_HLT:
1011  /* The guest has halted and is waiting for interrupts */
1012  DPRINTF(Kvm, "handleKvmExitHalt\n");
1013  ++numHalt;
1014 
1015  // Suspend the thread until the next interrupt arrives
1016  thread->suspend();
1017 
1018  // This is actually ignored since the thread is suspended.
1019  return 0;
1020 
1021  case KVM_EXIT_MMIO:
1022  {
1023  /* Service memory mapped IO requests */
1024  DPRINTF(KvmIO, "KVM: Handling MMIO (w: %u, addr: 0x%x, len: %u)\n",
1025  _kvmRun->mmio.is_write,
1026  _kvmRun->mmio.phys_addr, _kvmRun->mmio.len);
1027 
1028  ++numMMIO;
1029  Tick ticks = doMMIOAccess(_kvmRun->mmio.phys_addr, _kvmRun->mmio.data,
1030  _kvmRun->mmio.len, _kvmRun->mmio.is_write);
1031  // doMMIOAccess could have triggered a suspend, in which case we don't
1032  // want to overwrite the _status.
1033  if (_status != Idle)
1035  return ticks;
1036  }
1037 
1038  case KVM_EXIT_IRQ_WINDOW_OPEN:
1039  return handleKvmExitIRQWindowOpen();
1040 
1041  case KVM_EXIT_FAIL_ENTRY:
1042  return handleKvmExitFailEntry();
1043 
1044  case KVM_EXIT_INTR:
1045  /* KVM was interrupted by a signal, restart it in the next
1046  * tick. */
1047  return 0;
1048 
1049  case KVM_EXIT_INTERNAL_ERROR:
1050  panic("KVM: Internal error (suberror: %u)\n",
1051  _kvmRun->internal.suberror);
1052 
1053  default:
1054  dump();
1055  panic("KVM: Unexpected exit (exit_reason: %u)\n", _kvmRun->exit_reason);
1056  }
1057 }
1058 
1059 Tick
1061 {
1062  panic("KVM: Unhandled guest IO (dir: %i, size: %i, port: 0x%x, count: %i)\n",
1063  _kvmRun->io.direction, _kvmRun->io.size,
1064  _kvmRun->io.port, _kvmRun->io.count);
1065 }
1066 
1067 Tick
1069 {
1070  panic("KVM: Unhandled hypercall\n");
1071 }
1072 
1073 Tick
1075 {
1076  warn("KVM: Unhandled IRQ window.\n");
1077  return 0;
1078 }
1079 
1080 
1081 Tick
1083 {
1084  dump();
1085  panic("KVM: Unknown error when starting vCPU (hw reason: 0x%llx)\n",
1086  _kvmRun->hw.hardware_exit_reason);
1087 }
1088 
1089 Tick
1091 {
1092  dump();
1093  panic("KVM: Got exception when starting vCPU "
1094  "(exception: %u, error_code: %u)\n",
1095  _kvmRun->ex.exception, _kvmRun->ex.error_code);
1096 }
1097 
1098 Tick
1100 {
1101  dump();
1102  panic("KVM: Failed to enter virtualized mode (hw reason: 0x%llx)\n",
1103  _kvmRun->fail_entry.hardware_entry_failure_reason);
1104 }
1105 
1106 Tick
1107 BaseKvmCPU::doMMIOAccess(Addr paddr, void *data, int size, bool write)
1108 {
1111 
1112  RequestPtr mmio_req = std::make_shared<Request>(
1113  paddr, size, Request::UNCACHEABLE, dataMasterId());
1114 
1115  mmio_req->setContext(tc->contextId());
1116  // Some architectures do need to massage physical addresses a bit
1117  // before they are inserted into the memory system. This enables
1118  // APIC accesses on x86 and m5ops where supported through a MMIO
1119  // interface.
1120  BaseTLB::Mode tlb_mode(write ? BaseTLB::Write : BaseTLB::Read);
1121  Fault fault(tc->getDTBPtr()->finalizePhysical(mmio_req, tc, tlb_mode));
1122  if (fault != NoFault)
1123  warn("Finalization of MMIO address failed: %s\n", fault->name());
1124 
1125 
1126  const MemCmd cmd(write ? MemCmd::WriteReq : MemCmd::ReadReq);
1127  PacketPtr pkt = new Packet(mmio_req, cmd);
1128  pkt->dataStatic(data);
1129 
1130  if (mmio_req->isLocalAccess()) {
1131  // We currently assume that there is no need to migrate to a
1132  // different event queue when doing local accesses. Currently, they
1133  // are only used for m5ops, so it should be a valid assumption.
1134  const Cycles ipr_delay = mmio_req->localAccessor(tc, pkt);
1135  threadContextDirty = true;
1136  delete pkt;
1137  return clockPeriod() * ipr_delay;
1138  } else {
1139  // Temporarily lock and migrate to the device event queue to
1140  // prevent races in multi-core mode.
1142 
1143  return dataPort.submitIO(pkt);
1144  }
1145 }
1146 
1147 void
1149 {
1150  std::unique_ptr<struct kvm_signal_mask> kvm_mask;
1151 
1152  if (mask) {
1153  kvm_mask.reset((struct kvm_signal_mask *)operator new(
1154  sizeof(struct kvm_signal_mask) + sizeof(*mask)));
1155  // The kernel and the user-space headers have different ideas
1156  // about the size of sigset_t. This seems like a massive hack,
1157  // but is actually what qemu does.
1158  assert(sizeof(*mask) >= 8);
1159  kvm_mask->len = 8;
1160  memcpy(kvm_mask->sigset, mask, kvm_mask->len);
1161  }
1162 
1163  if (ioctl(KVM_SET_SIGNAL_MASK, (void *)kvm_mask.get()) == -1)
1164  panic("KVM: Failed to set vCPU signal mask (errno: %i)\n",
1165  errno);
1166 }
1167 
1168 int
1169 BaseKvmCPU::ioctl(int request, long p1) const
1170 {
1171  if (vcpuFD == -1)
1172  panic("KVM: CPU ioctl called before initialization\n");
1173 
1174  return ::ioctl(vcpuFD, request, p1);
1175 }
1176 
1177 Tick
1179 {
1180  if (!mmioRing)
1181  return 0;
1182 
1183  DPRINTF(KvmIO, "KVM: Flushing the coalesced MMIO ring buffer\n");
1184 
1185  // TODO: We might need to do synchronization when we start to
1186  // support multiple CPUs
1187  Tick ticks(0);
1188  while (mmioRing->first != mmioRing->last) {
1189  struct kvm_coalesced_mmio &ent(
1190  mmioRing->coalesced_mmio[mmioRing->first]);
1191 
1192  DPRINTF(KvmIO, "KVM: Handling coalesced MMIO (addr: 0x%x, len: %u)\n",
1193  ent.phys_addr, ent.len);
1194 
1195  ++numCoalescedMMIO;
1196  ticks += doMMIOAccess(ent.phys_addr, ent.data, ent.len, true);
1197 
1198  mmioRing->first = (mmioRing->first + 1) % KVM_COALESCED_MMIO_MAX;
1199  }
1200 
1201  return ticks;
1202 }
1203 
1214 static void
1215 onKickSignal(int signo, siginfo_t *si, void *data)
1216 {
1217 }
1218 
1219 void
1221 {
1222  struct sigaction sa;
1223 
1224  memset(&sa, 0, sizeof(sa));
1225  sa.sa_sigaction = onKickSignal;
1226  sa.sa_flags = SA_SIGINFO | SA_RESTART;
1227  if (sigaction(KVM_KICK_SIGNAL, &sa, NULL) == -1)
1228  panic("KVM: Failed to setup vCPU timer signal handler\n");
1229 
1230  sigset_t sigset;
1231  if (pthread_sigmask(SIG_BLOCK, NULL, &sigset) == -1)
1232  panic("KVM: Failed get signal mask\n");
1233 
1234  // Request KVM to setup the same signal mask as we're currently
1235  // running with except for the KVM control signal. We'll sometimes
1236  // need to raise the KVM_KICK_SIGNAL to cause immediate exits from
1237  // KVM after servicing IO requests. See kvmRun().
1238  sigdelset(&sigset, KVM_KICK_SIGNAL);
1239  setSignalMask(&sigset);
1240 
1241  // Mask our control signals so they aren't delivered unless we're
1242  // actually executing inside KVM.
1243  sigaddset(&sigset, KVM_KICK_SIGNAL);
1244  if (pthread_sigmask(SIG_SETMASK, &sigset, NULL) == -1)
1245  panic("KVM: Failed mask the KVM control signals\n");
1246 }
1247 
1248 bool
1250 {
1251  int discardedSignal;
1252 
1253  // Setting the timeout to zero causes sigtimedwait to return
1254  // immediately.
1255  struct timespec timeout;
1256  timeout.tv_sec = 0;
1257  timeout.tv_nsec = 0;
1258 
1259  sigset_t sigset;
1260  sigemptyset(&sigset);
1261  sigaddset(&sigset, signum);
1262 
1263  do {
1264  discardedSignal = sigtimedwait(&sigset, NULL, &timeout);
1265  } while (discardedSignal == -1 && errno == EINTR);
1266 
1267  if (discardedSignal == signum)
1268  return true;
1269  else if (discardedSignal == -1 && errno == EAGAIN)
1270  return false;
1271  else
1272  panic("Unexpected return value from sigtimedwait: %i (errno: %i)\n",
1273  discardedSignal, errno);
1274 }
1275 
1276 void
1278 {
1279  DPRINTF(Kvm, "Attaching cycle counter...\n");
1280  PerfKvmCounterConfig cfgCycles(PERF_TYPE_HARDWARE,
1281  PERF_COUNT_HW_CPU_CYCLES);
1282  cfgCycles.disabled(true)
1283  .pinned(true);
1284 
1285  // Try to exclude the host. We set both exclude_hv and
1286  // exclude_host since different architectures use slightly
1287  // different APIs in the kernel.
1288  cfgCycles.exclude_hv(true)
1289  .exclude_host(true);
1290 
1291  if (perfControlledByTimer) {
1292  // We need to configure the cycles counter to send overflows
1293  // since we are going to use it to trigger timer signals that
1294  // trap back into m5 from KVM. In practice, this means that we
1295  // need to set some non-zero sample period that gets
1296  // overridden when the timer is armed.
1297  cfgCycles.wakeupEvents(1)
1298  .samplePeriod(42);
1299  }
1300 
1301  hwCycles.attach(cfgCycles,
1302  0); // TID (0 => currentThread)
1303 
1304  setupInstCounter();
1305 }
1306 
1307 bool
1309 {
1311  return false;
1312 
1313  if (!archIsDrained()) {
1314  DPRINTF(Drain, "tryDrain: Architecture code is not ready.\n");
1315  return false;
1316  }
1317 
1318  if (_status == Idle || _status == Running) {
1319  DPRINTF(Drain,
1320  "tryDrain: CPU transitioned into the Idle state, drain done\n");
1321  signalDrainDone();
1322  return true;
1323  } else {
1324  DPRINTF(Drain, "tryDrain: CPU not ready.\n");
1325  return false;
1326  }
1327 }
1328 
1329 void
1331 {
1332  if (ioctl(KVM_RUN) == -1) {
1333  if (errno != EINTR)
1334  panic("KVM: Failed to start virtual CPU (errno: %i)\n",
1335  errno);
1336  }
1337 }
1338 
1339 void
1341 {
1342  if (thread->comInstEventQueue.empty()) {
1343  setupInstCounter(0);
1344  } else {
1346  assert(next > ctrInsts);
1347  setupInstCounter(next - ctrInsts);
1348  }
1349 }
1350 
1351 void
1353 {
1354  // No need to do anything if we aren't attaching for the first
1355  // time or the period isn't changing.
1356  if (period == activeInstPeriod && hwInstructions.attached())
1357  return;
1358 
1359  PerfKvmCounterConfig cfgInstructions(PERF_TYPE_HARDWARE,
1360  PERF_COUNT_HW_INSTRUCTIONS);
1361 
1362  // Try to exclude the host. We set both exclude_hv and
1363  // exclude_host since different architectures use slightly
1364  // different APIs in the kernel.
1365  cfgInstructions.exclude_hv(true)
1366  .exclude_host(true);
1367 
1368  if (period) {
1369  // Setup a sampling counter if that has been requested.
1370  cfgInstructions.wakeupEvents(1)
1371  .samplePeriod(period);
1372  }
1373 
1374  // We need to detach and re-attach the counter to reliably change
1375  // sampling settings. See PerfKvmCounter::period() for details.
1376  if (hwInstructions.attached())
1378  assert(hwCycles.attached());
1379  hwInstructions.attach(cfgInstructions,
1380  0, // TID (0 => currentThread)
1381  hwCycles);
1382 
1383  if (period)
1385 
1386  activeInstPeriod = period;
1387 }
#define panic(...)
This implements a cprintf based panic() function.
Definition: logging.hh:163
void detach()
Detach a counter from PerfEvent.
Definition: perfevent.cc:93
void tick()
Execute the CPU until the next event in the main event queue or until the guest needs service from ge...
Definition: base.cc:610
#define DPRINTF(x,...)
Definition: trace.hh:225
void unserialize(CheckpointIn &cp) override
Unserialize an object.
void setupCounters()
Setup hardware performance counters.
Definition: base.cc:1277
EventQueue * deviceEventQueue()
Get a pointer to the event queue owning devices.
Definition: base.hh:428
PerfKvmCounterConfig & pinned(bool val)
Force the group to be on the active all the time (i.e., disallow multiplexing).
Definition: perfevent.hh:123
void finishMMIOPending()
Callback from KvmCPUPort to transition the CPU out of RunningMMIOPending when all timing requests hav...
Definition: base.cc:224
Counter ctrInsts
Number of instructions executed by the CPU.
Definition: base.hh:798
void suspend() override
Set the status to Suspended.
Status status() const override
decltype(nullptr) constexpr NoFault
Definition: types.hh:243
Cycles is a wrapper class for representing cycle counts, i.e.
Definition: types.hh:81
#define fatal(...)
This implements a cprintf based fatal() function.
Definition: logging.hh:171
uint64_t activeInstPeriod
Currently active instruction count breakpoint.
Definition: base.hh:737
Timing MMIO request in flight or stalled.
Definition: base.hh:217
Definition: packet.hh:70
Tick lastActivate
Last time activate was called on this thread.
const std::string & name()
Definition: trace.cc:50
bool empty() const
Returns true if no events are queued.
Definition: eventq.hh:823
virtual void updateThreadContext()=0
Update the current thread context with the KVM state.
virtual Tick handleKvmExitIO()
The guest performed a legacy IO request (out/inp on x86)
Definition: base.cc:1060
ThreadID numThreads
Number of threads we&#39;re actually simulating (<= SMT_MAX_THREADS).
Definition: base.hh:374
bool recvTimingResp(PacketPtr pkt) override
Receive a timing response from the peer.
Definition: base.cc:191
Tick submitIO(PacketPtr pkt)
Interface to send Atomic or Timing IO request.
Definition: base.cc:173
virtual BaseTLB * getDTBPtr()=0
bool threadContextDirty
Is the gem5 context dirty? Set to true to force an update of the KVM vCPU state upon the next call to...
Definition: base.hh:627
bool perfControlledByTimer
Does the runTimer control the performance counters?
Definition: base.hh:769
void getSpecialRegisters(struct kvm_sregs &regs) const
Definition: base.cc:849
virtual ~BaseKvmCPU()
Definition: base.cc:98
void notifyFork() override
Notify a child process of a fork.
Definition: base.cc:440
std::shared_ptr< Request > RequestPtr
Definition: request.hh:81
virtual Tick kvmRun(Tick ticks)
Request KVM to run the guest for a given number of ticks.
Definition: base.cc:721
void cpuStartup()
VM CPU initialization code.
Definition: vm.cc:332
Tick lastSuspend
Last time suspend was called on this thread.
ip6_addr_t addr
Definition: inet.hh:330
std::unique_ptr< BaseKvmTimer > runTimer
Timer used to force execution into the monitor after a specified number of simulation tick equivalent...
Definition: base.hh:778
ThreadContext * tc
ThreadContext object, provides an interface for external objects to modify this thread&#39;s state...
Definition: base.hh:149
void kvmNonMaskableInterrupt()
Send a non-maskable interrupt to the guest.
Definition: base.cc:819
Stats::Scalar numHalt
Definition: base.hh:792
void enableSignals(pid_t tid, int signal)
Enable signal delivery to a thread on counter overflow.
Definition: perfevent.cc:144
virtual Tick handleKvmExitIRQWindowOpen()
The guest exited because an interrupt window was requested.
Definition: base.cc:1074
bool FullSystem
The FullSystem variable can be used to determine the current mode of simulation.
Definition: root.cc:132
void verifyMemoryMode() const override
Verify that the system is in a memory mode supported by the CPU.
Definition: base.cc:499
bool switchedOut() const
Determine if the CPU is switched out.
Definition: base.hh:363
void wakeup(ThreadID tid=0) override
Definition: base.cc:508
The SimpleThread object provides a combination of the ThreadState object and the ThreadContext interf...
void setStatus(Status newStatus) override
virtual void dump() const
Dump the internal state to the terminal.
Definition: base.cc:604
float hostFactor
Host factor as specified in the configuration.
Definition: base.hh:781
bool tryDrain()
Try to drain the CPU if a drain is pending.
Definition: base.cc:1308
void getFPUState(struct kvm_fpu &state) const
Get/Set the guest FPU/vector state.
Definition: base.cc:863
Counter totalInsts() const override
Definition: base.cc:591
System * system
Definition: base.hh:382
Stats::Scalar numExitSignal
Definition: base.hh:788
virtual Tick kvmRunDrain()
Request the CPU to run until draining completes.
Definition: base.cc:701
int createVCPU(long vcpuID)
Create a new vCPU within a VM.
Definition: vm.cc:546
Definition: cprintf.cc:40
Tick flushCoalescedMMIO()
Service MMIO requests in the mmioRing.
Definition: base.cc:1178
DrainState drain() override
Notify an object that it needs to drain its state.
Definition: base.cc:346
Tick clockPeriod() const
void init() override
init() is called after all C++ SimObjects have been created and all ports are connected.
Definition: base.cc:106
ThreadContext is the external interface to all thread state for anything outside of the CPU...
The request is to an uncacheable address.
Definition: request.hh:113
DrainState
Object drain/handover states.
Definition: drain.hh:71
const long vcpuID
KVM internal ID of the vCPU.
Definition: base.hh:636
Bitfield< 33 > id
void dataStatic(T *p)
Set the data pointer to the following value that should not be freed.
Definition: packet.hh:1034
void recvReqRetry() override
Called by the peer if sendTimingReq was called on this peer (causing recvTimingReq to be called on th...
Definition: base.cc:208
Bitfield< 15, 0 > si
Definition: types.hh:53
virtual void updateKvmState()=0
Update the KVM state from the current thread context.
void regStats() override
Callback to set stat parameters.
Definition: base.cc:264
Stats::Scalar numInsts
Definition: base.hh:785
void regStats() override
Callback to set stat parameters.
Definition: base.cc:384
DrainState drainState() const
Return the current drain state of an object.
Definition: drain.hh:308
void activateContext(ThreadID thread_num) override
Notify the CPU that the indicated context is now active.
Definition: base.cc:526
Stats::Scalar numInterrupts
Definition: base.hh:793
std::vector< ThreadContext * > threadContexts
Definition: base.hh:263
#define KVM_KICK_SIGNAL
Signal to use to trigger exits from KVM.
Definition: base.hh:56
PerfKvmCounterConfig & wakeupEvents(uint32_t events)
Set the number of samples that need to be triggered before reporting data as being available on the p...
Definition: perfevent.hh:98
void setSpecialRegisters(const struct kvm_sregs &regs)
Definition: base.cc:856
#define inform(...)
Definition: logging.hh:209
const Tick MaxTick
Definition: types.hh:63
Draining buffers pending serialization/handover.
void serializeThread(CheckpointOut &cp, ThreadID tid) const override
Serialize a single thread.
Definition: base.cc:322
Stats::Scalar numIO
Definition: base.hh:791
void setupSignalHandler()
Setup a signal handler to catch the timer signal used to switch back to the monitor.
Definition: base.cc:1220
Tick curTick()
The current simulated tick.
Definition: core.hh:44
Temporarily migrate execution to a different event queue.
Definition: eventq.hh:673
int vcpuMMapSize
Size of MMAPed kvm_run area.
Definition: base.hh:688
#define DTRACE(x)
Definition: trace.hh:223
virtual Tick handleKvmExitFailEntry()
KVM failed to start the virtualized CPU.
Definition: base.cc:1099
void drainResume() override
Resume execution after a successful drain.
Definition: base.cc:417
struct kvm_run * _kvmRun
Pointer to the kvm_run structure used to communicate parameters with KVM.
Definition: base.hh:697
void syncKvmState()
Update the KVM if the thread context is dirty.
Definition: base.cc:971
#define M5_FALLTHROUGH
Definition: compiler.hh:84
KvmVM & vm
Definition: base.hh:151
Stats::Scalar numVMExits
Definition: base.hh:786
void activate() override
Set the status to Active.
virtual void takeOverFrom(BaseCPU *cpu)
Load the state of a CPU from the previous CPU object, invoked on all new CPUs that are about to be sw...
Definition: base.cc:555
#define hack_once(...)
Definition: logging.hh:214
ThreadContext * getContext(int tn) override
Given a thread num get tho thread context for it.
Definition: base.cc:582
Stats::Scalar numMMIO
Definition: base.hh:789
MasterID dataMasterId() const
Reads this CPU&#39;s unique data requestor ID.
Definition: base.hh:185
void setOneReg(uint64_t id, const void *addr)
Get/Set single register using the KVM_(SET|GET)_ONE_REG API.
Definition: base.cc:878
uint64_t Tick
Tick count type.
Definition: types.hh:61
void updateCycleCounters(CPUState state)
base method keeping track of cycle progression
Definition: base.hh:528
virtual bool archIsDrained() const
Is the architecture specific code in a state that prevents draining?
Definition: base.hh:522
const bool alwaysSyncTC
Be conservative and always synchronize the thread context on KVM entry/exit.
Definition: base.hh:621
void deallocateContext(ThreadID thread_num)
Definition: base.cc:567
void takeOverFrom(BaseCPU *cpu) override
Load the state of a CPU from the previous CPU object, invoked on all new CPUs that are about to be sw...
Definition: base.cc:477
struct kvm_coalesced_mmio_ring * mmioRing
Coalesced MMIO ring buffer.
Definition: base.hh:702
void startup() override
startup() is the final initialization call before simulation.
Definition: base.cc:320
std::string getAndFormatOneReg(uint64_t id) const
Get and format one register for printout.
Definition: base.cc:912
EventQueue * curEventQueue()
Definition: eventq.hh:82
void getRegisters(struct kvm_regs &regs) const
Get/Set the register state of the guest vCPU.
Definition: base.cc:835
pthread_t vcpuThread
ID of the vCPU thread.
Definition: base.hh:639
void deschedule(Event &event)
Definition: eventq.hh:943
PerfKvmCounterConfig & samplePeriod(uint64_t period)
Set the initial sample period (overflow count) of an event.
Definition: perfevent.hh:85
bool attached() const
Check if a counter is attached.
Definition: perfevent.hh:228
bool kvmStateDirty
Is the KVM state dirty? Set to true to force an update of the KVM vCPU state upon the next call to kv...
Definition: base.hh:633
static const Priority CPU_Tick_Pri
CPU ticks must come after other associated CPU events (such as writebacks).
Definition: eventq.hh:198
PerfKvmCounter hwInstructions
Guest instruction counter.
Definition: base.hh:760
uint64_t read() const
Read the current value of a counter.
Definition: perfevent.cc:135
#define fatal_if(cond,...)
Conditional fatal macro that checks the supplied condition and only causes a fatal error if the condi...
Definition: logging.hh:199
Running normally.
Definition: base.hh:195
PerfKvmCounter hwCycles
Guest cycle counter.
Definition: base.hh:747
Service completion in progress.
Definition: base.hh:226
void schedule(Event &event, Tick when)
Definition: eventq.hh:934
EventFunctionWrapper tickEvent
Definition: base.hh:706
Bitfield< 21 > ss
Requiring service at the beginning of the next cycle.
Definition: base.hh:209
virtual Tick handleKvmExitException()
An unhandled virtualization exception occured.
Definition: base.cc:1090
void setSignalMask(const sigset_t *mask)
Set the signal mask used in kvmRun()
Definition: base.cc:1148
Tick nextCycle() const
Based on the clock of the object, determine the start tick of the first cycle that is at least one cy...
Stats::Scalar numVMHalfEntries
Definition: base.hh:787
uint64_t Addr
Address type This will probably be moved somewhere else in the near future.
Definition: types.hh:140
ThreadContext * getTC()
Returns the pointer to this SimpleThread&#39;s ThreadContext.
void attach(PerfKvmCounterConfig &config, pid_t tid)
Attach a counter.
Definition: perfevent.hh:204
Tick nextTick() const
Definition: eventq.hh:770
int64_t Counter
Statistics counter type.
Definition: types.hh:56
void setupInstStop()
Setup an instruction break if there is one pending.
Definition: base.cc:1340
A Packet is used to encapsulate a transfer between two objects in the memory system (e...
Definition: packet.hh:249
Tick clockEdge(Cycles cycles=Cycles(0)) const
Determine the tick when a cycle begins, by default the current one, but the argument also enables the...
Status _status
CPU run state.
Definition: base.hh:230
Bitfield< 15 > system
Definition: misc.hh:997
bool discardPendingSignal(int signum) const
Discard a (potentially) pending signal.
Definition: base.cc:1249
virtual Fault finalizePhysical(const RequestPtr &req, ThreadContext *tc, Mode mode) const =0
Do post-translation physical address finalization.
virtual void switchOut()
Prepare for another CPU to take over execution.
Definition: base.cc:539
void kvmInterrupt(const struct kvm_interrupt &interrupt)
Send a normal interrupt to the guest.
Definition: base.cc:827
Stats::Scalar numHypercalls
Definition: base.hh:794
BaseKvmCPU(BaseKvmCPUParams *params)
Definition: base.cc:62
void setFPUState(const struct kvm_fpu &state)
Definition: base.cc:870
PerfKvmCounterConfig & exclude_host(bool val)
Exclude the events from the host (i.e., only include events from the guest system).
Definition: perfevent.hh:141
bool scheduled() const
Determine if the current event is scheduled.
Definition: eventq.hh:459
Mode
Definition: tlb.hh:57
Derived & name(const std::string &name)
Set the name and marks this stat to print at the end of simulation.
Definition: statistics.hh:276
int16_t ThreadID
Thread index/ID type.
Definition: types.hh:225
virtual const std::string name() const
Definition: sim_object.hh:129
const long pageSize
Cached page size of the host.
Definition: base.hh:704
PerfKvmCounterConfig & disabled(bool val)
Don&#39;t start the performance counter automatically when attaching it.
Definition: perfevent.hh:110
static void onKickSignal(int signo, siginfo_t *si, void *data)
Dummy handler for KVM kick signals.
Definition: base.cc:1215
PerfKvmCounterConfig & exclude_hv(bool val)
Exclude the hyper visor (i.e., only include events from the guest system).
Definition: perfevent.hh:156
Cycles ticksToCycles(Tick t) const
KVMCpuPort dataPort
Port for data requests.
Definition: base.hh:612
void ioctlRun()
Execute the KVM_RUN ioctl.
Definition: base.cc:1330
std::ostream CheckpointOut
Definition: serialize.hh:63
Status nextIOState() const
Returns next valid state after one or more IO accesses.
Definition: base.cc:166
Permanently shut down.
void getOneReg(uint64_t id, void *addr) const
Definition: base.cc:895
PerfEvent counter configuration.
Definition: perfevent.hh:51
int vcpuFD
KVM vCPU file descriptor.
Definition: base.hh:686
virtual uint64_t getHostCycles() const
Get the value of the hardware cycle counter in the guest.
Definition: base.cc:715
Definition: eventq.hh:245
void setRegisters(const struct kvm_regs &regs)
Definition: base.cc:842
bool bypassCaches() const
Should caches be bypassed?
Definition: system.hh:152
EventQueue * eventQueue() const
Definition: eventq.hh:925
void setupInstCounter(uint64_t period=0)
Setup the guest instruction counter.
Definition: base.cc:1352
Stats::Scalar numCycles
Definition: base.hh:599
void signalDrainDone() const
Signal that an object is drained.
Definition: drain.hh:289
void stop()
Stop counting.
Definition: perfevent.cc:114
void suspendContext(ThreadID thread_num) override
Notify the CPU that the indicated context is now suspended.
Definition: base.cc:544
virtual Tick handleKvmExitHypercall()
The guest requested a monitor service using a hypercall.
Definition: base.cc:1068
void unserializeThread(CheckpointIn &cp, ThreadID tid) override
Unserialize one thread.
Definition: base.cc:335
void init() override
init() is called after all C++ SimObjects have been created and all ports are connected.
Definition: base.cc:277
virtual ContextID contextId() const =0
int ioctl(int request, long p1) const
vCPU ioctl interface.
Definition: base.cc:1169
virtual Status status() const =0
int capCoalescedMMIO() const
Check if coalesced MMIO is supported and which page in the MMAP&#39;ed structure it stores requests in...
Definition: vm.cc:123
Kvm * kvm
Global KVM interface.
Definition: vm.hh:409
Bitfield< 3, 0 > mask
Definition: types.hh:62
Derived & desc(const std::string &_desc)
Set the description and marks this stat to print at the end of simulation.
Definition: statistics.hh:309
Temporarily inactive.
void serialize(CheckpointOut &cp) const override
Serialize an object.
Context not scheduled in KVM.
Definition: base.hh:189
void startup() override
startup() is the final initialization call before simulation.
Definition: base.cc:117
Counter totalOps() const override
Definition: base.cc:597
#define warn(...)
Definition: logging.hh:208
virtual Tick handleKvmExitUnknown()
An unknown architecture dependent error occurred when starting the vCPU.
Definition: base.cc:1082
SimpleThread * thread
A cached copy of a thread&#39;s state in the form of a SimpleThread object.
Definition: base.hh:144
void start()
Start counting.
Definition: perfevent.cc:107
Bitfield< 0 > vm
KVM parent interface.
Definition: vm.hh:72
Temporarily release the event queue service lock.
Definition: eventq.hh:714
void switchOut() override
Prepare for another CPU to take over execution.
Definition: base.cc:463
EventQueue comInstEventQueue
An instruction-based event queue.
int getVCPUMMapSize() const
Get the size of the MMAPed parameter area used to communicate vCPU parameters between the kernel and ...
Definition: vm.hh:88
virtual void initMemProxies(ThreadContext *tc)=0
Initialise the physical and virtual port proxies and tie them to the data port of the CPU...
Bitfield< 0 > p
Running normally.
virtual Tick handleKvmExit()
Main kvmRun exit handler, calls the relevant handleKvmExit* depending on exit type.
Definition: base.cc:983
const char data[]
std::shared_ptr< FaultBase > Fault
Definition: types.hh:238
const Params * params() const
Definition: base.hh:307
Tick doMMIOAccess(Addr paddr, void *data, int size, bool write)
Inject a memory mapped IO request into gem5.
Definition: base.cc:1107
Timer based on standard POSIX timers.
Definition: timer.hh:181
Bitfield< 5 > lock
Definition: types.hh:77
Stats::Scalar numCoalescedMMIO
Definition: base.hh:790
PerfEvent based timer using the host&#39;s CPU cycle counter.
Definition: timer.hh:213
void kick() const
Force an exit from KVM.
Definition: base.hh:129
void startupThread()
Thread-specific initialization.
Definition: base.cc:234
void syncThreadContext()
Update a thread context if the KVM state is dirty with respect to the cached thread context...
Definition: base.cc:959
void haltContext(ThreadID thread_num) override
Notify the CPU that the indicated context is now halted.
Definition: base.cc:574
Counter totalNumInsts
Definition: system.hh:480
ProbePointArg< PacketInfo > Packet
Packet probe point.
Definition: mem.hh:103

Generated on Fri Jul 3 2020 15:52:59 for gem5 by doxygen 1.8.13