traffic_gen.cc revision 9403:af9066bc088c
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::BaseGen::send(Addr addr, unsigned size,
357                                      const MemCmd& cmd)
358{
359    // Create new request
360    Request::Flags flags;
361    Request *req = new Request(addr, size, flags, masterID);
362
363    // Embed it in a packet
364    PacketPtr pkt = new Packet(req, cmd);
365
366    uint8_t* pkt_data = new uint8_t[req->getSize()];
367    pkt->dataDynamicArray(pkt_data);
368
369    if (cmd.isWrite()) {
370        memset(pkt_data, 0xA, req->getSize());
371    }
372
373    port.schedTimingReq(pkt, curTick());
374}
375
376void
377TrafficGen::StateGraph::LinearGen::enter()
378{
379    // reset the address and the data counter
380    nextAddr = startAddr;
381    dataManipulated = 0;
382
383    // this test only needs to happen once, but cannot be performed
384    // before init() is called and the ports are connected
385    if (port.deviceBlockSize() && blocksize > port.deviceBlockSize())
386        fatal("TrafficGen %s block size (%d) is larger than port"
387              " block size (%d)\n", blocksize, port.deviceBlockSize());
388
389}
390
391void
392TrafficGen::StateGraph::LinearGen::execute()
393{
394    // choose if we generate a read or a write here
395    bool isRead = readPercent != 0 &&
396        (readPercent == 100 || random_mt.random<uint8_t>(0, 100) < readPercent);
397
398    assert((readPercent == 0 && !isRead) || (readPercent == 100 && isRead) ||
399           readPercent != 100);
400
401    DPRINTF(TrafficGen, "LinearGen::execute: %c to addr %x, size %d\n",
402            isRead ? 'r' : 'w', nextAddr, blocksize);
403
404    send(nextAddr, blocksize, isRead ? MemCmd::ReadReq : MemCmd::WriteReq);
405
406    // increment the address
407    nextAddr += blocksize;
408
409    // Add the amount of data manipulated to the total
410    dataManipulated += blocksize;
411}
412
413Tick
414TrafficGen::StateGraph::LinearGen::nextExecuteTick()
415{
416    // If we have reached the end of the address space, reset the
417    // address to the start of the range
418    if (nextAddr + blocksize > endAddr) {
419        DPRINTF(TrafficGen, "Wrapping address to the start of "
420                "the range\n");
421        nextAddr = startAddr;
422    }
423
424    // Check to see if we have reached the data limit. If dataLimit is
425    // zero we do not have a data limit and therefore we will keep
426    // generating requests for the entire residency in this state.
427    if (dataLimit && dataManipulated >= dataLimit) {
428        DPRINTF(TrafficGen, "Data limit for LinearGen reached.\n");
429        // there are no more requests, therefore return MaxTick
430        return MaxTick;
431    } else {
432        // return the time when the next request should take place
433        return curTick() + random_mt.random<Tick>(minPeriod, maxPeriod);
434    }
435}
436
437void
438TrafficGen::StateGraph::RandomGen::enter()
439{
440    // reset the counter to zero
441    dataManipulated = 0;
442
443    // this test only needs to happen once, but cannot be performed
444    // before init() is called and the ports are connected
445    if (port.deviceBlockSize() && blocksize > port.deviceBlockSize())
446        fatal("TrafficGen %s block size (%d) is larger than port"
447              " block size (%d)\n", name(), blocksize, port.deviceBlockSize());
448}
449
450void
451TrafficGen::StateGraph::RandomGen::execute()
452{
453    // choose if we generate a read or a write here
454    bool isRead = readPercent != 0 &&
455        (readPercent == 100 || random_mt.random<uint8_t>(0, 100) < readPercent);
456
457    assert((readPercent == 0 && !isRead) || (readPercent == 100 && isRead) ||
458           readPercent != 100);
459
460    // address of the request
461    Addr addr = random_mt.random<Addr>(startAddr, endAddr - 1);
462
463    // round down to start address of block
464    addr -= addr % blocksize;
465
466    DPRINTF(TrafficGen, "RandomGen::execute: %c to addr %x, size %d\n",
467            isRead ? 'r' : 'w', addr, blocksize);
468
469    // send a new request packet
470    send(addr, blocksize, isRead ? MemCmd::ReadReq : MemCmd::WriteReq);
471
472    // Add the amount of data manipulated to the total
473    dataManipulated += blocksize;
474}
475
476Tick
477TrafficGen::StateGraph::RandomGen::nextExecuteTick()
478{
479    // Check to see if we have reached the data limit. If dataLimit is
480    // zero we do not have a data limit and therefore we will keep
481    // generating requests for the entire residency in this state.
482    if (dataLimit && dataManipulated >= dataLimit)
483    {
484        DPRINTF(TrafficGen, "Data limit for RandomGen reached.\n");
485        // No more requests. Return MaxTick.
486        return MaxTick;
487    } else {
488        // Return the time when the next request should take place.
489        return curTick() + random_mt.random<Tick>(minPeriod, maxPeriod);
490    }
491}
492
493TrafficGen::StateGraph::TraceGen::InputStream::InputStream(const string&
494                                                           filename)
495    : trace(filename)
496{
497    // Create a protobuf message for the header and read it from the stream
498    Message::PacketHeader header_msg;
499    if (!trace.read(header_msg)) {
500        panic("Failed to read packet header from %s\n", filename);
501
502        if (header_msg.tick_freq() != SimClock::Frequency) {
503            panic("Trace %s was recorded with a different tick frequency %d\n",
504                  header_msg.tick_freq());
505        }
506    }
507}
508
509void
510TrafficGen::StateGraph::TraceGen::InputStream::reset()
511{
512    trace.reset();
513}
514
515bool
516TrafficGen::StateGraph::TraceGen::InputStream::read(TraceElement& element)
517{
518    Message::Packet pkt_msg;
519    if (trace.read(pkt_msg)) {
520        element.cmd = pkt_msg.cmd();
521        element.addr = pkt_msg.addr();
522        element.blocksize = pkt_msg.size();
523        element.tick = pkt_msg.tick();
524        return true;
525    }
526
527    // We have reached the end of the file
528    return false;
529}
530
531Tick
532TrafficGen::StateGraph::TraceGen::nextExecuteTick() {
533    if (traceComplete)
534        // We are at the end of the file, thus we have no more data in
535        // the trace Return MaxTick to signal that there will be no
536        // more transactions in this active period for the state.
537        return MaxTick;
538
539
540    //Reset the nextElement to the default values
541    currElement = nextElement;
542    nextElement.clear();
543
544    // We need to look at the next line to calculate the next time an
545    // event occurs, or potentially return MaxTick to signal that
546    // nothing has to be done.
547    if (!trace.read(nextElement)) {
548        traceComplete = true;
549        return MaxTick;
550    }
551
552    DPRINTF(TrafficGen, "currElement: %c addr %d size %d tick %d (%d)\n",
553            currElement.cmd.isRead() ? 'r' : 'w',
554            currElement.addr,
555            currElement.blocksize,
556            currElement.tick + tickOffset,
557            currElement.tick);
558
559    DPRINTF(TrafficGen, "nextElement: %c addr %d size %d tick %d (%d)\n",
560            nextElement.cmd.isRead() ? 'r' : 'w',
561            nextElement.addr,
562            nextElement.blocksize,
563            nextElement.tick + tickOffset,
564            nextElement.tick);
565
566    return tickOffset + nextElement.tick;
567}
568
569void
570TrafficGen::StateGraph::TraceGen::enter() {
571    // update the trace offset to the time where the state was entered.
572    tickOffset = curTick();
573
574    // clear everything
575    nextElement.clear();
576    currElement.clear();
577
578    traceComplete = false;
579}
580
581void
582TrafficGen::StateGraph::TraceGen::execute() {
583    // it is the responsibility of nextExecuteTick to prevent the
584    // state graph from executing the state if it should not
585    assert(currElement.isValid());
586
587    DPRINTF(TrafficGen, "TraceGen::execute: %c %d %d %d\n",
588            currElement.cmd.isRead() ? 'r' : 'w',
589            currElement.addr,
590            currElement.blocksize,
591            currElement.tick);
592
593    send(currElement.addr + addrOffset, currElement.blocksize,
594         currElement.cmd);
595}
596
597void
598TrafficGen::StateGraph::TraceGen::exit() {
599    // Check if we reached the end of the trace file. If we did not
600    // then we want to generate a warning stating that not the entire
601    // trace was played.
602    if (!traceComplete) {
603        warn("Trace player %s was unable to replay the entire trace!\n",
604             name());
605    }
606
607    // Clear any flags and start over again from the beginning of the
608    // file
609    trace.reset();
610}
611
612bool
613TrafficGen::TrafficGenPort::recvTimingResp(PacketPtr pkt)
614{
615    delete pkt->req;
616    delete pkt;
617
618    return true;
619}
620