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

Generated on Tue Jun 22 2021 15:28:25 for gem5 by doxygen 1.8.17