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

Generated on Fri Feb 28 2020 16:26:59 for gem5 by doxygen 1.8.13