1/*
2 * Copyright (c) 2012-2013, 2016-2019 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: Thomas Grass
38 *          Andreas Hansson
39 *          Sascha Bischoff
40 */
41
42#ifndef __CPU_TRAFFIC_GEN_BASE_HH__
43#define __CPU_TRAFFIC_GEN_BASE_HH__
44
45#include <memory>
46#include <tuple>
47#include <unordered_map>
48
49#include "base/statistics.hh"
50#include "mem/qport.hh"
51#include "sim/clocked_object.hh"
52
53class BaseGen;
54class StreamGen;
55class System;
56struct BaseTrafficGenParams;
57
58/**
59 * The traffic generator is a master module that generates stimuli for
60 * the memory system, based on a collection of simple generator
61 * behaviours that are either probabilistic or based on traces. It can
62 * be used stand alone for creating test cases for interconnect and
63 * memory controllers, or function as a black box replacement for
64 * system components that are not yet modelled in detail, e.g. a video
65 * engine or baseband subsystem.
66 */
67class BaseTrafficGen : public ClockedObject
68{
69    friend class BaseGen;
70
71  protected: // Params
72    /**
73     * The system used to determine which mode we are currently operating
74     * in.
75     */
76    System *const system;
77
78    /**
79     * Determine whether to add elasticity in the request injection,
80     * thus responding to backpressure by slowing things down.
81     */
82    const bool elasticReq;
83
84    /**
85     * Time to tolerate waiting for retries (not making progress),
86     * until we declare things broken.
87     */
88    const Tick progressCheck;
89
90  private:
91    /**
92     * Receive a retry from the neighbouring port and attempt to
93     * resend the waiting packet.
94     */
95    void recvReqRetry();
96
97    void retryReq();
98
99    bool recvTimingResp(PacketPtr pkt);
100
101    /** Transition to the next generator */
102    void transition();
103
104    /**
105     * Schedule the update event based on nextPacketTick and
106     * nextTransitionTick.
107     */
108    void scheduleUpdate();
109
110    /**
111     * Method to inform the user we have made no progress.
112     */
113    void noProgress();
114
115    /**
116     * Event to keep track of our progress, or lack thereof.
117     */
118    EventFunctionWrapper noProgressEvent;
119
120    /** Time of next transition */
121    Tick nextTransitionTick;
122
123    /** Time of the next packet. */
124    Tick nextPacketTick;
125
126    const int maxOutstandingReqs;
127
128
129    /** Master port specialisation for the traffic generator */
130    class TrafficGenPort : public MasterPort
131    {
132      public:
133
134        TrafficGenPort(const std::string& name, BaseTrafficGen& traffic_gen)
135            : MasterPort(name, &traffic_gen), trafficGen(traffic_gen)
136        { }
137
138      protected:
139
140        void recvReqRetry() { trafficGen.recvReqRetry(); }
141
142        bool recvTimingResp(PacketPtr pkt)
143        { return trafficGen.recvTimingResp(pkt); }
144
145        void recvTimingSnoopReq(PacketPtr pkt) { }
146
147        void recvFunctionalSnoop(PacketPtr pkt) { }
148
149        Tick recvAtomicSnoop(PacketPtr pkt) { return 0; }
150
151      private:
152
153        BaseTrafficGen& trafficGen;
154
155    };
156
157    /**
158     * Schedules event for next update and generates a new packet or
159     * requests a new generatoir depending on the current time.
160     */
161    void update();
162
163    /** The instance of master port used by the traffic generator. */
164    TrafficGenPort port;
165
166    /** Packet waiting to be sent. */
167    PacketPtr retryPkt;
168
169    /** Tick when the stalled packet was meant to be sent. */
170    Tick retryPktTick;
171
172    /** Set when we blocked waiting for outstanding reqs */
173    bool blockedWaitingResp;
174
175    /**
176     * Puts this packet in the waitingResp list and returns true if
177     * we are above the maximum number of oustanding requests.
178     */
179    bool allocateWaitingRespSlot(PacketPtr pkt)
180    {
181        assert(waitingResp.find(pkt->req) == waitingResp.end());
182        assert(pkt->needsResponse());
183
184        waitingResp[pkt->req] = curTick();
185
186        return (maxOutstandingReqs > 0) &&
187               (waitingResp.size() > maxOutstandingReqs);
188    }
189
190    /** Event for scheduling updates */
191    EventFunctionWrapper updateEvent;
192
193  protected: // Stats
194    /** Reqs waiting for response **/
195    std::unordered_map<RequestPtr,Tick> waitingResp;
196
197    struct StatGroup : public Stats::Group {
198        StatGroup(Stats::Group *parent);
199
200        /** Count the number of dropped requests. */
201        Stats::Scalar numSuppressed;
202
203        /** Count the number of generated packets. */
204        Stats::Scalar numPackets;
205
206        /** Count the number of retries. */
207        Stats::Scalar numRetries;
208
209        /** Count the time incurred from back-pressure. */
210        Stats::Scalar retryTicks;
211
212        /** Count the number of bytes read. */
213        Stats::Scalar bytesRead;
214
215        /** Count the number of bytes written. */
216        Stats::Scalar bytesWritten;
217
218        /** Total num of ticks read reqs took to complete  */
219        Stats::Scalar totalReadLatency;
220
221        /** Total num of ticks write reqs took to complete  */
222        Stats::Scalar totalWriteLatency;
223
224        /** Count the number reads. */
225        Stats::Scalar totalReads;
226
227        /** Count the number writes. */
228        Stats::Scalar totalWrites;
229
230        /** Avg num of ticks each read req took to complete  */
231        Stats::Formula avgReadLatency;
232
233        /** Avg num of ticks each write reqs took to complete  */
234        Stats::Formula avgWriteLatency;
235
236        /** Read bandwidth in bytes/s  */
237        Stats::Formula readBW;
238
239        /** Write bandwidth in bytes/s  */
240        Stats::Formula writeBW;
241    } stats;
242
243  public:
244    BaseTrafficGen(const BaseTrafficGenParams* p);
245
246    ~BaseTrafficGen();
247
248    Port &getPort(const std::string &if_name,
249                  PortID idx=InvalidPortID) override;
250
251    void init() override;
252
253    DrainState drain() override;
254
255    void serialize(CheckpointOut &cp) const override;
256    void unserialize(CheckpointIn &cp) override;
257
258  public: // Generator factory methods
259    std::shared_ptr<BaseGen> createIdle(Tick duration);
260    std::shared_ptr<BaseGen> createExit(Tick duration);
261
262    std::shared_ptr<BaseGen> createLinear(
263        Tick duration,
264        Addr start_addr, Addr end_addr, Addr blocksize,
265        Tick min_period, Tick max_period,
266        uint8_t read_percent, Addr data_limit);
267
268    std::shared_ptr<BaseGen> createRandom(
269        Tick duration,
270        Addr start_addr, Addr end_addr, Addr blocksize,
271        Tick min_period, Tick max_period,
272        uint8_t read_percent, Addr data_limit);
273
274    std::shared_ptr<BaseGen> createDram(
275        Tick duration,
276        Addr start_addr, Addr end_addr, Addr blocksize,
277        Tick min_period, Tick max_period,
278        uint8_t read_percent, Addr data_limit,
279        unsigned int num_seq_pkts, unsigned int page_size,
280        unsigned int nbr_of_banks_DRAM, unsigned int nbr_of_banks_util,
281        unsigned int addr_mapping,
282        unsigned int nbr_of_ranks);
283
284    std::shared_ptr<BaseGen> createDramRot(
285        Tick duration,
286        Addr start_addr, Addr end_addr, Addr blocksize,
287        Tick min_period, Tick max_period,
288        uint8_t read_percent, Addr data_limit,
289        unsigned int num_seq_pkts, unsigned int page_size,
290        unsigned int nbr_of_banks_DRAM, unsigned int nbr_of_banks_util,
291        unsigned int addr_mapping,
292        unsigned int nbr_of_ranks,
293        unsigned int max_seq_count_per_rank);
294
295    std::shared_ptr<BaseGen> createTrace(
296        Tick duration,
297        const std::string& trace_file, Addr addr_offset);
298
299  protected:
300    void start();
301
302    virtual std::shared_ptr<BaseGen> nextGenerator() = 0;
303
304    /**
305     * MasterID used in generated requests.
306     */
307    const MasterID masterID;
308
309    /** Currently active generator */
310    std::shared_ptr<BaseGen> activeGenerator;
311
312    /** Stream/SubStreamID Generator */
313    std::unique_ptr<StreamGen> streamGenerator;
314};
315
316#endif //__CPU_TRAFFIC_GEN_BASE_HH__
317