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