2 * Copyright (c) 2013, 2015, 2017-2018,2020 ARM Limited
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.
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.
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.
38 #ifndef __DEV_ARM_GENERIC_TIMER_HH__
39 #define __DEV_ARM_GENERIC_TIMER_HH__
41 #include "arch/arm/isa_device.hh"
42 #include "arch/arm/system.hh"
43 #include "dev/arm/base_gic.hh"
44 #include "dev/arm/generic_timer_miscregs_types.hh"
45 #include "sim/core.hh"
46 #include "sim/sim_object.hh"
49 /// This module implements the global system counter and the local per-CPU
50 /// architected timers as specified by the ARM Generic Timer extension:
51 /// Arm ARM (ARM DDI 0487E.a)
52 /// D11.1.2 - The system counter
53 /// D11.2 - The AArch64 view of the Generic Timer
54 /// G6.2 - The AArch32 view of the Generic Timer
55 /// I2 - System Level Implementation of the Generic Timer
58 class SystemCounterParams;
59 class GenericTimerParams;
60 class GenericTimerFrameParams;
61 class GenericTimerMemParams;
63 /// Abstract class for elements whose events depend on the counting speed
64 /// of the System Counter
65 class SystemCounterListener : public Serializable
68 /// Called from the SystemCounter when a change in counting speed occurred
69 /// Events should be rescheduled properly inside this member function
70 virtual void notify(void) = 0;
73 /// Global system counter. It is shared by the architected and memory-mapped
75 class SystemCounter : public SimObject
78 /// Indicates if the counter is enabled
80 /// Counter frequency (as specified by CNTFRQ).
82 /// Counter value (as specified in CNTCV).
84 /// Value increment in each counter cycle
86 /// Frequency modes table with all possible frequencies for the counter
87 std::vector<uint32_t> _freqTable;
88 /// Currently selected entry in the table, its contents should match _freq
89 size_t _activeFreqEntry;
90 /// Cached copy of the counter period (inverse of the frequency).
92 /// Counter cycle start Tick when the counter status affecting
93 /// its value has been updated
96 /// Listeners to changes in counting speed
97 std::vector<SystemCounterListener *> _listeners;
99 /// Maximum architectural number of frequency table entries
100 static constexpr size_t MAX_FREQ_ENTRIES = 1004;
103 SystemCounter(SystemCounterParams *const p);
105 /// Validates a System Counter reference
106 /// @param sys_cnt System counter reference to validate
107 static void validateCounterRef(SystemCounter *sys_cnt);
109 /// Indicates if the counter is enabled.
110 bool enabled() const { return _enabled; }
111 /// Returns the counter frequency.
112 uint32_t freq() const { return _freq; }
113 /// Updates and returns the counter value.
115 /// Returns the value increment
116 uint64_t increment() const { return _increment; }
117 /// Returns a reference to the frequency modes table.
118 std::vector<uint32_t>& freqTable() { return _freqTable; }
119 /// Returns the currently active frequency table entry.
120 size_t activeFreqEntry() const { return _activeFreqEntry; }
121 /// Returns the counter period.
122 Tick period() const { return _period; }
124 /// Enables the counter after a CNTCR.EN == 1
126 /// Disables the counter after a CNTCR.EN == 0
129 /// Schedules a counter frequency update after a CNTCR.FCREQ == 1
130 /// This complies with frequency transitions as per the architecture
131 /// @param new_freq_entry Index in CNTFID of the new freq
132 void freqUpdateSchedule(size_t new_freq_entry);
134 /// Sets the value explicitly from writes to CNTCR.CNTCV
135 void setValue(uint64_t new_value);
137 /// Called from System Counter Listeners to register
138 void registerListener(SystemCounterListener *listener);
140 /// Returns the tick at which a certain counter value is reached
141 Tick whenValue(uint64_t target_val);
142 Tick whenValue(uint64_t cur_val, uint64_t target_val) const;
144 void serialize(CheckpointOut &cp) const override;
145 void unserialize(CheckpointIn &cp) override;
149 SystemCounter(const SystemCounter &c);
151 /// Frequency update event handling
152 EventFunctionWrapper _freqUpdateEvent;
153 size_t _nextFreqEntry;
154 /// Callback for the frequency update
155 void freqUpdateCallback();
157 /// Updates the counter value.
158 void updateValue(void);
160 /// Updates the update tick, normalizes to the lower cycle start tick
161 void updateTick(void);
163 /// Notifies counting speed changes to listeners
164 void notifyListeners(void) const;
167 /// Per-CPU architected timer.
168 class ArchTimer : public SystemCounterListener, public Drainable
171 /// Control register.
172 BitUnion32(ArchTimerCtrl)
176 EndBitUnion(ArchTimerCtrl)
178 /// Name of this timer.
179 const std::string _name;
181 /// Pointer to parent class.
184 SystemCounter &_systemCounter;
186 ArmInterruptPin * const _interrupt;
188 /// Value of the control register ({CNTP/CNTHP/CNTV}_CTL).
189 ArchTimerCtrl _control;
190 /// Programmed limit value for the upcounter ({CNTP/CNTHP/CNTV}_CVAL).
191 uint64_t _counterLimit;
192 /// Offset relative to the physical timer (CNTVOFF)
196 * Timer settings or the offset has changed, re-evaluate
197 * trigger condition and raise interrupt if necessary.
199 void updateCounter();
201 /// Called when the upcounter reaches the programmed value.
202 void counterLimitReached();
203 EventFunctionWrapper _counterLimitReachedEvent;
205 virtual bool scheduleEvents() { return true; }
208 ArchTimer(const std::string &name,
210 SystemCounter &sysctr,
211 ArmInterruptPin *interrupt);
213 /// Returns the timer name.
214 std::string name() const { return _name; }
216 /// Returns the CompareValue view of the timer.
217 uint64_t compareValue() const { return _counterLimit; }
218 /// Sets the CompareValue view of the timer.
219 void setCompareValue(uint64_t val);
221 /// Returns the TimerValue view of the timer.
222 uint32_t timerValue() const { return _counterLimit - value(); }
223 /// Sets the TimerValue view of the timer.
224 void setTimerValue(uint32_t val);
226 /// Sets the control register.
227 uint32_t control() const { return _control; }
228 void setControl(uint32_t val);
230 uint64_t offset() const { return _offset; }
231 void setOffset(uint64_t val);
233 /// Returns the value of the counter which this timer relies on.
234 uint64_t value() const;
235 Tick whenValue(uint64_t target_val) {
236 return _systemCounter.whenValue(value(), target_val);
239 void notify(void) override;
242 void serialize(CheckpointOut &cp) const override;
243 void unserialize(CheckpointIn &cp) override;
246 DrainState drain() override;
247 void drainResume() override;
251 ArchTimer(const ArchTimer &t);
254 class ArchTimerKvm : public ArchTimer
260 ArchTimerKvm(const std::string &name,
263 SystemCounter &sysctr,
264 ArmInterruptPin *interrupt)
265 : ArchTimer(name, parent, sysctr, interrupt), system(system) {}
268 // For ArchTimer's in a GenericTimerISA with Kvm execution about
269 // to begin, skip rescheduling the event.
270 // Otherwise, we should reschedule the event (if necessary).
271 bool scheduleEvents() override {
272 return !system.validKvmEnvironment();
276 class GenericTimer : public SimObject
279 const GenericTimerParams * params() const;
281 GenericTimer(GenericTimerParams *const p);
283 void serialize(CheckpointOut &cp) const override;
284 void unserialize(CheckpointIn &cp) override;
287 void setMiscReg(int misc_reg, unsigned cpu, RegVal val);
288 RegVal readMiscReg(int misc_reg, unsigned cpu);
291 class CoreTimers : public SystemCounterListener
294 CoreTimers(GenericTimer &_parent, ArmSystem &system, unsigned cpu,
295 ArmInterruptPin *_irqPhysS, ArmInterruptPin *_irqPhysNS,
296 ArmInterruptPin *_irqVirt, ArmInterruptPin *_irqHyp);
298 /// Generic Timer parent reference
299 GenericTimer &parent;
301 /// System counter frequency as visible from this core
304 /// Kernel control register
307 /// Hypervisor control register
310 /// Thread (HW) context associated to this PE implementation
311 ThreadContext *threadContext;
313 ArmInterruptPin const *irqPhysS;
314 ArmInterruptPin const *irqPhysNS;
315 ArmInterruptPin const *irqVirt;
316 ArmInterruptPin const *irqHyp;
323 // Event Stream. Events are generated based on a configurable
324 // transitionBit over the counter value. transitionTo indicates
325 // the transition direction (0->1 or 1->0)
328 EventFunctionWrapper event;
329 uint8_t transitionTo;
330 uint8_t transitionBit;
333 eventTargetValue(uint64_t val) const
335 uint64_t bit_val = bits(val, transitionBit);
336 uint64_t ret_val = mbits(val, 63, transitionBit);
337 uint64_t incr_val = 1 << transitionBit;
338 if (bit_val == transitionTo)
340 return ret_val + incr_val;
344 EventStream physEvStream;
345 EventStream virtEvStream;
346 void physEventStreamCallback();
347 void virtEventStreamCallback();
348 void eventStreamCallback() const;
349 void schedNextEvent(EventStream &ev_stream, ArchTimer &timer);
351 void notify(void) override;
353 void serialize(CheckpointOut &cp) const override;
354 void unserialize(CheckpointIn &cp) override;
358 CoreTimers(const CoreTimers &c);
361 CoreTimers &getTimers(int cpu_id);
362 void createTimers(unsigned cpus);
364 /// System counter reference.
365 SystemCounter &systemCounter;
367 /// Per-CPU physical architected timers.
368 std::vector<std::unique_ptr<CoreTimers>> timers;
370 protected: // Configuration
371 /// ARM system containing this timer
374 void handleStream(CoreTimers::EventStream *ev_stream,
375 ArchTimer *timer, RegVal old_cnt_ctl, RegVal cnt_ctl);
378 class GenericTimerISA : public ArmISA::BaseISADevice
381 GenericTimerISA(GenericTimer &_parent, unsigned _cpu)
382 : parent(_parent), cpu(_cpu) {}
384 void setMiscReg(int misc_reg, RegVal val) override;
385 RegVal readMiscReg(int misc_reg) override;
388 GenericTimer &parent;
392 class GenericTimerFrame : public PioDevice
395 GenericTimerFrame(GenericTimerFrameParams *const p);
397 void serialize(CheckpointOut &cp) const override;
398 void unserialize(CheckpointIn &cp) override;
400 /// Indicates if this frame implements a virtual timer
401 bool hasVirtualTimer() const;
403 /// Returns the virtual offset for this frame if a virtual timer is
405 uint64_t getVirtOffset() const;
407 /// Sets the virtual offset for this frame's virtual timer after
408 /// a write to CNTVOFF
409 void setVirtOffset(uint64_t new_offset);
411 /// Indicates if this frame implements a second EL0 view
412 bool hasEl0View() const;
414 /// Returns the access bits for this frame
415 uint8_t getAccessBits() const;
417 /// Updates the access bits after a write to CNTCTLBase.CNTACR
418 void setAccessBits(uint8_t data);
420 /// Indicates if non-secure accesses are allowed to this frame
421 bool hasNonSecureAccess() const;
423 /// Allows non-secure accesses after an enabling write to
424 /// CNTCTLBase.CNTNSAR
425 void setNonSecureAccess();
427 /// Indicates if CNTVOFF is readable for this frame
428 bool hasReadableVoff() const;
431 AddrRangeList getAddrRanges() const override;
432 Tick read(PacketPtr pkt) override;
433 Tick write(PacketPtr pkt) override;
436 /// CNTBase/CNTEL0Base (Memory-mapped timer frame)
437 uint64_t timerRead(Addr addr, size_t size, bool is_sec, bool to_el0) const;
438 void timerWrite(Addr addr, size_t size, uint64_t data, bool is_sec,
440 const AddrRange timerRange;
441 AddrRange timerEl0Range;
443 static const Addr TIMER_CNTPCT_LO = 0x00;
444 static const Addr TIMER_CNTPCT_HI = 0x04;
445 static const Addr TIMER_CNTVCT_LO = 0x08;
446 static const Addr TIMER_CNTVCT_HI = 0x0c;
447 static const Addr TIMER_CNTFRQ = 0x10;
448 static const Addr TIMER_CNTEL0ACR = 0x14;
449 static const Addr TIMER_CNTVOFF_LO = 0x18;
450 static const Addr TIMER_CNTVOFF_HI = 0x1c;
451 static const Addr TIMER_CNTP_CVAL_LO = 0x20;
452 static const Addr TIMER_CNTP_CVAL_HI = 0x24;
453 static const Addr TIMER_CNTP_TVAL = 0x28;
454 static const Addr TIMER_CNTP_CTL = 0x2c;
455 static const Addr TIMER_CNTV_CVAL_LO = 0x30;
456 static const Addr TIMER_CNTV_CVAL_HI = 0x34;
457 static const Addr TIMER_CNTV_TVAL = 0x38;
458 static const Addr TIMER_CNTV_CTL = 0x3c;
460 /// All MMIO ranges GenericTimerFrame responds to
461 AddrRangeList addrRanges;
463 /// System counter reference.
464 SystemCounter &systemCounter;
466 /// Physical and virtual timers
470 /// Reports access properties of the CNTBase register frame elements
471 BitUnion8(AccessBits)
478 EndBitUnion(AccessBits)
479 AccessBits accessBits;
481 // Reports access properties of the CNTEL0Base register frame elements
482 BitUnion16(AccessBitsEl0)
487 EndBitUnion(AccessBitsEl0)
488 AccessBitsEl0 accessBitsEl0;
490 /// Reports whether non-secure accesses are allowed to this frame
491 bool nonSecureAccess;
496 class GenericTimerMem : public PioDevice
499 GenericTimerMem(GenericTimerMemParams *const p);
501 /// Validates a Generic Timer register frame address range
502 /// @param base_addr Range of the register frame
503 static void validateFrameRange(const AddrRange &range);
505 /// Validates an MMIO access permissions
506 /// @param sys System reference where the acces is being made
507 /// @param is_sec If the access is to secure memory
508 static bool validateAccessPerm(ArmSystem &sys, bool is_sec);
511 AddrRangeList getAddrRanges() const override;
512 Tick read(PacketPtr pkt) override;
513 Tick write(PacketPtr pkt) override;
516 /// CNTControlBase (System counter control frame)
517 uint64_t counterCtrlRead(Addr addr, size_t size, bool is_sec) const;
518 void counterCtrlWrite(Addr addr, size_t size, uint64_t data, bool is_sec);
519 const AddrRange counterCtrlRange;
522 Bitfield<17,8> fcreq;
529 Bitfield<31,8> fcack;
532 static const Addr COUNTER_CTRL_CNTCR = 0x00;
533 static const Addr COUNTER_CTRL_CNTSR = 0x04;
534 static const Addr COUNTER_CTRL_CNTCV_LO = 0x08;
535 static const Addr COUNTER_CTRL_CNTCV_HI = 0x0c;
536 static const Addr COUNTER_CTRL_CNTSCR = 0x10;
537 static const Addr COUNTER_CTRL_CNTID = 0x1c;
538 static const Addr COUNTER_CTRL_CNTFID = 0x20;
540 /// CNTReadBase (System counter status frame)
541 uint64_t counterStatusRead(Addr addr, size_t size) const;
542 void counterStatusWrite(Addr addr, size_t size, uint64_t data);
543 const AddrRange counterStatusRange;
545 static const Addr COUNTER_STATUS_CNTCV_LO = 0x00;
546 static const Addr COUNTER_STATUS_CNTCV_HI = 0x04;
548 /// CNTCTLBase (Memory-mapped timer global control frame)
549 uint64_t timerCtrlRead(Addr addr, size_t size, bool is_sec) const;
550 void timerCtrlWrite(Addr addr, size_t size, uint64_t data, bool is_sec);
551 const AddrRange timerCtrlRange;
553 /// ID register for reporting features of implemented timer frames
556 static const Addr TIMER_CTRL_CNTFRQ = 0x00;
557 static const Addr TIMER_CTRL_CNTNSAR = 0x04;
558 static const Addr TIMER_CTRL_CNTTIDR = 0x08;
559 static const Addr TIMER_CTRL_CNTACR = 0x40;
560 static const Addr TIMER_CTRL_CNTVOFF_LO = 0x80;
561 static const Addr TIMER_CTRL_CNTVOFF_HI = 0x84;
563 /// All MMIO ranges GenericTimerMem responds to
564 const AddrRangeList addrRanges;
566 /// System counter reference.
567 SystemCounter &systemCounter;
569 /// Maximum architectural number of memory-mapped timer frames
570 static constexpr size_t MAX_TIMER_FRAMES = 8;
572 /// Timer frame references
573 std::vector<GenericTimerFrame *> frames;
578 #endif // __DEV_ARM_GENERIC_TIMER_HH__