coherent_xbar.cc revision 11199:929fd978ab4e
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->isEviction()) {
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 or clean writeback, but the packet is
224    // found in a cache, do not forward it
225    if ((pkt->cmd == MemCmd::CleanEvict ||
226         pkt->cmd == MemCmd::WritebackClean) && pkt->isBlockCached()) {
227        DPRINTF(CoherentXBar, "Clean evict/writeback %#llx still cached, "
228                "not forwarding\n", pkt->getAddr());
229
230        // update the layer state and schedule an idle event
231        reqLayers[master_port_id]->succeededTiming(packetFinishTime);
232
233        // queue the packet for deletion
234        pendingDelete.reset(pkt);
235
236        return true;
237    }
238
239    // remember if the packet will generate a snoop response
240    const bool expect_snoop_resp = !is_inhibited && pkt->memInhibitAsserted();
241    const bool expect_response = pkt->needsResponse() &&
242        !pkt->memInhibitAsserted();
243
244    // since it is a normal request, attempt to send the packet
245    bool success = masterPorts[master_port_id]->sendTimingReq(pkt);
246
247    if (snoopFilter && !system->bypassCaches()) {
248        // Let the snoop filter know about the success of the send operation
249        snoopFilter->finishRequest(!success, pkt);
250    }
251
252    // check if we were successful in sending the packet onwards
253    if (!success)  {
254        // express snoops and inhibited packets should never be forced
255        // to retry
256        assert(!is_express_snoop);
257        assert(!pkt->memInhibitAsserted());
258
259        // restore the header delay
260        pkt->headerDelay = old_header_delay;
261
262        DPRINTF(CoherentXBar, "recvTimingReq: src %s %s 0x%x RETRY\n",
263                src_port->name(), pkt->cmdString(), pkt->getAddr());
264
265        // update the layer state and schedule an idle event
266        reqLayers[master_port_id]->failedTiming(src_port,
267                                                clockEdge(Cycles(1)));
268    } else {
269        // express snoops currently bypass the crossbar state entirely
270        if (!is_express_snoop) {
271            // if this particular request will generate a snoop
272            // response
273            if (expect_snoop_resp) {
274                // we should never have an exsiting request outstanding
275                assert(outstandingSnoop.find(pkt->req) ==
276                       outstandingSnoop.end());
277                outstandingSnoop.insert(pkt->req);
278
279                // basic sanity check on the outstanding snoops
280                panic_if(outstandingSnoop.size() > 512,
281                         "Outstanding snoop requests exceeded 512\n");
282            }
283
284            // remember where to route the normal response to
285            if (expect_response || expect_snoop_resp) {
286                assert(routeTo.find(pkt->req) == routeTo.end());
287                routeTo[pkt->req] = slave_port_id;
288
289                panic_if(routeTo.size() > 512,
290                         "Routing table exceeds 512 packets\n");
291            }
292
293            // update the layer state and schedule an idle event
294            reqLayers[master_port_id]->succeededTiming(packetFinishTime);
295        }
296
297        // stats updates only consider packets that were successfully sent
298        pktCount[slave_port_id][master_port_id]++;
299        pktSize[slave_port_id][master_port_id] += pkt_size;
300        transDist[pkt_cmd]++;
301
302        if (is_express_snoop)
303            snoops++;
304    }
305
306    return success;
307}
308
309bool
310CoherentXBar::recvTimingResp(PacketPtr pkt, PortID master_port_id)
311{
312    // determine the source port based on the id
313    MasterPort *src_port = masterPorts[master_port_id];
314
315    // determine the destination
316    const auto route_lookup = routeTo.find(pkt->req);
317    assert(route_lookup != routeTo.end());
318    const PortID slave_port_id = route_lookup->second;
319    assert(slave_port_id != InvalidPortID);
320    assert(slave_port_id < respLayers.size());
321
322    // test if the crossbar should be considered occupied for the
323    // current port
324    if (!respLayers[slave_port_id]->tryTiming(src_port)) {
325        DPRINTF(CoherentXBar, "recvTimingResp: src %s %s 0x%x BUSY\n",
326                src_port->name(), pkt->cmdString(), pkt->getAddr());
327        return false;
328    }
329
330    DPRINTF(CoherentXBar, "recvTimingResp: src %s %s 0x%x\n",
331            src_port->name(), pkt->cmdString(), pkt->getAddr());
332
333    // store size and command as they might be modified when
334    // forwarding the packet
335    unsigned int pkt_size = pkt->hasData() ? pkt->getSize() : 0;
336    unsigned int pkt_cmd = pkt->cmdToIndex();
337
338    // a response sees the response latency
339    Tick xbar_delay = responseLatency * clockPeriod();
340
341    // set the packet header and payload delay
342    calcPacketTiming(pkt, xbar_delay);
343
344    // determine how long to be crossbar layer is busy
345    Tick packetFinishTime = clockEdge(Cycles(1)) + pkt->payloadDelay;
346
347    if (snoopFilter && !system->bypassCaches()) {
348        // let the snoop filter inspect the response and update its state
349        snoopFilter->updateResponse(pkt, *slavePorts[slave_port_id]);
350    }
351
352    // send the packet through the destination slave port and pay for
353    // any outstanding header delay
354    Tick latency = pkt->headerDelay;
355    pkt->headerDelay = 0;
356    slavePorts[slave_port_id]->schedTimingResp(pkt, curTick() + latency);
357
358    // remove the request from the routing table
359    routeTo.erase(route_lookup);
360
361    respLayers[slave_port_id]->succeededTiming(packetFinishTime);
362
363    // stats updates
364    pktCount[slave_port_id][master_port_id]++;
365    pktSize[slave_port_id][master_port_id] += pkt_size;
366    transDist[pkt_cmd]++;
367
368    return true;
369}
370
371void
372CoherentXBar::recvTimingSnoopReq(PacketPtr pkt, PortID master_port_id)
373{
374    DPRINTF(CoherentXBar, "recvTimingSnoopReq: src %s %s 0x%x\n",
375            masterPorts[master_port_id]->name(), pkt->cmdString(),
376            pkt->getAddr());
377
378    // update stats here as we know the forwarding will succeed
379    transDist[pkt->cmdToIndex()]++;
380    snoops++;
381
382    // we should only see express snoops from caches
383    assert(pkt->isExpressSnoop());
384
385    // set the packet header and payload delay, for now use forward latency
386    // @todo Assess the choice of latency further
387    calcPacketTiming(pkt, forwardLatency * clockPeriod());
388
389    // remeber if the packet is inhibited so we can see if it changes
390    const bool is_inhibited = pkt->memInhibitAsserted();
391
392    assert(pkt->snoopDelay == 0);
393
394    if (snoopFilter) {
395        // let the Snoop Filter work its magic and guide probing
396        auto sf_res = snoopFilter->lookupSnoop(pkt);
397        // the time required by a packet to be delivered through
398        // the xbar has to be charged also with to lookup latency
399        // of the snoop filter
400        pkt->headerDelay += sf_res.second * clockPeriod();
401        DPRINTF(CoherentXBar, "recvTimingSnoopReq: src %s %s 0x%x"\
402                " SF size: %i lat: %i\n", masterPorts[master_port_id]->name(),
403                pkt->cmdString(), pkt->getAddr(), sf_res.first.size(),
404                sf_res.second);
405
406        // forward to all snoopers
407        forwardTiming(pkt, InvalidPortID, sf_res.first);
408    } else {
409        forwardTiming(pkt, InvalidPortID);
410    }
411
412    // add the snoop delay to our header delay, and then reset it
413    pkt->headerDelay += pkt->snoopDelay;
414    pkt->snoopDelay = 0;
415
416    // if we can expect a response, remember how to route it
417    if (!is_inhibited && pkt->memInhibitAsserted()) {
418        assert(routeTo.find(pkt->req) == routeTo.end());
419        routeTo[pkt->req] = master_port_id;
420    }
421
422    // a snoop request came from a connected slave device (one of
423    // our master ports), and if it is not coming from the slave
424    // device responsible for the address range something is
425    // wrong, hence there is nothing further to do as the packet
426    // would be going back to where it came from
427    assert(master_port_id == findPort(pkt->getAddr()));
428}
429
430bool
431CoherentXBar::recvTimingSnoopResp(PacketPtr pkt, PortID slave_port_id)
432{
433    // determine the source port based on the id
434    SlavePort* src_port = slavePorts[slave_port_id];
435
436    // get the destination
437    const auto route_lookup = routeTo.find(pkt->req);
438    assert(route_lookup != routeTo.end());
439    const PortID dest_port_id = route_lookup->second;
440    assert(dest_port_id != InvalidPortID);
441
442    // determine if the response is from a snoop request we
443    // created as the result of a normal request (in which case it
444    // should be in the outstandingSnoop), or if we merely forwarded
445    // someone else's snoop request
446    const bool forwardAsSnoop = outstandingSnoop.find(pkt->req) ==
447        outstandingSnoop.end();
448
449    // test if the crossbar should be considered occupied for the
450    // current port, note that the check is bypassed if the response
451    // is being passed on as a normal response since this is occupying
452    // the response layer rather than the snoop response layer
453    if (forwardAsSnoop) {
454        assert(dest_port_id < snoopLayers.size());
455        if (!snoopLayers[dest_port_id]->tryTiming(src_port)) {
456            DPRINTF(CoherentXBar, "recvTimingSnoopResp: src %s %s 0x%x BUSY\n",
457                    src_port->name(), pkt->cmdString(), pkt->getAddr());
458            return false;
459        }
460    } else {
461        // get the master port that mirrors this slave port internally
462        MasterPort* snoop_port = snoopRespPorts[slave_port_id];
463        assert(dest_port_id < respLayers.size());
464        if (!respLayers[dest_port_id]->tryTiming(snoop_port)) {
465            DPRINTF(CoherentXBar, "recvTimingSnoopResp: src %s %s 0x%x BUSY\n",
466                    snoop_port->name(), pkt->cmdString(), pkt->getAddr());
467            return false;
468        }
469    }
470
471    DPRINTF(CoherentXBar, "recvTimingSnoopResp: src %s %s 0x%x\n",
472            src_port->name(), pkt->cmdString(), pkt->getAddr());
473
474    // store size and command as they might be modified when
475    // forwarding the packet
476    unsigned int pkt_size = pkt->hasData() ? pkt->getSize() : 0;
477    unsigned int pkt_cmd = pkt->cmdToIndex();
478
479    // responses are never express snoops
480    assert(!pkt->isExpressSnoop());
481
482    // a snoop response sees the snoop response latency, and if it is
483    // forwarded as a normal response, the response latency
484    Tick xbar_delay =
485        (forwardAsSnoop ? snoopResponseLatency : responseLatency) *
486        clockPeriod();
487
488    // set the packet header and payload delay
489    calcPacketTiming(pkt, xbar_delay);
490
491    // determine how long to be crossbar layer is busy
492    Tick packetFinishTime = clockEdge(Cycles(1)) + pkt->payloadDelay;
493
494    // forward it either as a snoop response or a normal response
495    if (forwardAsSnoop) {
496        // this is a snoop response to a snoop request we forwarded,
497        // e.g. coming from the L1 and going to the L2, and it should
498        // be forwarded as a snoop response
499
500        if (snoopFilter) {
501            // update the probe filter so that it can properly track the line
502            snoopFilter->updateSnoopForward(pkt, *slavePorts[slave_port_id],
503                                            *masterPorts[dest_port_id]);
504        }
505
506        bool success M5_VAR_USED =
507            masterPorts[dest_port_id]->sendTimingSnoopResp(pkt);
508        pktCount[slave_port_id][dest_port_id]++;
509        pktSize[slave_port_id][dest_port_id] += pkt_size;
510        assert(success);
511
512        snoopLayers[dest_port_id]->succeededTiming(packetFinishTime);
513    } else {
514        // we got a snoop response on one of our slave ports,
515        // i.e. from a coherent master connected to the crossbar, and
516        // since we created the snoop request as part of recvTiming,
517        // this should now be a normal response again
518        outstandingSnoop.erase(pkt->req);
519
520        // this is a snoop response from a coherent master, hence it
521        // should never go back to where the snoop response came from,
522        // but instead to where the original request came from
523        assert(slave_port_id != dest_port_id);
524
525        if (snoopFilter) {
526            // update the probe filter so that it can properly track the line
527            snoopFilter->updateSnoopResponse(pkt, *slavePorts[slave_port_id],
528                                    *slavePorts[dest_port_id]);
529        }
530
531        DPRINTF(CoherentXBar, "recvTimingSnoopResp: src %s %s 0x%x"\
532                " FWD RESP\n", src_port->name(), pkt->cmdString(),
533                pkt->getAddr());
534
535        // as a normal response, it should go back to a master through
536        // one of our slave ports, we also pay for any outstanding
537        // header latency
538        Tick latency = pkt->headerDelay;
539        pkt->headerDelay = 0;
540        slavePorts[dest_port_id]->schedTimingResp(pkt, curTick() + latency);
541
542        respLayers[dest_port_id]->succeededTiming(packetFinishTime);
543    }
544
545    // remove the request from the routing table
546    routeTo.erase(route_lookup);
547
548    // stats updates
549    transDist[pkt_cmd]++;
550    snoops++;
551
552    return true;
553}
554
555
556void
557CoherentXBar::forwardTiming(PacketPtr pkt, PortID exclude_slave_port_id,
558                           const std::vector<QueuedSlavePort*>& dests)
559{
560    DPRINTF(CoherentXBar, "%s for %s address %x size %d\n", __func__,
561            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
562
563    // snoops should only happen if the system isn't bypassing caches
564    assert(!system->bypassCaches());
565
566    unsigned fanout = 0;
567
568    for (const auto& p: dests) {
569        // we could have gotten this request from a snooping master
570        // (corresponding to our own slave port that is also in
571        // snoopPorts) and should not send it back to where it came
572        // from
573        if (exclude_slave_port_id == InvalidPortID ||
574            p->getId() != exclude_slave_port_id) {
575            // cache is not allowed to refuse snoop
576            p->sendTimingSnoopReq(pkt);
577            fanout++;
578        }
579    }
580
581    // Stats for fanout of this forward operation
582    snoopFanout.sample(fanout);
583}
584
585void
586CoherentXBar::recvReqRetry(PortID master_port_id)
587{
588    // responses and snoop responses never block on forwarding them,
589    // so the retry will always be coming from a port to which we
590    // tried to forward a request
591    reqLayers[master_port_id]->recvRetry();
592}
593
594Tick
595CoherentXBar::recvAtomic(PacketPtr pkt, PortID slave_port_id)
596{
597    DPRINTF(CoherentXBar, "recvAtomic: packet src %s addr 0x%x cmd %s\n",
598            slavePorts[slave_port_id]->name(), pkt->getAddr(),
599            pkt->cmdString());
600
601    unsigned int pkt_size = pkt->hasData() ? pkt->getSize() : 0;
602    unsigned int pkt_cmd = pkt->cmdToIndex();
603
604    MemCmd snoop_response_cmd = MemCmd::InvalidCmd;
605    Tick snoop_response_latency = 0;
606
607    if (!system->bypassCaches()) {
608        // forward to all snoopers but the source
609        std::pair<MemCmd, Tick> snoop_result;
610        if (snoopFilter) {
611            // check with the snoop filter where to forward this packet
612            auto sf_res =
613                snoopFilter->lookupRequest(pkt, *slavePorts[slave_port_id]);
614            snoop_response_latency += sf_res.second * clockPeriod();
615            DPRINTF(CoherentXBar, "%s: src %s %s 0x%x"\
616                    " SF size: %i lat: %i\n", __func__,
617                    slavePorts[slave_port_id]->name(), pkt->cmdString(),
618                    pkt->getAddr(), sf_res.first.size(), sf_res.second);
619
620            // let the snoop filter know about the success of the send
621            // operation, and do it even before sending it onwards to
622            // avoid situations where atomic upward snoops sneak in
623            // between and change the filter state
624            snoopFilter->finishRequest(false, pkt);
625
626            snoop_result = forwardAtomic(pkt, slave_port_id, InvalidPortID,
627                                         sf_res.first);
628        } else {
629            snoop_result = forwardAtomic(pkt, slave_port_id);
630        }
631        snoop_response_cmd = snoop_result.first;
632        snoop_response_latency += snoop_result.second;
633    }
634
635    // forwardAtomic snooped into peer caches of the sender, and if
636    // this is a clean evict, but the packet is found in a cache, do
637    // not forward it
638    if ((pkt->cmd == MemCmd::CleanEvict ||
639         pkt->cmd == MemCmd::WritebackClean) && pkt->isBlockCached()) {
640        DPRINTF(CoherentXBar, "Clean evict/writeback %#llx still cached, "
641                "not forwarding\n", pkt->getAddr());
642        return 0;
643    }
644
645    // even if we had a snoop response, we must continue and also
646    // perform the actual request at the destination
647    PortID master_port_id = findPort(pkt->getAddr());
648
649    // stats updates for the request
650    pktCount[slave_port_id][master_port_id]++;
651    pktSize[slave_port_id][master_port_id] += pkt_size;
652    transDist[pkt_cmd]++;
653
654    // forward the request to the appropriate destination
655    Tick response_latency = masterPorts[master_port_id]->sendAtomic(pkt);
656
657    // if lower levels have replied, tell the snoop filter
658    if (!system->bypassCaches() && snoopFilter && pkt->isResponse()) {
659        snoopFilter->updateResponse(pkt, *slavePorts[slave_port_id]);
660    }
661
662    // if we got a response from a snooper, restore it here
663    if (snoop_response_cmd != MemCmd::InvalidCmd) {
664        // no one else should have responded
665        assert(!pkt->isResponse());
666        pkt->cmd = snoop_response_cmd;
667        response_latency = snoop_response_latency;
668    }
669
670    // add the response data
671    if (pkt->isResponse()) {
672        pkt_size = pkt->hasData() ? pkt->getSize() : 0;
673        pkt_cmd = pkt->cmdToIndex();
674
675        // stats updates
676        pktCount[slave_port_id][master_port_id]++;
677        pktSize[slave_port_id][master_port_id] += pkt_size;
678        transDist[pkt_cmd]++;
679    }
680
681    // @todo: Not setting header time
682    pkt->payloadDelay = response_latency;
683    return response_latency;
684}
685
686Tick
687CoherentXBar::recvAtomicSnoop(PacketPtr pkt, PortID master_port_id)
688{
689    DPRINTF(CoherentXBar, "recvAtomicSnoop: packet src %s addr 0x%x cmd %s\n",
690            masterPorts[master_port_id]->name(), pkt->getAddr(),
691            pkt->cmdString());
692
693    // add the request snoop data
694    snoops++;
695
696    // forward to all snoopers
697    std::pair<MemCmd, Tick> snoop_result;
698    Tick snoop_response_latency = 0;
699    if (snoopFilter) {
700        auto sf_res = snoopFilter->lookupSnoop(pkt);
701        snoop_response_latency += sf_res.second * clockPeriod();
702        DPRINTF(CoherentXBar, "%s: src %s %s 0x%x SF size: %i lat: %i\n",
703                __func__, masterPorts[master_port_id]->name(), pkt->cmdString(),
704                pkt->getAddr(), sf_res.first.size(), sf_res.second);
705        snoop_result = forwardAtomic(pkt, InvalidPortID, master_port_id,
706                                     sf_res.first);
707    } else {
708        snoop_result = forwardAtomic(pkt, InvalidPortID);
709    }
710    MemCmd snoop_response_cmd = snoop_result.first;
711    snoop_response_latency += snoop_result.second;
712
713    if (snoop_response_cmd != MemCmd::InvalidCmd)
714        pkt->cmd = snoop_response_cmd;
715
716    // add the response snoop data
717    if (pkt->isResponse()) {
718        snoops++;
719    }
720
721    // @todo: Not setting header time
722    pkt->payloadDelay = snoop_response_latency;
723    return snoop_response_latency;
724}
725
726std::pair<MemCmd, Tick>
727CoherentXBar::forwardAtomic(PacketPtr pkt, PortID exclude_slave_port_id,
728                           PortID source_master_port_id,
729                           const std::vector<QueuedSlavePort*>& dests)
730{
731    // the packet may be changed on snoops, record the original
732    // command to enable us to restore it between snoops so that
733    // additional snoops can take place properly
734    MemCmd orig_cmd = pkt->cmd;
735    MemCmd snoop_response_cmd = MemCmd::InvalidCmd;
736    Tick snoop_response_latency = 0;
737
738    // snoops should only happen if the system isn't bypassing caches
739    assert(!system->bypassCaches());
740
741    unsigned fanout = 0;
742
743    for (const auto& p: dests) {
744        // we could have gotten this request from a snooping master
745        // (corresponding to our own slave port that is also in
746        // snoopPorts) and should not send it back to where it came
747        // from
748        if (exclude_slave_port_id != InvalidPortID &&
749            p->getId() == exclude_slave_port_id)
750            continue;
751
752        Tick latency = p->sendAtomicSnoop(pkt);
753        fanout++;
754
755        // in contrast to a functional access, we have to keep on
756        // going as all snoopers must be updated even if we get a
757        // response
758        if (!pkt->isResponse())
759            continue;
760
761        // response from snoop agent
762        assert(pkt->cmd != orig_cmd);
763        assert(pkt->memInhibitAsserted());
764        // should only happen once
765        assert(snoop_response_cmd == MemCmd::InvalidCmd);
766        // save response state
767        snoop_response_cmd = pkt->cmd;
768        snoop_response_latency = latency;
769
770        if (snoopFilter) {
771            // Handle responses by the snoopers and differentiate between
772            // responses to requests from above and snoops from below
773            if (source_master_port_id != InvalidPortID) {
774                // Getting a response for a snoop from below
775                assert(exclude_slave_port_id == InvalidPortID);
776                snoopFilter->updateSnoopForward(pkt, *p,
777                             *masterPorts[source_master_port_id]);
778            } else {
779                // Getting a response for a request from above
780                assert(source_master_port_id == InvalidPortID);
781                snoopFilter->updateSnoopResponse(pkt, *p,
782                             *slavePorts[exclude_slave_port_id]);
783            }
784        }
785        // restore original packet state for remaining snoopers
786        pkt->cmd = orig_cmd;
787    }
788
789    // Stats for fanout
790    snoopFanout.sample(fanout);
791
792    // the packet is restored as part of the loop and any potential
793    // snoop response is part of the returned pair
794    return std::make_pair(snoop_response_cmd, snoop_response_latency);
795}
796
797void
798CoherentXBar::recvFunctional(PacketPtr pkt, PortID slave_port_id)
799{
800    if (!pkt->isPrint()) {
801        // don't do DPRINTFs on PrintReq as it clutters up the output
802        DPRINTF(CoherentXBar,
803                "recvFunctional: packet src %s addr 0x%x cmd %s\n",
804                slavePorts[slave_port_id]->name(), pkt->getAddr(),
805                pkt->cmdString());
806    }
807
808    if (!system->bypassCaches()) {
809        // forward to all snoopers but the source
810        forwardFunctional(pkt, slave_port_id);
811    }
812
813    // there is no need to continue if the snooping has found what we
814    // were looking for and the packet is already a response
815    if (!pkt->isResponse()) {
816        // since our slave ports are queued ports we need to check them as well
817        for (const auto& p : slavePorts) {
818            // if we find a response that has the data, then the
819            // downstream caches/memories may be out of date, so simply stop
820            // here
821            if (p->checkFunctional(pkt)) {
822                if (pkt->needsResponse())
823                    pkt->makeResponse();
824                return;
825            }
826        }
827
828        PortID dest_id = findPort(pkt->getAddr());
829
830        masterPorts[dest_id]->sendFunctional(pkt);
831    }
832}
833
834void
835CoherentXBar::recvFunctionalSnoop(PacketPtr pkt, PortID master_port_id)
836{
837    if (!pkt->isPrint()) {
838        // don't do DPRINTFs on PrintReq as it clutters up the output
839        DPRINTF(CoherentXBar,
840                "recvFunctionalSnoop: packet src %s addr 0x%x cmd %s\n",
841                masterPorts[master_port_id]->name(), pkt->getAddr(),
842                pkt->cmdString());
843    }
844
845    for (const auto& p : slavePorts) {
846        if (p->checkFunctional(pkt)) {
847            if (pkt->needsResponse())
848                pkt->makeResponse();
849            return;
850        }
851    }
852
853    // forward to all snoopers
854    forwardFunctional(pkt, InvalidPortID);
855}
856
857void
858CoherentXBar::forwardFunctional(PacketPtr pkt, PortID exclude_slave_port_id)
859{
860    // snoops should only happen if the system isn't bypassing caches
861    assert(!system->bypassCaches());
862
863    for (const auto& p: snoopPorts) {
864        // we could have gotten this request from a snooping master
865        // (corresponding to our own slave port that is also in
866        // snoopPorts) and should not send it back to where it came
867        // from
868        if (exclude_slave_port_id == InvalidPortID ||
869            p->getId() != exclude_slave_port_id)
870            p->sendFunctionalSnoop(pkt);
871
872        // if we get a response we are done
873        if (pkt->isResponse()) {
874            break;
875        }
876    }
877}
878
879void
880CoherentXBar::regStats()
881{
882    // register the stats of the base class and our layers
883    BaseXBar::regStats();
884    for (auto l: reqLayers)
885        l->regStats();
886    for (auto l: respLayers)
887        l->regStats();
888    for (auto l: snoopLayers)
889        l->regStats();
890
891    snoops
892        .name(name() + ".snoops")
893        .desc("Total snoops (count)")
894    ;
895
896    snoopFanout
897        .init(0, snoopPorts.size(), 1)
898        .name(name() + ".snoop_fanout")
899        .desc("Request fanout histogram")
900    ;
901}
902
903CoherentXBar *
904CoherentXBarParams::create()
905{
906    return new CoherentXBar(this);
907}
908