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