comm_monitor.cc revision 13784
1/*
2 * Copyright (c) 2012-2013, 2015, 2018 ARM Limited
3 * Copyright (c) 2016 Google Inc.
4 * Copyright (c) 2017, Centre National de la Recherche Scientifique
5 * All rights reserved.
6 *
7 * The license below extends only to copyright in the software and shall
8 * not be construed as granting a license to any other intellectual
9 * property including but not limited to intellectual property relating
10 * to a hardware implementation of the functionality of the software
11 * licensed hereunder.  You may use the software subject to the license
12 * terms below provided that you ensure that this notice is replicated
13 * unmodified and in its entirety in all distributions of the software,
14 * modified or unmodified, in source code or in binary form.
15 *
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions are
18 * met: redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer;
20 * redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution;
23 * neither the name of the copyright holders nor the names of its
24 * contributors may be used to endorse or promote products derived from
25 * this software without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 *
39 * Authors: Thomas Grass
40 *          Andreas Hansson
41 *          Rahul Thakur
42 *          Pierre-Yves Peneau
43 */
44
45#include "mem/comm_monitor.hh"
46
47#include "base/trace.hh"
48#include "debug/CommMonitor.hh"
49#include "sim/stats.hh"
50
51CommMonitor::CommMonitor(Params* params)
52    : MemObject(params),
53      masterPort(name() + "-master", *this),
54      slavePort(name() + "-slave", *this),
55      samplePeriodicEvent([this]{ samplePeriodic(); }, name()),
56      samplePeriodTicks(params->sample_period),
57      samplePeriod(params->sample_period / SimClock::Float::s),
58      stats(params)
59{
60    DPRINTF(CommMonitor,
61            "Created monitor %s with sample period %d ticks (%f ms)\n",
62            name(), samplePeriodTicks, samplePeriod * 1E3);
63}
64
65CommMonitor*
66CommMonitorParams::create()
67{
68    return new CommMonitor(this);
69}
70
71void
72CommMonitor::init()
73{
74    // make sure both sides of the monitor are connected
75    if (!slavePort.isConnected() || !masterPort.isConnected())
76        fatal("Communication monitor is not connected on both sides.\n");
77}
78
79void
80CommMonitor::regProbePoints()
81{
82    ppPktReq.reset(new ProbePoints::Packet(getProbeManager(), "PktRequest"));
83    ppPktResp.reset(new ProbePoints::Packet(getProbeManager(), "PktResponse"));
84}
85
86Port &
87CommMonitor::getPort(const std::string &if_name, PortID idx)
88{
89    if (if_name == "master") {
90        return masterPort;
91    } else if (if_name == "slave") {
92        return slavePort;
93    } else {
94        return MemObject::getPort(if_name, idx);
95    }
96}
97
98void
99CommMonitor::recvFunctional(PacketPtr pkt)
100{
101    masterPort.sendFunctional(pkt);
102}
103
104void
105CommMonitor::recvFunctionalSnoop(PacketPtr pkt)
106{
107    slavePort.sendFunctionalSnoop(pkt);
108}
109
110void
111CommMonitor::MonitorStats::updateReqStats(
112    const ProbePoints::PacketInfo& pkt_info, bool is_atomic,
113    bool expects_response)
114{
115    if (pkt_info.cmd.isRead()) {
116        // Increment number of observed read transactions
117        if (!disableTransactionHists)
118            ++readTrans;
119
120        // Get sample of burst length
121        if (!disableBurstLengthHists)
122            readBurstLengthHist.sample(pkt_info.size);
123
124        // Sample the masked address
125        if (!disableAddrDists)
126            readAddrDist.sample(pkt_info.addr & readAddrMask);
127
128        if (!disableITTDists) {
129            // Sample value of read-read inter transaction time
130            if (timeOfLastRead != 0)
131                ittReadRead.sample(curTick() - timeOfLastRead);
132            timeOfLastRead = curTick();
133
134            // Sample value of req-req inter transaction time
135            if (timeOfLastReq != 0)
136                ittReqReq.sample(curTick() - timeOfLastReq);
137            timeOfLastReq = curTick();
138        }
139        if (!is_atomic && !disableOutstandingHists && expects_response)
140            ++outstandingReadReqs;
141
142    } else if (pkt_info.cmd.isWrite()) {
143        // Same as for reads
144        if (!disableTransactionHists)
145            ++writeTrans;
146
147        if (!disableBurstLengthHists)
148            writeBurstLengthHist.sample(pkt_info.size);
149
150        // Update the bandwidth stats on the request
151        if (!disableBandwidthHists) {
152            writtenBytes += pkt_info.size;
153            totalWrittenBytes += pkt_info.size;
154        }
155
156        // Sample the masked write address
157        if (!disableAddrDists)
158            writeAddrDist.sample(pkt_info.addr & writeAddrMask);
159
160        if (!disableITTDists) {
161            // Sample value of write-to-write inter transaction time
162            if (timeOfLastWrite != 0)
163                ittWriteWrite.sample(curTick() - timeOfLastWrite);
164            timeOfLastWrite = curTick();
165
166            // Sample value of req-to-req inter transaction time
167            if (timeOfLastReq != 0)
168                ittReqReq.sample(curTick() - timeOfLastReq);
169            timeOfLastReq = curTick();
170        }
171
172        if (!is_atomic && !disableOutstandingHists && expects_response)
173            ++outstandingWriteReqs;
174    }
175}
176
177void
178CommMonitor::MonitorStats::updateRespStats(
179    const ProbePoints::PacketInfo& pkt_info, Tick latency, bool is_atomic)
180{
181    if (pkt_info.cmd.isRead()) {
182        // Decrement number of outstanding read requests
183        if (!is_atomic && !disableOutstandingHists) {
184            assert(outstandingReadReqs != 0);
185            --outstandingReadReqs;
186        }
187
188        if (!disableLatencyHists)
189            readLatencyHist.sample(latency);
190
191        // Update the bandwidth stats based on responses for reads
192        if (!disableBandwidthHists) {
193            readBytes += pkt_info.size;
194            totalReadBytes += pkt_info.size;
195        }
196
197    } else if (pkt_info.cmd.isWrite()) {
198        // Decrement number of outstanding write requests
199        if (!is_atomic && !disableOutstandingHists) {
200            assert(outstandingWriteReqs != 0);
201            --outstandingWriteReqs;
202        }
203
204        if (!disableLatencyHists)
205            writeLatencyHist.sample(latency);
206    }
207}
208
209Tick
210CommMonitor::recvAtomic(PacketPtr pkt)
211{
212    const bool expects_response(pkt->needsResponse() &&
213                                !pkt->cacheResponding());
214    ProbePoints::PacketInfo req_pkt_info(pkt);
215    ppPktReq->notify(req_pkt_info);
216
217    const Tick delay(masterPort.sendAtomic(pkt));
218
219    stats.updateReqStats(req_pkt_info, true, expects_response);
220    if (expects_response)
221        stats.updateRespStats(req_pkt_info, delay, true);
222
223    assert(pkt->isResponse());
224    ProbePoints::PacketInfo resp_pkt_info(pkt);
225    ppPktResp->notify(resp_pkt_info);
226    return delay;
227}
228
229Tick
230CommMonitor::recvAtomicSnoop(PacketPtr pkt)
231{
232    return slavePort.sendAtomicSnoop(pkt);
233}
234
235bool
236CommMonitor::recvTimingReq(PacketPtr pkt)
237{
238    // should always see a request
239    assert(pkt->isRequest());
240
241    // Store relevant fields of packet, because packet may be modified
242    // or even deleted when sendTiming() is called.
243    const ProbePoints::PacketInfo pkt_info(pkt);
244
245    const bool expects_response(pkt->needsResponse() &&
246                                !pkt->cacheResponding());
247
248    // If a cache miss is served by a cache, a monitor near the memory
249    // would see a request which needs a response, but this response
250    // would not come back from the memory. Therefore we additionally
251    // have to check the cacheResponding flag
252    if (expects_response && !stats.disableLatencyHists) {
253        pkt->pushSenderState(new CommMonitorSenderState(curTick()));
254    }
255
256    // Attempt to send the packet
257    bool successful = masterPort.sendTimingReq(pkt);
258
259    // If not successful, restore the sender state
260    if (!successful && expects_response && !stats.disableLatencyHists) {
261        delete pkt->popSenderState();
262    }
263
264    if (successful) {
265        ppPktReq->notify(pkt_info);
266    }
267
268    if (successful) {
269        DPRINTF(CommMonitor, "Forwarded %s request\n", pkt->isRead() ? "read" :
270                pkt->isWrite() ? "write" : "non read/write");
271        stats.updateReqStats(pkt_info, false, expects_response);
272    }
273    return successful;
274}
275
276bool
277CommMonitor::recvTimingResp(PacketPtr pkt)
278{
279    // should always see responses
280    assert(pkt->isResponse());
281
282    // Store relevant fields of packet, because packet may be modified
283    // or even deleted when sendTiming() is called.
284    const ProbePoints::PacketInfo pkt_info(pkt);
285
286    Tick latency = 0;
287    CommMonitorSenderState* received_state =
288        dynamic_cast<CommMonitorSenderState*>(pkt->senderState);
289
290    if (!stats.disableLatencyHists) {
291        // Restore initial sender state
292        if (received_state == NULL)
293            panic("Monitor got a response without monitor sender state\n");
294
295        // Restore the sate
296        pkt->senderState = received_state->predecessor;
297    }
298
299    // Attempt to send the packet
300    bool successful = slavePort.sendTimingResp(pkt);
301
302    if (!stats.disableLatencyHists) {
303        // If packet successfully send, sample value of latency,
304        // afterwards delete sender state, otherwise restore state
305        if (successful) {
306            latency = curTick() - received_state->transmitTime;
307            DPRINTF(CommMonitor, "Latency: %d\n", latency);
308            delete received_state;
309        } else {
310            // Don't delete anything and let the packet look like we
311            // did not touch it
312            pkt->senderState = received_state;
313        }
314    }
315
316    if (successful) {
317        ppPktResp->notify(pkt_info);
318        DPRINTF(CommMonitor, "Received %s response\n", pkt->isRead() ? "read" :
319                pkt->isWrite() ?  "write" : "non read/write");
320        stats.updateRespStats(pkt_info, latency, false);
321    }
322    return successful;
323}
324
325void
326CommMonitor::recvTimingSnoopReq(PacketPtr pkt)
327{
328    slavePort.sendTimingSnoopReq(pkt);
329}
330
331bool
332CommMonitor::recvTimingSnoopResp(PacketPtr pkt)
333{
334    return masterPort.sendTimingSnoopResp(pkt);
335}
336
337void
338CommMonitor::recvRetrySnoopResp()
339{
340    slavePort.sendRetrySnoopResp();
341}
342
343bool
344CommMonitor::isSnooping() const
345{
346    // check if the connected master port is snooping
347    return slavePort.isSnooping();
348}
349
350AddrRangeList
351CommMonitor::getAddrRanges() const
352{
353    // get the address ranges of the connected slave port
354    return masterPort.getAddrRanges();
355}
356
357void
358CommMonitor::recvReqRetry()
359{
360    slavePort.sendRetryReq();
361}
362
363void
364CommMonitor::recvRespRetry()
365{
366    masterPort.sendRetryResp();
367}
368
369bool
370CommMonitor::tryTiming(PacketPtr pkt)
371{
372    return masterPort.tryTiming(pkt);
373}
374
375void
376CommMonitor::recvRangeChange()
377{
378    slavePort.sendRangeChange();
379}
380
381void
382CommMonitor::regStats()
383{
384    MemObject::regStats();
385
386    // Initialise all the monitor stats
387    using namespace Stats;
388
389    stats.readBurstLengthHist
390        .init(params()->burst_length_bins)
391        .name(name() + ".readBurstLengthHist")
392        .desc("Histogram of burst lengths of transmitted packets")
393        .flags(stats.disableBurstLengthHists ? nozero : pdf);
394
395    stats.writeBurstLengthHist
396        .init(params()->burst_length_bins)
397        .name(name() + ".writeBurstLengthHist")
398        .desc("Histogram of burst lengths of transmitted packets")
399        .flags(stats.disableBurstLengthHists ? nozero : pdf);
400
401    // Stats based on received responses
402    stats.readBandwidthHist
403        .init(params()->bandwidth_bins)
404        .name(name() + ".readBandwidthHist")
405        .desc("Histogram of read bandwidth per sample period (bytes/s)")
406        .flags(stats.disableBandwidthHists ? nozero : pdf);
407
408    stats.averageReadBW
409        .name(name() + ".averageReadBandwidth")
410        .desc("Average read bandwidth (bytes/s)")
411        .flags(stats.disableBandwidthHists ? nozero : pdf);
412
413    stats.totalReadBytes
414        .name(name() + ".totalReadBytes")
415        .desc("Number of bytes read")
416        .flags(stats.disableBandwidthHists ? nozero : pdf);
417
418    stats.averageReadBW = stats.totalReadBytes / simSeconds;
419
420    // Stats based on successfully sent requests
421    stats.writeBandwidthHist
422        .init(params()->bandwidth_bins)
423        .name(name() + ".writeBandwidthHist")
424        .desc("Histogram of write bandwidth (bytes/s)")
425        .flags(stats.disableBandwidthHists ? (pdf | nozero) : pdf);
426
427    stats.averageWriteBW
428        .name(name() + ".averageWriteBandwidth")
429        .desc("Average write bandwidth (bytes/s)")
430        .flags(stats.disableBandwidthHists ? nozero : pdf);
431
432    stats.totalWrittenBytes
433        .name(name() + ".totalWrittenBytes")
434        .desc("Number of bytes written")
435        .flags(stats.disableBandwidthHists ? nozero : pdf);
436
437    stats.averageWriteBW = stats.totalWrittenBytes / simSeconds;
438
439    stats.readLatencyHist
440        .init(params()->latency_bins)
441        .name(name() + ".readLatencyHist")
442        .desc("Read request-response latency")
443        .flags(stats.disableLatencyHists ? nozero : pdf);
444
445    stats.writeLatencyHist
446        .init(params()->latency_bins)
447        .name(name() + ".writeLatencyHist")
448        .desc("Write request-response latency")
449        .flags(stats.disableLatencyHists ? nozero : pdf);
450
451    stats.ittReadRead
452        .init(1, params()->itt_max_bin, params()->itt_max_bin /
453              params()->itt_bins)
454        .name(name() + ".ittReadRead")
455        .desc("Read-to-read inter transaction time")
456        .flags(stats.disableITTDists ? nozero : pdf);
457
458    stats.ittWriteWrite
459        .init(1, params()->itt_max_bin, params()->itt_max_bin /
460              params()->itt_bins)
461        .name(name() + ".ittWriteWrite")
462        .desc("Write-to-write inter transaction time")
463        .flags(stats.disableITTDists ? nozero : pdf);
464
465    stats.ittReqReq
466        .init(1, params()->itt_max_bin, params()->itt_max_bin /
467              params()->itt_bins)
468        .name(name() + ".ittReqReq")
469        .desc("Request-to-request inter transaction time")
470        .flags(stats.disableITTDists ? nozero : pdf);
471
472    stats.outstandingReadsHist
473        .init(params()->outstanding_bins)
474        .name(name() + ".outstandingReadsHist")
475        .desc("Outstanding read transactions")
476        .flags(stats.disableOutstandingHists ? nozero : pdf);
477
478    stats.outstandingWritesHist
479        .init(params()->outstanding_bins)
480        .name(name() + ".outstandingWritesHist")
481        .desc("Outstanding write transactions")
482        .flags(stats.disableOutstandingHists ? nozero : pdf);
483
484    stats.readTransHist
485        .init(params()->transaction_bins)
486        .name(name() + ".readTransHist")
487        .desc("Histogram of read transactions per sample period")
488        .flags(stats.disableTransactionHists ? nozero : pdf);
489
490    stats.writeTransHist
491        .init(params()->transaction_bins)
492        .name(name() + ".writeTransHist")
493        .desc("Histogram of write transactions per sample period")
494        .flags(stats.disableTransactionHists ? nozero : pdf);
495
496    stats.readAddrDist
497        .init(0)
498        .name(name() + ".readAddrDist")
499        .desc("Read address distribution")
500        .flags(stats.disableAddrDists ? nozero : pdf);
501
502    stats.writeAddrDist
503        .init(0)
504        .name(name() + ".writeAddrDist")
505        .desc("Write address distribution")
506        .flags(stats.disableAddrDists ? nozero : pdf);
507}
508
509void
510CommMonitor::samplePeriodic()
511{
512    // the periodic stats update runs on the granularity of sample
513    // periods, but in combination with this there may also be a
514    // external resets and dumps of the stats (through schedStatEvent)
515    // causing the stats themselves to capture less than a sample
516    // period
517
518    // only capture if we have not reset the stats during the last
519    // sample period
520    if (simTicks.value() >= samplePeriodTicks) {
521        if (!stats.disableTransactionHists) {
522            stats.readTransHist.sample(stats.readTrans);
523            stats.writeTransHist.sample(stats.writeTrans);
524        }
525
526        if (!stats.disableBandwidthHists) {
527            stats.readBandwidthHist.sample(stats.readBytes / samplePeriod);
528            stats.writeBandwidthHist.sample(stats.writtenBytes / samplePeriod);
529        }
530
531        if (!stats.disableOutstandingHists) {
532            stats.outstandingReadsHist.sample(stats.outstandingReadReqs);
533            stats.outstandingWritesHist.sample(stats.outstandingWriteReqs);
534        }
535    }
536
537    // reset the sampled values
538    stats.readTrans = 0;
539    stats.writeTrans = 0;
540
541    stats.readBytes = 0;
542    stats.writtenBytes = 0;
543
544    schedule(samplePeriodicEvent, curTick() + samplePeriodTicks);
545}
546
547void
548CommMonitor::startup()
549{
550    schedule(samplePeriodicEvent, curTick() + samplePeriodTicks);
551}
552