coherent_xbar.cc revision 11196:53d4f7e452d6
1/*
2 * Copyright (c) 2011-2015 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 * Copyright (c) 2006 The Regents of The University of Michigan
15 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *
40 * Authors: Ali Saidi
41 *          Andreas Hansson
42 *          William Wang
43 */
44
45/**
46 * @file
47 * Definition of a crossbar object.
48 */
49
50#include "base/misc.hh"
51#include "base/trace.hh"
52#include "debug/AddrRanges.hh"
53#include "debug/CoherentXBar.hh"
54#include "mem/coherent_xbar.hh"
55#include "sim/system.hh"
56
57CoherentXBar::CoherentXBar(const CoherentXBarParams *p)
58    : BaseXBar(p), system(p->system), snoopFilter(p->snoop_filter),
59      snoopResponseLatency(p->snoop_response_latency)
60{
61    // create the ports based on the size of the master and slave
62    // vector ports, and the presence of the default port, the ports
63    // are enumerated starting from zero
64    for (int i = 0; i < p->port_master_connection_count; ++i) {
65        std::string portName = csprintf("%s.master[%d]", name(), i);
66        MasterPort* bp = new CoherentXBarMasterPort(portName, *this, i);
67        masterPorts.push_back(bp);
68        reqLayers.push_back(new ReqLayer(*bp, *this,
69                                         csprintf(".reqLayer%d", i)));
70        snoopLayers.push_back(new SnoopRespLayer(*bp, *this,
71                                                 csprintf(".snoopLayer%d", i)));
72    }
73
74    // see if we have a default slave device connected and if so add
75    // our corresponding master port
76    if (p->port_default_connection_count) {
77        defaultPortID = masterPorts.size();
78        std::string portName = name() + ".default";
79        MasterPort* bp = new CoherentXBarMasterPort(portName, *this,
80                                                   defaultPortID);
81        masterPorts.push_back(bp);
82        reqLayers.push_back(new ReqLayer(*bp, *this, csprintf(".reqLayer%d",
83                                             defaultPortID)));
84        snoopLayers.push_back(new SnoopRespLayer(*bp, *this,
85                                                 csprintf(".snoopLayer%d",
86                                                          defaultPortID)));
87    }
88
89    // create the slave ports, once again starting at zero
90    for (int i = 0; i < p->port_slave_connection_count; ++i) {
91        std::string portName = csprintf("%s.slave[%d]", name(), i);
92        QueuedSlavePort* bp = new CoherentXBarSlavePort(portName, *this, i);
93        slavePorts.push_back(bp);
94        respLayers.push_back(new RespLayer(*bp, *this,
95                                           csprintf(".respLayer%d", i)));
96        snoopRespPorts.push_back(new SnoopRespPort(*bp, *this));
97    }
98
99    clearPortCache();
100}
101
102CoherentXBar::~CoherentXBar()
103{
104    for (auto l: reqLayers)
105        delete l;
106    for (auto l: respLayers)
107        delete l;
108    for (auto l: snoopLayers)
109        delete l;
110    for (auto p: snoopRespPorts)
111        delete p;
112}
113
114void
115CoherentXBar::init()
116{
117    // the base class is responsible for determining the block size
118    BaseXBar::init();
119
120    // iterate over our slave ports and determine which of our
121    // neighbouring master ports are snooping and add them as snoopers
122    for (const auto& p: slavePorts) {
123        // check if the connected master port is snooping
124        if (p->isSnooping()) {
125            DPRINTF(AddrRanges, "Adding snooping master %s\n",
126                    p->getMasterPort().name());
127            snoopPorts.push_back(p);
128        }
129    }
130
131    if (snoopPorts.empty())
132        warn("CoherentXBar %s has no snooping ports attached!\n", name());
133
134    // inform the snoop filter about the slave ports so it can create
135    // its own internal representation
136    if (snoopFilter)
137        snoopFilter->setSlavePorts(slavePorts);
138}
139
140bool
141CoherentXBar::recvTimingReq(PacketPtr pkt, PortID slave_port_id)
142{
143    // determine the source port based on the id
144    SlavePort *src_port = slavePorts[slave_port_id];
145
146    // remember if the packet is an express snoop
147    bool is_express_snoop = pkt->isExpressSnoop();
148    bool is_inhibited = pkt->memInhibitAsserted();
149    // for normal requests, going downstream, the express snoop flag
150    // and the inhibited flag should always be the same
151    assert(is_express_snoop == is_inhibited);
152
153    // determine the destination based on the address
154    PortID master_port_id = findPort(pkt->getAddr());
155
156    // test if the crossbar should be considered occupied for the current
157    // port, and exclude express snoops from the check
158    if (!is_express_snoop && !reqLayers[master_port_id]->tryTiming(src_port)) {
159        DPRINTF(CoherentXBar, "recvTimingReq: src %s %s 0x%x BUSY\n",
160                src_port->name(), pkt->cmdString(), pkt->getAddr());
161        return false;
162    }
163
164    DPRINTF(CoherentXBar, "recvTimingReq: src %s %s expr %d 0x%x\n",
165            src_port->name(), pkt->cmdString(), is_express_snoop,
166            pkt->getAddr());
167
168    // store size and command as they might be modified when
169    // forwarding the packet
170    unsigned int pkt_size = pkt->hasData() ? pkt->getSize() : 0;
171    unsigned int pkt_cmd = pkt->cmdToIndex();
172
173    // store the old header delay so we can restore it if needed
174    Tick old_header_delay = pkt->headerDelay;
175
176    // a request sees the frontend and forward latency
177    Tick xbar_delay = (frontendLatency + forwardLatency) * clockPeriod();
178
179    // set the packet header and payload delay
180    calcPacketTiming(pkt, xbar_delay);
181
182    // determine how long to be crossbar layer is busy
183    Tick packetFinishTime = clockEdge(Cycles(1)) + pkt->payloadDelay;
184
185    if (!system->bypassCaches()) {
186        assert(pkt->snoopDelay == 0);
187
188        // the packet is a memory-mapped request and should be
189        // broadcasted to our snoopers but the source
190        if (snoopFilter) {
191            // check with the snoop filter where to forward this packet
192            auto sf_res = snoopFilter->lookupRequest(pkt, *src_port);
193            // the time required by a packet to be delivered through
194            // the xbar has to be charged also with to lookup latency
195            // of the snoop filter
196            pkt->headerDelay += sf_res.second * clockPeriod();
197            DPRINTF(CoherentXBar, "recvTimingReq: src %s %s 0x%x"\
198                    " SF size: %i lat: %i\n", src_port->name(),
199                    pkt->cmdString(), pkt->getAddr(), sf_res.first.size(),
200                    sf_res.second);
201
202            if (pkt->evictingBlock()) {
203                // for block-evicting packets, i.e. writebacks and
204                // clean evictions, there is no need to snoop up, as
205                // all we do is determine if the block is cached or
206                // not, instead just set it here based on the snoop
207                // filter result
208                if (!sf_res.first.empty())
209                    pkt->setBlockCached();
210            } else {
211                forwardTiming(pkt, slave_port_id, sf_res.first);
212            }
213        } else {
214            forwardTiming(pkt, slave_port_id);
215        }
216
217        // add the snoop delay to our header delay, and then reset it
218        pkt->headerDelay += pkt->snoopDelay;
219        pkt->snoopDelay = 0;
220    }
221
222    // forwardTiming snooped into peer caches of the sender, and if
223    // this is a clean evict, but the packet is found in a cache, do
224    // not forward it
225    if (pkt->cmd == MemCmd::CleanEvict && pkt->isBlockCached()) {
226        DPRINTF(CoherentXBar, "recvTimingReq: Clean evict 0x%x still cached, "
227                "not forwarding\n", pkt->getAddr());
228
229        // update the layer state and schedule an idle event
230        reqLayers[master_port_id]->succeededTiming(packetFinishTime);
231
232        // queue the packet for deletion
233        pendingDelete.reset(pkt);
234
235        return true;
236    }
237
238    // remember if the packet will generate a snoop response
239    const bool expect_snoop_resp = !is_inhibited && pkt->memInhibitAsserted();
240    const bool expect_response = pkt->needsResponse() &&
241        !pkt->memInhibitAsserted();
242
243    // since it is a normal request, attempt to send the packet
244    bool success = masterPorts[master_port_id]->sendTimingReq(pkt);
245
246    if (snoopFilter && !system->bypassCaches()) {
247        // Let the snoop filter know about the success of the send operation
248        snoopFilter->finishRequest(!success, pkt);
249    }
250
251    // check if we were successful in sending the packet onwards
252    if (!success)  {
253        // express snoops and inhibited packets should never be forced
254        // to retry
255        assert(!is_express_snoop);
256        assert(!pkt->memInhibitAsserted());
257
258        // restore the header delay
259        pkt->headerDelay = old_header_delay;
260
261        DPRINTF(CoherentXBar, "recvTimingReq: src %s %s 0x%x RETRY\n",
262                src_port->name(), pkt->cmdString(), pkt->getAddr());
263
264        // update the layer state and schedule an idle event
265        reqLayers[master_port_id]->failedTiming(src_port,
266                                                clockEdge(Cycles(1)));
267    } else {
268        // express snoops currently bypass the crossbar state entirely
269        if (!is_express_snoop) {
270            // if this particular request will generate a snoop
271            // response
272            if (expect_snoop_resp) {
273                // we should never have an exsiting request outstanding
274                assert(outstandingSnoop.find(pkt->req) ==
275                       outstandingSnoop.end());
276                outstandingSnoop.insert(pkt->req);
277
278                // basic sanity check on the outstanding snoops
279                panic_if(outstandingSnoop.size() > 512,
280                         "Outstanding snoop requests exceeded 512\n");
281            }
282
283            // remember where to route the normal response to
284            if (expect_response || expect_snoop_resp) {
285                assert(routeTo.find(pkt->req) == routeTo.end());
286                routeTo[pkt->req] = slave_port_id;
287
288                panic_if(routeTo.size() > 512,
289                         "Routing table exceeds 512 packets\n");
290            }
291
292            // update the layer state and schedule an idle event
293            reqLayers[master_port_id]->succeededTiming(packetFinishTime);
294        }
295
296        // stats updates only consider packets that were successfully sent
297        pktCount[slave_port_id][master_port_id]++;
298        pktSize[slave_port_id][master_port_id] += pkt_size;
299        transDist[pkt_cmd]++;
300
301        if (is_express_snoop)
302            snoops++;
303    }
304
305    return success;
306}
307
308bool
309CoherentXBar::recvTimingResp(PacketPtr pkt, PortID master_port_id)
310{
311    // determine the source port based on the id
312    MasterPort *src_port = masterPorts[master_port_id];
313
314    // determine the destination
315    const auto route_lookup = routeTo.find(pkt->req);
316    assert(route_lookup != routeTo.end());
317    const PortID slave_port_id = route_lookup->second;
318    assert(slave_port_id != InvalidPortID);
319    assert(slave_port_id < respLayers.size());
320
321    // test if the crossbar should be considered occupied for the
322    // current port
323    if (!respLayers[slave_port_id]->tryTiming(src_port)) {
324        DPRINTF(CoherentXBar, "recvTimingResp: src %s %s 0x%x BUSY\n",
325                src_port->name(), pkt->cmdString(), pkt->getAddr());
326        return false;
327    }
328
329    DPRINTF(CoherentXBar, "recvTimingResp: src %s %s 0x%x\n",
330            src_port->name(), pkt->cmdString(), pkt->getAddr());
331
332    // store size and command as they might be modified when
333    // forwarding the packet
334    unsigned int pkt_size = pkt->hasData() ? pkt->getSize() : 0;
335    unsigned int pkt_cmd = pkt->cmdToIndex();
336
337    // a response sees the response latency
338    Tick xbar_delay = responseLatency * clockPeriod();
339
340    // set the packet header and payload delay
341    calcPacketTiming(pkt, xbar_delay);
342
343    // determine how long to be crossbar layer is busy
344    Tick packetFinishTime = clockEdge(Cycles(1)) + pkt->payloadDelay;
345
346    if (snoopFilter && !system->bypassCaches()) {
347        // let the snoop filter inspect the response and update its state
348        snoopFilter->updateResponse(pkt, *slavePorts[slave_port_id]);
349    }
350
351    // send the packet through the destination slave port and pay for
352    // any outstanding header delay
353    Tick latency = pkt->headerDelay;
354    pkt->headerDelay = 0;
355    slavePorts[slave_port_id]->schedTimingResp(pkt, curTick() + latency);
356
357    // remove the request from the routing table
358    routeTo.erase(route_lookup);
359
360    respLayers[slave_port_id]->succeededTiming(packetFinishTime);
361
362    // stats updates
363    pktCount[slave_port_id][master_port_id]++;
364    pktSize[slave_port_id][master_port_id] += pkt_size;
365    transDist[pkt_cmd]++;
366
367    return true;
368}
369
370void
371CoherentXBar::recvTimingSnoopReq(PacketPtr pkt, PortID master_port_id)
372{
373    DPRINTF(CoherentXBar, "recvTimingSnoopReq: src %s %s 0x%x\n",
374            masterPorts[master_port_id]->name(), pkt->cmdString(),
375            pkt->getAddr());
376
377    // update stats here as we know the forwarding will succeed
378    transDist[pkt->cmdToIndex()]++;
379    snoops++;
380
381    // we should only see express snoops from caches
382    assert(pkt->isExpressSnoop());
383
384    // set the packet header and payload delay, for now use forward latency
385    // @todo Assess the choice of latency further
386    calcPacketTiming(pkt, forwardLatency * clockPeriod());
387
388    // remeber if the packet is inhibited so we can see if it changes
389    const bool is_inhibited = pkt->memInhibitAsserted();
390
391    assert(pkt->snoopDelay == 0);
392
393    if (snoopFilter) {
394        // let the Snoop Filter work its magic and guide probing
395        auto sf_res = snoopFilter->lookupSnoop(pkt);
396        // the time required by a packet to be delivered through
397        // the xbar has to be charged also with to lookup latency
398        // of the snoop filter
399        pkt->headerDelay += sf_res.second * clockPeriod();
400        DPRINTF(CoherentXBar, "recvTimingSnoopReq: src %s %s 0x%x"\
401                " SF size: %i lat: %i\n", masterPorts[master_port_id]->name(),
402                pkt->cmdString(), pkt->getAddr(), sf_res.first.size(),
403                sf_res.second);
404
405        // forward to all snoopers
406        forwardTiming(pkt, InvalidPortID, sf_res.first);
407    } else {
408        forwardTiming(pkt, InvalidPortID);
409    }
410
411    // add the snoop delay to our header delay, and then reset it
412    pkt->headerDelay += pkt->snoopDelay;
413    pkt->snoopDelay = 0;
414
415    // if we can expect a response, remember how to route it
416    if (!is_inhibited && pkt->memInhibitAsserted()) {
417        assert(routeTo.find(pkt->req) == routeTo.end());
418        routeTo[pkt->req] = master_port_id;
419    }
420
421    // a snoop request came from a connected slave device (one of
422    // our master ports), and if it is not coming from the slave
423    // device responsible for the address range something is
424    // wrong, hence there is nothing further to do as the packet
425    // would be going back to where it came from
426    assert(master_port_id == findPort(pkt->getAddr()));
427}
428
429bool
430CoherentXBar::recvTimingSnoopResp(PacketPtr pkt, PortID slave_port_id)
431{
432    // determine the source port based on the id
433    SlavePort* src_port = slavePorts[slave_port_id];
434
435    // get the destination
436    const auto route_lookup = routeTo.find(pkt->req);
437    assert(route_lookup != routeTo.end());
438    const PortID dest_port_id = route_lookup->second;
439    assert(dest_port_id != InvalidPortID);
440
441    // determine if the response is from a snoop request we
442    // created as the result of a normal request (in which case it
443    // should be in the outstandingSnoop), or if we merely forwarded
444    // someone else's snoop request
445    const bool forwardAsSnoop = outstandingSnoop.find(pkt->req) ==
446        outstandingSnoop.end();
447
448    // test if the crossbar should be considered occupied for the
449    // current port, note that the check is bypassed if the response
450    // is being passed on as a normal response since this is occupying
451    // the response layer rather than the snoop response layer
452    if (forwardAsSnoop) {
453        assert(dest_port_id < snoopLayers.size());
454        if (!snoopLayers[dest_port_id]->tryTiming(src_port)) {
455            DPRINTF(CoherentXBar, "recvTimingSnoopResp: src %s %s 0x%x BUSY\n",
456                    src_port->name(), pkt->cmdString(), pkt->getAddr());
457            return false;
458        }
459    } else {
460        // get the master port that mirrors this slave port internally
461        MasterPort* snoop_port = snoopRespPorts[slave_port_id];
462        assert(dest_port_id < respLayers.size());
463        if (!respLayers[dest_port_id]->tryTiming(snoop_port)) {
464            DPRINTF(CoherentXBar, "recvTimingSnoopResp: src %s %s 0x%x BUSY\n",
465                    snoop_port->name(), pkt->cmdString(), pkt->getAddr());
466            return false;
467        }
468    }
469
470    DPRINTF(CoherentXBar, "recvTimingSnoopResp: src %s %s 0x%x\n",
471            src_port->name(), pkt->cmdString(), pkt->getAddr());
472
473    // store size and command as they might be modified when
474    // forwarding the packet
475    unsigned int pkt_size = pkt->hasData() ? pkt->getSize() : 0;
476    unsigned int pkt_cmd = pkt->cmdToIndex();
477
478    // responses are never express snoops
479    assert(!pkt->isExpressSnoop());
480
481    // a snoop response sees the snoop response latency, and if it is
482    // forwarded as a normal response, the response latency
483    Tick xbar_delay =
484        (forwardAsSnoop ? snoopResponseLatency : responseLatency) *
485        clockPeriod();
486
487    // set the packet header and payload delay
488    calcPacketTiming(pkt, xbar_delay);
489
490    // determine how long to be crossbar layer is busy
491    Tick packetFinishTime = clockEdge(Cycles(1)) + pkt->payloadDelay;
492
493    // forward it either as a snoop response or a normal response
494    if (forwardAsSnoop) {
495        // this is a snoop response to a snoop request we forwarded,
496        // e.g. coming from the L1 and going to the L2, and it should
497        // be forwarded as a snoop response
498
499        if (snoopFilter) {
500            // update the probe filter so that it can properly track the line
501            snoopFilter->updateSnoopForward(pkt, *slavePorts[slave_port_id],
502                                            *masterPorts[dest_port_id]);
503        }
504
505        bool success M5_VAR_USED =
506            masterPorts[dest_port_id]->sendTimingSnoopResp(pkt);
507        pktCount[slave_port_id][dest_port_id]++;
508        pktSize[slave_port_id][dest_port_id] += pkt_size;
509        assert(success);
510
511        snoopLayers[dest_port_id]->succeededTiming(packetFinishTime);
512    } else {
513        // we got a snoop response on one of our slave ports,
514        // i.e. from a coherent master connected to the crossbar, and
515        // since we created the snoop request as part of recvTiming,
516        // this should now be a normal response again
517        outstandingSnoop.erase(pkt->req);
518
519        // this is a snoop response from a coherent master, hence it
520        // should never go back to where the snoop response came from,
521        // but instead to where the original request came from
522        assert(slave_port_id != dest_port_id);
523
524        if (snoopFilter) {
525            // update the probe filter so that it can properly track the line
526            snoopFilter->updateSnoopResponse(pkt, *slavePorts[slave_port_id],
527                                    *slavePorts[dest_port_id]);
528        }
529
530        DPRINTF(CoherentXBar, "recvTimingSnoopResp: src %s %s 0x%x"\
531                " FWD RESP\n", src_port->name(), pkt->cmdString(),
532                pkt->getAddr());
533
534        // as a normal response, it should go back to a master through
535        // one of our slave ports, we also pay for any outstanding
536        // header latency
537        Tick latency = pkt->headerDelay;
538        pkt->headerDelay = 0;
539        slavePorts[dest_port_id]->schedTimingResp(pkt, curTick() + latency);
540
541        respLayers[dest_port_id]->succeededTiming(packetFinishTime);
542    }
543
544    // remove the request from the routing table
545    routeTo.erase(route_lookup);
546
547    // stats updates
548    transDist[pkt_cmd]++;
549    snoops++;
550
551    return true;
552}
553
554
555void
556CoherentXBar::forwardTiming(PacketPtr pkt, PortID exclude_slave_port_id,
557                           const std::vector<QueuedSlavePort*>& dests)
558{
559    DPRINTF(CoherentXBar, "%s for %s address %x size %d\n", __func__,
560            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
561
562    // snoops should only happen if the system isn't bypassing caches
563    assert(!system->bypassCaches());
564
565    unsigned fanout = 0;
566
567    for (const auto& p: dests) {
568        // we could have gotten this request from a snooping master
569        // (corresponding to our own slave port that is also in
570        // snoopPorts) and should not send it back to where it came
571        // from
572        if (exclude_slave_port_id == InvalidPortID ||
573            p->getId() != exclude_slave_port_id) {
574            // cache is not allowed to refuse snoop
575            p->sendTimingSnoopReq(pkt);
576            fanout++;
577        }
578    }
579
580    // Stats for fanout of this forward operation
581    snoopFanout.sample(fanout);
582}
583
584void
585CoherentXBar::recvReqRetry(PortID master_port_id)
586{
587    // responses and snoop responses never block on forwarding them,
588    // so the retry will always be coming from a port to which we
589    // tried to forward a request
590    reqLayers[master_port_id]->recvRetry();
591}
592
593Tick
594CoherentXBar::recvAtomic(PacketPtr pkt, PortID slave_port_id)
595{
596    DPRINTF(CoherentXBar, "recvAtomic: packet src %s addr 0x%x cmd %s\n",
597            slavePorts[slave_port_id]->name(), pkt->getAddr(),
598            pkt->cmdString());
599
600    unsigned int pkt_size = pkt->hasData() ? pkt->getSize() : 0;
601    unsigned int pkt_cmd = pkt->cmdToIndex();
602
603    MemCmd snoop_response_cmd = MemCmd::InvalidCmd;
604    Tick snoop_response_latency = 0;
605
606    if (!system->bypassCaches()) {
607        // forward to all snoopers but the source
608        std::pair<MemCmd, Tick> snoop_result;
609        if (snoopFilter) {
610            // check with the snoop filter where to forward this packet
611            auto sf_res =
612                snoopFilter->lookupRequest(pkt, *slavePorts[slave_port_id]);
613            snoop_response_latency += sf_res.second * clockPeriod();
614            DPRINTF(CoherentXBar, "%s: src %s %s 0x%x"\
615                    " SF size: %i lat: %i\n", __func__,
616                    slavePorts[slave_port_id]->name(), pkt->cmdString(),
617                    pkt->getAddr(), sf_res.first.size(), sf_res.second);
618
619            // let the snoop filter know about the success of the send
620            // operation, and do it even before sending it onwards to
621            // avoid situations where atomic upward snoops sneak in
622            // between and change the filter state
623            snoopFilter->finishRequest(false, pkt);
624
625            snoop_result = forwardAtomic(pkt, slave_port_id, InvalidPortID,
626                                         sf_res.first);
627        } else {
628            snoop_result = forwardAtomic(pkt, slave_port_id);
629        }
630        snoop_response_cmd = snoop_result.first;
631        snoop_response_latency += snoop_result.second;
632    }
633
634    // forwardAtomic snooped into peer caches of the sender, and if
635    // this is a clean evict, but the packet is found in a cache, do
636    // not forward it
637    if (pkt->cmd == MemCmd::CleanEvict && pkt->isBlockCached()) {
638        DPRINTF(CoherentXBar, "recvAtomic: Clean evict 0x%x still cached, "
639                "not forwarding\n", pkt->getAddr());
640        return 0;
641    }
642
643    // even if we had a snoop response, we must continue and also
644    // perform the actual request at the destination
645    PortID master_port_id = findPort(pkt->getAddr());
646
647    // stats updates for the request
648    pktCount[slave_port_id][master_port_id]++;
649    pktSize[slave_port_id][master_port_id] += pkt_size;
650    transDist[pkt_cmd]++;
651
652    // forward the request to the appropriate destination
653    Tick response_latency = masterPorts[master_port_id]->sendAtomic(pkt);
654
655    // if lower levels have replied, tell the snoop filter
656    if (!system->bypassCaches() && snoopFilter && pkt->isResponse()) {
657        snoopFilter->updateResponse(pkt, *slavePorts[slave_port_id]);
658    }
659
660    // if we got a response from a snooper, restore it here
661    if (snoop_response_cmd != MemCmd::InvalidCmd) {
662        // no one else should have responded
663        assert(!pkt->isResponse());
664        pkt->cmd = snoop_response_cmd;
665        response_latency = snoop_response_latency;
666    }
667
668    // add the response data
669    if (pkt->isResponse()) {
670        pkt_size = pkt->hasData() ? pkt->getSize() : 0;
671        pkt_cmd = pkt->cmdToIndex();
672
673        // stats updates
674        pktCount[slave_port_id][master_port_id]++;
675        pktSize[slave_port_id][master_port_id] += pkt_size;
676        transDist[pkt_cmd]++;
677    }
678
679    // @todo: Not setting header time
680    pkt->payloadDelay = response_latency;
681    return response_latency;
682}
683
684Tick
685CoherentXBar::recvAtomicSnoop(PacketPtr pkt, PortID master_port_id)
686{
687    DPRINTF(CoherentXBar, "recvAtomicSnoop: packet src %s addr 0x%x cmd %s\n",
688            masterPorts[master_port_id]->name(), pkt->getAddr(),
689            pkt->cmdString());
690
691    // add the request snoop data
692    snoops++;
693
694    // forward to all snoopers
695    std::pair<MemCmd, Tick> snoop_result;
696    Tick snoop_response_latency = 0;
697    if (snoopFilter) {
698        auto sf_res = snoopFilter->lookupSnoop(pkt);
699        snoop_response_latency += sf_res.second * clockPeriod();
700        DPRINTF(CoherentXBar, "%s: src %s %s 0x%x SF size: %i lat: %i\n",
701                __func__, masterPorts[master_port_id]->name(), pkt->cmdString(),
702                pkt->getAddr(), sf_res.first.size(), sf_res.second);
703        snoop_result = forwardAtomic(pkt, InvalidPortID, master_port_id,
704                                     sf_res.first);
705    } else {
706        snoop_result = forwardAtomic(pkt, InvalidPortID);
707    }
708    MemCmd snoop_response_cmd = snoop_result.first;
709    snoop_response_latency += snoop_result.second;
710
711    if (snoop_response_cmd != MemCmd::InvalidCmd)
712        pkt->cmd = snoop_response_cmd;
713
714    // add the response snoop data
715    if (pkt->isResponse()) {
716        snoops++;
717    }
718
719    // @todo: Not setting header time
720    pkt->payloadDelay = snoop_response_latency;
721    return snoop_response_latency;
722}
723
724std::pair<MemCmd, Tick>
725CoherentXBar::forwardAtomic(PacketPtr pkt, PortID exclude_slave_port_id,
726                           PortID source_master_port_id,
727                           const std::vector<QueuedSlavePort*>& dests)
728{
729    // the packet may be changed on snoops, record the original
730    // command to enable us to restore it between snoops so that
731    // additional snoops can take place properly
732    MemCmd orig_cmd = pkt->cmd;
733    MemCmd snoop_response_cmd = MemCmd::InvalidCmd;
734    Tick snoop_response_latency = 0;
735
736    // snoops should only happen if the system isn't bypassing caches
737    assert(!system->bypassCaches());
738
739    unsigned fanout = 0;
740
741    for (const auto& p: dests) {
742        // we could have gotten this request from a snooping master
743        // (corresponding to our own slave port that is also in
744        // snoopPorts) and should not send it back to where it came
745        // from
746        if (exclude_slave_port_id != InvalidPortID &&
747            p->getId() == exclude_slave_port_id)
748            continue;
749
750        Tick latency = p->sendAtomicSnoop(pkt);
751        fanout++;
752
753        // in contrast to a functional access, we have to keep on
754        // going as all snoopers must be updated even if we get a
755        // response
756        if (!pkt->isResponse())
757            continue;
758
759        // response from snoop agent
760        assert(pkt->cmd != orig_cmd);
761        assert(pkt->memInhibitAsserted());
762        // should only happen once
763        assert(snoop_response_cmd == MemCmd::InvalidCmd);
764        // save response state
765        snoop_response_cmd = pkt->cmd;
766        snoop_response_latency = latency;
767
768        if (snoopFilter) {
769            // Handle responses by the snoopers and differentiate between
770            // responses to requests from above and snoops from below
771            if (source_master_port_id != InvalidPortID) {
772                // Getting a response for a snoop from below
773                assert(exclude_slave_port_id == InvalidPortID);
774                snoopFilter->updateSnoopForward(pkt, *p,
775                             *masterPorts[source_master_port_id]);
776            } else {
777                // Getting a response for a request from above
778                assert(source_master_port_id == InvalidPortID);
779                snoopFilter->updateSnoopResponse(pkt, *p,
780                             *slavePorts[exclude_slave_port_id]);
781            }
782        }
783        // restore original packet state for remaining snoopers
784        pkt->cmd = orig_cmd;
785    }
786
787    // Stats for fanout
788    snoopFanout.sample(fanout);
789
790    // the packet is restored as part of the loop and any potential
791    // snoop response is part of the returned pair
792    return std::make_pair(snoop_response_cmd, snoop_response_latency);
793}
794
795void
796CoherentXBar::recvFunctional(PacketPtr pkt, PortID slave_port_id)
797{
798    if (!pkt->isPrint()) {
799        // don't do DPRINTFs on PrintReq as it clutters up the output
800        DPRINTF(CoherentXBar,
801                "recvFunctional: packet src %s addr 0x%x cmd %s\n",
802                slavePorts[slave_port_id]->name(), pkt->getAddr(),
803                pkt->cmdString());
804    }
805
806    if (!system->bypassCaches()) {
807        // forward to all snoopers but the source
808        forwardFunctional(pkt, slave_port_id);
809    }
810
811    // there is no need to continue if the snooping has found what we
812    // were looking for and the packet is already a response
813    if (!pkt->isResponse()) {
814        // since our slave ports are queued ports we need to check them as well
815        for (const auto& p : slavePorts) {
816            // if we find a response that has the data, then the
817            // downstream caches/memories may be out of date, so simply stop
818            // here
819            if (p->checkFunctional(pkt)) {
820                if (pkt->needsResponse())
821                    pkt->makeResponse();
822                return;
823            }
824        }
825
826        PortID dest_id = findPort(pkt->getAddr());
827
828        masterPorts[dest_id]->sendFunctional(pkt);
829    }
830}
831
832void
833CoherentXBar::recvFunctionalSnoop(PacketPtr pkt, PortID master_port_id)
834{
835    if (!pkt->isPrint()) {
836        // don't do DPRINTFs on PrintReq as it clutters up the output
837        DPRINTF(CoherentXBar,
838                "recvFunctionalSnoop: packet src %s addr 0x%x cmd %s\n",
839                masterPorts[master_port_id]->name(), pkt->getAddr(),
840                pkt->cmdString());
841    }
842
843    for (const auto& p : slavePorts) {
844        if (p->checkFunctional(pkt)) {
845            if (pkt->needsResponse())
846                pkt->makeResponse();
847            return;
848        }
849    }
850
851    // forward to all snoopers
852    forwardFunctional(pkt, InvalidPortID);
853}
854
855void
856CoherentXBar::forwardFunctional(PacketPtr pkt, PortID exclude_slave_port_id)
857{
858    // snoops should only happen if the system isn't bypassing caches
859    assert(!system->bypassCaches());
860
861    for (const auto& p: snoopPorts) {
862        // we could have gotten this request from a snooping master
863        // (corresponding to our own slave port that is also in
864        // snoopPorts) and should not send it back to where it came
865        // from
866        if (exclude_slave_port_id == InvalidPortID ||
867            p->getId() != exclude_slave_port_id)
868            p->sendFunctionalSnoop(pkt);
869
870        // if we get a response we are done
871        if (pkt->isResponse()) {
872            break;
873        }
874    }
875}
876
877void
878CoherentXBar::regStats()
879{
880    // register the stats of the base class and our layers
881    BaseXBar::regStats();
882    for (auto l: reqLayers)
883        l->regStats();
884    for (auto l: respLayers)
885        l->regStats();
886    for (auto l: snoopLayers)
887        l->regStats();
888
889    snoops
890        .name(name() + ".snoops")
891        .desc("Total snoops (count)")
892    ;
893
894    snoopFanout
895        .init(0, snoopPorts.size(), 1)
896        .name(name() + ".snoop_fanout")
897        .desc("Request fanout histogram")
898    ;
899}
900
901CoherentXBar *
902CoherentXBarParams::create()
903{
904    return new CoherentXBar(this);
905}
906