1/*
2 * Copyright (c) 2012-2013, 2015-2016 ARM Limited
3 * Copyright (c) 2013 Cornell University
4 * All rights reserved
5 *
6 * The license below extends only to copyright in the software and shall
7 * not be construed as granting a license to any other intellectual
8 * property including but not limited to intellectual property relating
9 * to a hardware implementation of the functionality of the software
10 * licensed hereunder.  You may use the software subject to the license
11 * terms below provided that you ensure that this notice is replicated
12 * unmodified and in its entirety in all distributions of the software,
13 * modified or unmodified, in source code or in binary form.
14 *
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions are
17 * met: redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer;
19 * redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution;
22 * neither the name of the copyright holders nor the names of its
23 * contributors may be used to endorse or promote products derived from
24 * this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
29 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
30 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
31 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
32 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
36 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 *
38 * Authors: Andreas Hansson
39 *          Christopher Torng
40 *          Akash Bagdia
41 *          David Guillen Fandos
42 */
43
44/**
45 * @file
46 * ClockedObject declaration and implementation.
47 */
48
49#ifndef __SIM_CLOCKED_OBJECT_HH__
50#define __SIM_CLOCKED_OBJECT_HH__
51
52#include "base/callback.hh"
53#include "base/intmath.hh"
54#include "enums/PwrState.hh"
55#include "params/ClockedObject.hh"
56#include "sim/core.hh"
57#include "sim/clock_domain.hh"
58#include "sim/sim_object.hh"
59
60/**
61 * Helper class for objects that need to be clocked. Clocked objects
62 * typically inherit from this class. Objects that need SimObject
63 * functionality as well should inherit from ClockedObject.
64 */
65class Clocked
66{
67
68  private:
69    // the tick value of the next clock edge (>= curTick()) at the
70    // time of the last call to update()
71    mutable Tick tick;
72
73    // The cycle counter value corresponding to the current value of
74    // 'tick'
75    mutable Cycles cycle;
76
77    /**
78     *  Align cycle and tick to the next clock edge if not already done. When
79     *  complete, tick must be at least curTick().
80     */
81    void
82    update() const
83    {
84        // both tick and cycle are up-to-date and we are done, note
85        // that the >= is important as it captures cases where tick
86        // has already passed curTick()
87        if (tick >= curTick())
88            return;
89
90        // optimise for the common case and see if the tick should be
91        // advanced by a single clock period
92        tick += clockPeriod();
93        ++cycle;
94
95        // see if we are done at this point
96        if (tick >= curTick())
97            return;
98
99        // if not, we have to recalculate the cycle and tick, we
100        // perform the calculations in terms of relative cycles to
101        // allow changes to the clock period in the future
102        Cycles elapsedCycles(divCeil(curTick() - tick, clockPeriod()));
103        cycle += elapsedCycles;
104        tick += elapsedCycles * clockPeriod();
105    }
106
107    /**
108     * The clock domain this clocked object belongs to
109     */
110    ClockDomain &clockDomain;
111
112  protected:
113
114    /**
115     * Create a clocked object and set the clock domain based on the
116     * parameters.
117     */
118    Clocked(ClockDomain &clk_domain)
119        : tick(0), cycle(0), clockDomain(clk_domain)
120    {
121        // Register with the clock domain, so that if the clock domain
122        // frequency changes, we can update this object's tick.
123        clockDomain.registerWithClockDomain(this);
124    }
125
126    Clocked(Clocked &) = delete;
127    Clocked &operator=(Clocked &) = delete;
128
129    /**
130     * Virtual destructor due to inheritance.
131     */
132    virtual ~Clocked() { }
133
134    /**
135     * Reset the object's clock using the current global tick value. Likely
136     * to be used only when the global clock is reset. Currently, this done
137     * only when Ruby is done warming up the memory system.
138     */
139    void
140    resetClock() const
141    {
142        Cycles elapsedCycles(divCeil(curTick(), clockPeriod()));
143        cycle = elapsedCycles;
144        tick = elapsedCycles * clockPeriod();
145    }
146
147    /**
148     * A hook subclasses can implement so they can do any extra work that's
149     * needed when the clock rate is changed.
150     */
151    virtual void clockPeriodUpdated() {}
152
153  public:
154
155    /**
156     * Update the tick to the current tick.
157     */
158    void
159    updateClockPeriod()
160    {
161        update();
162        clockPeriodUpdated();
163    }
164
165    /**
166     * Determine the tick when a cycle begins, by default the current one, but
167     * the argument also enables the caller to determine a future cycle. When
168     * curTick() is on a clock edge, the number of cycles in the parameter is
169     * added to curTick() to be returned. When curTick() is not aligned to a
170     * clock edge, the number of cycles in the parameter is added to the next
171     * clock edge.
172     *
173     * @param cycles The number of cycles into the future
174     *
175     * @return The start tick when the requested clock edge occurs. Precisely,
176     * this tick can be
177     *     curTick() + [0, clockPeriod()) + clockPeriod() * cycles
178     */
179    Tick
180    clockEdge(Cycles cycles=Cycles(0)) const
181    {
182        // align tick to the next clock edge
183        update();
184
185        // figure out when this future cycle is
186        return tick + clockPeriod() * cycles;
187    }
188
189    /**
190     * Determine the current cycle, corresponding to a tick aligned to
191     * a clock edge.
192     *
193     * @return When curTick() is on a clock edge, return the Cycle corresponding
194     * to that clock edge. When curTick() is not on a clock edge, return the
195     * Cycle corresponding to the next clock edge.
196     */
197    Cycles
198    curCycle() const
199    {
200        // align cycle to the next clock edge.
201        update();
202
203        return cycle;
204    }
205
206    /**
207     * Based on the clock of the object, determine the start tick of the first
208     * cycle that is at least one cycle in the future. When curTick() is at the
209     * current cycle edge, this returns the next clock edge. When calling this
210     * during the middle of a cycle, this returns 2 clock edges in the future.
211     *
212     * @return The start tick of the first cycle that is at least one cycle in
213     * the future. Precisely, the returned tick can be in the range
214     *     curTick() + [clockPeriod(), 2 * clockPeriod())
215     */
216    Tick nextCycle() const { return clockEdge(Cycles(1)); }
217
218    uint64_t frequency() const { return SimClock::Frequency / clockPeriod(); }
219
220    Tick clockPeriod() const { return clockDomain.clockPeriod(); }
221
222    double voltage() const { return clockDomain.voltage(); }
223
224    Cycles
225    ticksToCycles(Tick t) const
226    {
227        return Cycles(divCeil(t, clockPeriod()));
228    }
229
230    Tick cyclesToTicks(Cycles c) const { return clockPeriod() * c; }
231};
232
233/**
234 * The ClockedObject class extends the SimObject with a clock and
235 * accessor functions to relate ticks to the cycles of the object.
236 */
237class ClockedObject : public SimObject, public Clocked
238{
239  public:
240    ClockedObject(const ClockedObjectParams *p);
241
242    /** Parameters of ClockedObject */
243    typedef ClockedObjectParams Params;
244    const Params *
245    params() const
246    {
247        return reinterpret_cast<const Params*>(_params);
248    }
249
250    void serialize(CheckpointOut &cp) const override;
251    void unserialize(CheckpointIn &cp) override;
252
253    Enums::PwrState pwrState() const { return _currPwrState; }
254
255    std::string
256    pwrStateName() const
257    {
258        return Enums::PwrStateStrings[_currPwrState];
259    }
260
261    /** Returns the percentage residency for each power state */
262    std::vector<double> pwrStateWeights() const;
263
264    /**
265     * Record stats values like state residency by computing the time
266     * difference from previous update. Also, updates the previous evaluation
267     * tick once all stats are recorded.
268     * Usually called on power state change and stats dump callback.
269     */
270    void computeStats();
271
272    void pwrState(Enums::PwrState);
273    void regStats() override;
274
275  protected:
276
277    /** To keep track of the current power state */
278    Enums::PwrState _currPwrState;
279
280    Tick prvEvalTick;
281
282    Stats::Scalar numPwrStateTransitions;
283    Stats::Distribution pwrStateClkGateDist;
284    Stats::Vector pwrStateResidencyTicks;
285
286};
287
288class ClockedObjectDumpCallback : public Callback
289{
290    ClockedObject *co;
291  public:
292    ClockedObjectDumpCallback(ClockedObject *co_t) : co(co_t) {}
293    virtual void process() { co->computeStats(); };
294};
295
296#endif //__SIM_CLOCKED_OBJECT_HH__
297