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