traffic_gen.cc revision 9402:f6e3c60f04e5
1/*
2 * Copyright (c) 2012 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#include <sstream>
43
44#include "base/random.hh"
45#include "cpu/testers/traffic_gen/traffic_gen.hh"
46#include "debug/Checkpoint.hh"
47#include "debug/TrafficGen.hh"
48#include "proto/packet.pb.h"
49#include "sim/stats.hh"
50#include "sim/system.hh"
51
52using namespace std;
53
54TrafficGen::TrafficGen(const TrafficGenParams* p)
55    : MemObject(p),
56      system(p->system),
57      masterID(system->getMasterId(name())),
58      port(name() + ".port", *this),
59      stateGraph(*this, port, p->config_file, masterID),
60      updateStateGraphEvent(this)
61{
62}
63
64TrafficGen*
65TrafficGenParams::create()
66{
67    return new TrafficGen(this);
68}
69
70BaseMasterPort&
71TrafficGen::getMasterPort(const string& if_name, PortID idx)
72{
73    if (if_name == "port") {
74        return port;
75    } else {
76        return MemObject::getMasterPort(if_name, idx);
77    }
78}
79
80void
81TrafficGen::init()
82{
83    if (!port.isConnected())
84        fatal("The port of %s is not connected!\n", name());
85
86    Enums::MemoryMode mode = system->getMemoryMode();
87
88    // if the system is in timing mode active the request generator
89    if (mode == Enums::timing) {
90        DPRINTF(TrafficGen, "Timing mode, activating request generator\n");
91
92        // enter initial state
93        stateGraph.enterState(stateGraph.currState);
94    } else {
95        DPRINTF(TrafficGen,
96                "Traffic generator is only active in timing mode\n");
97    }
98}
99
100void
101TrafficGen::initState()
102{
103    // when not restoring from a checkpoint, make sure we kick things off
104    if (system->getMemoryMode() == Enums::timing) {
105        Tick nextStateGraphEvent = stateGraph.nextEventTick();
106        schedule(updateStateGraphEvent, nextStateGraphEvent);
107    } else {
108        DPRINTF(TrafficGen,
109                "Traffic generator is only active in timing mode\n");
110    }
111}
112
113unsigned int
114TrafficGen::drain(DrainManager *dm)
115{
116    // @todo we should also stop putting new requests in the queue and
117    // either interrupt the current state or wait for a transition
118    return port.drain(dm);
119}
120
121void
122TrafficGen::serialize(ostream &os)
123{
124    DPRINTF(Checkpoint, "Serializing TrafficGen\n");
125
126    // save ticks of the graph event if it is scheduled
127    Tick nextStateGraphEvent = updateStateGraphEvent.scheduled() ?
128        updateStateGraphEvent.when() : 0;
129
130    DPRINTF(TrafficGen, "Saving nextStateGraphEvent=%llu\n",
131            nextStateGraphEvent);
132
133    SERIALIZE_SCALAR(nextStateGraphEvent);
134
135    Tick nextTransitionTick = stateGraph.nextTransitionTick;
136    SERIALIZE_SCALAR(nextTransitionTick);
137
138    // @todo: also serialise the current state, figure out the best
139    // way to drain and restore
140}
141
142void
143TrafficGen::unserialize(Checkpoint* cp, const string& section)
144{
145    // restore scheduled events
146    Tick nextStateGraphEvent;
147    UNSERIALIZE_SCALAR(nextStateGraphEvent);
148    if (nextStateGraphEvent != 0) {
149        schedule(updateStateGraphEvent, nextStateGraphEvent);
150    }
151
152    Tick nextTransitionTick;
153    UNSERIALIZE_SCALAR(nextTransitionTick);
154    stateGraph.nextTransitionTick = nextTransitionTick;
155}
156
157void
158TrafficGen::updateStateGraph()
159{
160    // schedule next update event based on either the next execute
161    // tick or the next transition, which ever comes first
162    Tick nextStateGraphEvent = stateGraph.nextEventTick();
163    DPRINTF(TrafficGen, "Updating state graph, next event at %lld\n",
164            nextStateGraphEvent);
165    schedule(updateStateGraphEvent, nextStateGraphEvent);
166
167    // perform the update associated with the current update event
168    stateGraph.update();
169}
170
171void
172TrafficGen::StateGraph::parseConfig(const string& file_name,
173                                    MasterID master_id)
174{
175    // keep track of the transitions parsed to create the matrix when
176    // done
177    vector<Transition> transitions;
178
179    // open input file
180    ifstream infile;
181    infile.open(file_name.c_str(), ifstream::in);
182    if (!infile.is_open()) {
183        fatal("Traffic generator %s config file not found at %s\n",
184              owner.name(), file_name);
185    }
186
187    // read line by line and determine the action based on the first
188    // keyword
189    string keyword;
190    string line;
191
192    while (getline(infile, line).good()) {
193        // see if this line is a comment line, and if so skip it
194        if (line.find('#') != 1) {
195            // create an input stream for the tokenization
196            istringstream is(line);
197
198            // determine the keyword
199            is >> keyword;
200
201            if (keyword == "STATE") {
202                // parse the behaviour of this state
203                uint32_t id;
204                Tick duration;
205                string mode;
206
207                is >> id >> duration >> mode;
208
209                if (mode == "TRACE") {
210                    string traceFile;
211                    Addr addrOffset;
212
213                    is >> traceFile >> addrOffset;
214
215                    states[id] = new TraceGen(port, master_id, duration,
216                                              traceFile, addrOffset);
217                    DPRINTF(TrafficGen, "State: %d TraceGen\n", id);
218                } else if (mode == "IDLE") {
219                    states[id] = new IdleGen(port, master_id, duration);
220                    DPRINTF(TrafficGen, "State: %d IdleGen\n", id);
221                } else if (mode == "LINEAR" || mode == "RANDOM") {
222                    uint32_t read_percent;
223                    Addr start_addr;
224                    Addr end_addr;
225                    Addr blocksize;
226                    Tick min_period;
227                    Tick max_period;
228                    Addr data_limit;
229
230                    is >> read_percent >> start_addr >> end_addr >>
231                        blocksize >> min_period >> max_period >> data_limit;
232
233                    DPRINTF(TrafficGen, "%s, addr %x to %x, size %d,"
234                            " period %d to %d, %d%% reads\n",
235                            mode, start_addr, end_addr, blocksize, min_period,
236                            max_period, read_percent);
237
238                    if (read_percent > 100)
239                        panic("%s cannot have more than 100% reads", name());
240
241                    if (mode == "LINEAR") {
242                        states[id] = new LinearGen(port, master_id,
243                                                   duration, start_addr,
244                                                   end_addr, blocksize,
245                                                   min_period, max_period,
246                                                   read_percent, data_limit);
247                        DPRINTF(TrafficGen, "State: %d LinearGen\n", id);
248                    } else if (mode == "RANDOM") {
249                        states[id] = new RandomGen(port, master_id,
250                                                   duration, start_addr,
251                                                   end_addr, blocksize,
252                                                   min_period, max_period,
253                                                   read_percent, data_limit);
254                        DPRINTF(TrafficGen, "State: %d RandomGen\n", id);
255                    }
256                } else {
257                    fatal("%s: Unknown traffic generator mode: %s",
258                          name(), mode);
259                }
260            } else if (keyword == "TRANSITION") {
261                Transition transition;
262
263                is >> transition.from >> transition.to >> transition.p;
264
265                transitions.push_back(transition);
266
267                DPRINTF(TrafficGen, "Transition: %d -> %d\n", transition.from,
268                        transition.to);
269            } else if (keyword == "INIT") {
270                // set the initial state as the active state
271                is >> currState;
272
273                DPRINTF(TrafficGen, "Initial state: %d\n", currState);
274            }
275        }
276    }
277
278    // resize and populate state transition matrix
279    transitionMatrix.resize(transitions.size());
280    for (size_t i = 0; i < transitions.size(); i++) {
281        transitionMatrix[i].resize(transitions.size());
282    }
283
284    for (vector<Transition>::iterator t = transitions.begin();
285         t != transitions.end(); ++t) {
286        transitionMatrix[t->from][t->to] = t->p;
287    }
288
289    // ensure the egress edges do not have a probability larger than
290    // one
291    for (size_t i = 0; i < transitions.size(); i++) {
292        double sum = 0;
293        for (size_t j = 0; j < transitions.size(); j++) {
294            sum += transitionMatrix[i][j];
295        }
296
297        // avoid comparing floating point numbers
298        if (abs(sum - 1.0) > 0.001)
299            fatal("%s has transition probability != 1 for state %d\n",
300                  name(), i);
301    }
302
303    // close input file
304    infile.close();
305}
306
307void
308TrafficGen::StateGraph::update()
309{
310    // if we have reached the time for the next state transition, then
311    // perform the transition
312    if (curTick() >= nextTransitionTick) {
313        transition();
314    } else {
315        // we are still in the current state and should execute it
316        states[currState]->execute();
317    }
318}
319
320void
321TrafficGen::StateGraph::transition()
322{
323    // exit the current state
324    states[currState]->exit();
325
326    // determine next state
327    double p = random_mt.gen_real1();
328    assert(currState < transitionMatrix.size());
329    double cumulative = transitionMatrix[currState][0];
330    size_t i = 1;
331    while (p < cumulative && i != transitionMatrix[currState].size()) {
332        cumulative += transitionMatrix[currState][i];
333        ++i;
334    }
335    enterState(i);
336}
337
338void
339TrafficGen::StateGraph::enterState(uint32_t newState)
340{
341    DPRINTF(TrafficGen, "Transition to state %d\n", newState);
342
343    currState = newState;
344    nextTransitionTick += states[currState]->duration;
345    states[currState]->enter();
346}
347
348TrafficGen::StateGraph::BaseGen::BaseGen(QueuedMasterPort& _port,
349                                         MasterID master_id,
350                                         Tick _duration)
351    : port(_port), masterID(master_id), duration(_duration)
352{
353}
354
355void
356TrafficGen::StateGraph::LinearGen::enter()
357{
358    // reset the address and the data counter
359    nextAddr = startAddr;
360    dataManipulated = 0;
361
362    // this test only needs to happen once, but cannot be performed
363    // before init() is called and the ports are connected
364    if (port.deviceBlockSize() && blocksize > port.deviceBlockSize())
365        fatal("TrafficGen %s block size (%d) is larger than port"
366              " block size (%d)\n", blocksize, port.deviceBlockSize());
367
368}
369
370void
371TrafficGen::StateGraph::LinearGen::execute()
372{
373    // choose if we generate a read or a write here
374    bool isRead = readPercent != 0 &&
375        (readPercent == 100 || random_mt.random<uint8_t>(0, 100) < readPercent);
376
377    assert((readPercent == 0 && !isRead) || (readPercent == 100 && isRead) ||
378           readPercent != 100);
379
380    DPRINTF(TrafficGen, "LinearGen::execute: %c to addr %x, size %d\n",
381            isRead ? 'r' : 'w', nextAddr, blocksize);
382
383    // Create new request
384    Request::Flags flags;
385    Request *req = new Request(nextAddr, blocksize, flags, masterID);
386
387    PacketPtr pkt = new Packet(req, isRead ? MemCmd::ReadReq :
388                               MemCmd::WriteReq);
389
390    uint8_t* pkt_data = new uint8_t[req->getSize()];
391    pkt->dataDynamicArray(pkt_data);
392
393    if (!isRead) {
394        memset(pkt_data, 0xA, req->getSize());
395    }
396
397    port.schedTimingReq(pkt, curTick());
398
399    // increment the address
400    nextAddr += blocksize;
401
402    // Add the amount of data manipulated to the total
403    dataManipulated += blocksize;
404}
405
406Tick
407TrafficGen::StateGraph::LinearGen::nextExecuteTick()
408{
409    // If we have reached the end of the address space, reset the
410    // address to the start of the range
411    if (nextAddr + blocksize > endAddr) {
412        DPRINTF(TrafficGen, "Wrapping address to the start of "
413                "the range\n");
414        nextAddr = startAddr;
415    }
416
417    // Check to see if we have reached the data limit. If dataLimit is
418    // zero we do not have a data limit and therefore we will keep
419    // generating requests for the entire residency in this state.
420    if (dataLimit && dataManipulated >= dataLimit) {
421        DPRINTF(TrafficGen, "Data limit for LinearGen reached.\n");
422        // there are no more requests, therefore return MaxTick
423        return MaxTick;
424    } else {
425        // return the time when the next request should take place
426        return curTick() + random_mt.random<Tick>(minPeriod, maxPeriod);
427    }
428}
429
430void
431TrafficGen::StateGraph::RandomGen::enter()
432{
433    // reset the counter to zero
434    dataManipulated = 0;
435
436    // this test only needs to happen once, but cannot be performed
437    // before init() is called and the ports are connected
438    if (port.deviceBlockSize() && blocksize > port.deviceBlockSize())
439        fatal("TrafficGen %s block size (%d) is larger than port"
440              " block size (%d)\n", name(), blocksize, port.deviceBlockSize());
441}
442
443void
444TrafficGen::StateGraph::RandomGen::execute()
445{
446    // choose if we generate a read or a write here
447    bool isRead = readPercent != 0 &&
448        (readPercent == 100 || random_mt.random<uint8_t>(0, 100) < readPercent);
449
450    assert((readPercent == 0 && !isRead) || (readPercent == 100 && isRead) ||
451           readPercent != 100);
452
453    // address of the request
454    Addr addr = random_mt.random<Addr>(startAddr, endAddr - 1);
455
456    // round down to start address of block
457    addr -= addr % blocksize;
458
459    DPRINTF(TrafficGen, "RandomGen::execute: %c to addr %x, size %d\n",
460            isRead ? 'r' : 'w', addr, blocksize);
461
462    // create new request packet
463    Request::Flags flags;
464    Request *req = new Request(addr, blocksize, flags, masterID);
465
466    PacketPtr pkt = new Packet(req, isRead ? MemCmd::ReadReq :
467                               MemCmd::WriteReq);
468
469    uint8_t* pkt_data = new uint8_t[req->getSize()];
470    pkt->dataDynamicArray(pkt_data);
471
472    if (!isRead) {
473        memset(pkt_data, 0xA, req->getSize());
474    }
475
476    port.schedTimingReq(pkt, curTick());
477
478    // Add the amount of data manipulated to the total
479    dataManipulated += blocksize;
480}
481
482Tick
483TrafficGen::StateGraph::RandomGen::nextExecuteTick()
484{
485    // Check to see if we have reached the data limit. If dataLimit is
486    // zero we do not have a data limit and therefore we will keep
487    // generating requests for the entire residency in this state.
488    if (dataLimit && dataManipulated >= dataLimit)
489    {
490        DPRINTF(TrafficGen, "Data limit for RandomGen reached.\n");
491        // No more requests. Return MaxTick.
492        return MaxTick;
493    } else {
494        // Return the time when the next request should take place.
495        return curTick() + random_mt.random<Tick>(minPeriod, maxPeriod);
496    }
497}
498
499TrafficGen::StateGraph::TraceGen::InputStream::InputStream(const string&
500                                                           filename)
501    : trace(filename)
502{
503    // Create a protobuf message for the header and read it from the stream
504    Message::PacketHeader header_msg;
505    if (!trace.read(header_msg)) {
506        panic("Failed to read packet header from %s\n", filename);
507
508        if (header_msg.tick_freq() != SimClock::Frequency) {
509            panic("Trace %s was recorded with a different tick frequency %d\n",
510                  header_msg.tick_freq());
511        }
512    }
513}
514
515void
516TrafficGen::StateGraph::TraceGen::InputStream::reset()
517{
518    trace.reset();
519}
520
521bool
522TrafficGen::StateGraph::TraceGen::InputStream::read(TraceElement& element)
523{
524    Message::Packet pkt_msg;
525    if (trace.read(pkt_msg)) {
526        element.cmd = pkt_msg.cmd();
527        element.addr = pkt_msg.addr();
528        element.blocksize = pkt_msg.size();
529        element.tick = pkt_msg.tick();
530        return true;
531    }
532
533    // We have reached the end of the file
534    return false;
535}
536
537Tick
538TrafficGen::StateGraph::TraceGen::nextExecuteTick() {
539    if (traceComplete)
540        // We are at the end of the file, thus we have no more data in
541        // the trace Return MaxTick to signal that there will be no
542        // more transactions in this active period for the state.
543        return MaxTick;
544
545
546    //Reset the nextElement to the default values
547    currElement = nextElement;
548    nextElement.clear();
549
550    // We need to look at the next line to calculate the next time an
551    // event occurs, or potentially return MaxTick to signal that
552    // nothing has to be done.
553    if (!trace.read(nextElement)) {
554        traceComplete = true;
555        return MaxTick;
556    }
557
558    DPRINTF(TrafficGen, "currElement: %c addr %d size %d tick %d (%d)\n",
559            currElement.cmd.isRead() ? 'r' : 'w',
560            currElement.addr,
561            currElement.blocksize,
562            currElement.tick + tickOffset,
563            currElement.tick);
564
565    DPRINTF(TrafficGen, "nextElement: %c addr %d size %d tick %d (%d)\n",
566            nextElement.cmd.isRead() ? 'r' : 'w',
567            nextElement.addr,
568            nextElement.blocksize,
569            nextElement.tick + tickOffset,
570            nextElement.tick);
571
572    return tickOffset + nextElement.tick;
573}
574
575void
576TrafficGen::StateGraph::TraceGen::enter() {
577    // update the trace offset to the time where the state was entered.
578    tickOffset = curTick();
579
580    // clear everything
581    nextElement.clear();
582    currElement.clear();
583
584    traceComplete = false;
585}
586
587void
588TrafficGen::StateGraph::TraceGen::execute() {
589    // it is the responsibility of nextExecuteTick to prevent the
590    // state graph from executing the state if it should not
591    assert(currElement.isValid());
592
593    DPRINTF(TrafficGen, "TraceGen::execute: %c %d %d %d\n",
594            currElement.cmd.isRead() ? 'r' : 'w',
595            currElement.addr,
596            currElement.blocksize,
597            currElement.tick);
598
599    Request::Flags flags;
600    Request *req = new Request(currElement.addr + addrOffset,
601                               currElement.blocksize, flags, masterID);
602
603    PacketPtr pkt = new Packet(req, currElement.cmd);
604
605    uint8_t* pkt_data = new uint8_t[req->getSize()];
606    pkt->dataDynamicArray(pkt_data);
607
608    if (currElement.cmd.isWrite()) {
609        memset(pkt_data, 0xA, req->getSize());
610    }
611
612    port.schedTimingReq(pkt, curTick());
613}
614
615void
616TrafficGen::StateGraph::TraceGen::exit() {
617    // Check if we reached the end of the trace file. If we did not
618    // then we want to generate a warning stating that not the entire
619    // trace was played.
620    if (!traceComplete) {
621        warn("Trace player %s was unable to replay the entire trace!\n",
622             name());
623    }
624
625    // Clear any flags and start over again from the beginning of the
626    // file
627    trace.reset();
628}
629
630bool
631TrafficGen::TrafficGenPort::recvTimingResp(PacketPtr pkt)
632{
633    delete pkt->req;
634    delete pkt;
635
636    return true;
637}
638