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