msi_caches.py revision 12609
1# -*- coding: utf-8 -*-
2# Copyright (c) 2017 Jason Power
3# All rights reserved.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met: redistributions of source code must retain the above copyright
8# notice, this list of conditions and the following disclaimer;
9# redistributions in binary form must reproduce the above copyright
10# notice, this list of conditions and the following disclaimer in the
11# documentation and/or other materials provided with the distribution;
12# neither the name of the copyright holders nor the names of its
13# contributors may be used to endorse or promote products derived from
14# this software without specific prior written permission.
15#
16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27#
28# Authors: Jason Power
29
30""" This file creates a set of Ruby caches, the Ruby network, and a simple
31point-to-point topology.
32See Part 3 in the Learning gem5 book: learning.gem5.org/book/part3
33
34IMPORTANT: If you modify this file, it's likely that the Learning gem5 book
35           also needs to be updated. For now, email Jason <jason@lowepower.com>
36
37"""
38
39import math
40
41from m5.defines import buildEnv
42from m5.util import fatal, panic
43
44from m5.objects import *
45
46class MyCacheSystem(RubySystem):
47
48    def __init__(self):
49        if buildEnv['PROTOCOL'] != 'MSI':
50            fatal("This system assumes MSI from learning gem5!")
51
52        super(MyCacheSystem, self).__init__()
53
54    def setup(self, system, cpus, mem_ctrls):
55        """Set up the Ruby cache subsystem. Note: This can't be done in the
56           constructor because many of these items require a pointer to the
57           ruby system (self). This causes infinite recursion in initialize()
58           if we do this in the __init__.
59        """
60        # Ruby's global network.
61        self.network = MyNetwork(self)
62
63        # MSI uses 3 virtual networks. One for requests (lowest priority), one
64        # for responses (highest priority), and one for "forwards" or
65        # cache-to-cache requests. See *.sm files for details.
66        self.number_of_virtual_networks = 3
67        self.network.number_of_virtual_networks = 3
68
69        # There is a single global list of all of the controllers to make it
70        # easier to connect everything to the global network. This can be
71        # customized depending on the topology/network requirements.
72        # Create one controller for each L1 cache (and the cache mem obj.)
73        # Create a single directory controller (Really the memory cntrl)
74        self.controllers = \
75            [L1Cache(system, self, cpu) for cpu in cpus] + \
76            [DirController(self, system.mem_ranges, mem_ctrls)]
77
78        # Create one sequencer per CPU. In many systems this is more
79        # complicated since you have to create sequencers for DMA controllers
80        # and other controllers, too.
81        self.sequencers = [RubySequencer(version = i,
82                                # I/D cache is combined and grab from ctrl
83                                icache = self.controllers[i].cacheMemory,
84                                dcache = self.controllers[i].cacheMemory,
85                                clk_domain = self.controllers[i].clk_domain,
86                                ) for i in range(len(cpus))]
87
88        # We know that we put the controllers in an order such that the first
89        # N of them are the L1 caches which need a sequencer pointer
90        for i,c in enumerate(self.controllers[0:len(self.sequencers)]):
91            c.sequencer = self.sequencers[i]
92
93        self.num_of_sequencers = len(self.sequencers)
94
95        # Create the network and connect the controllers.
96        # NOTE: This is quite different if using Garnet!
97        self.network.connectControllers(self.controllers)
98        self.network.setup_buffers()
99
100        # Set up a proxy port for the system_port. Used for load binaries and
101        # other functional-only things.
102        self.sys_port_proxy = RubyPortProxy()
103        system.system_port = self.sys_port_proxy.slave
104
105        # Connect the cpu's cache, interrupt, and TLB ports to Ruby
106        for i,cpu in enumerate(cpus):
107            cpu.icache_port = self.sequencers[i].slave
108            cpu.dcache_port = self.sequencers[i].slave
109            isa = buildEnv['TARGET_ISA']
110            if isa == 'x86':
111                cpu.interrupts[0].pio = self.sequencers[i].master
112                cpu.interrupts[0].int_master = self.sequencers[i].slave
113                cpu.interrupts[0].int_slave = self.sequencers[i].master
114            if isa == 'x86' or isa == 'arm':
115                cpu.itb.walker.port = self.sequencers[i].slave
116                cpu.dtb.walker.port = self.sequencers[i].slave
117
118
119class L1Cache(L1Cache_Controller):
120
121    _version = 0
122    @classmethod
123    def versionCount(cls):
124        cls._version += 1 # Use count for this particular type
125        return cls._version - 1
126
127    def __init__(self, system, ruby_system, cpu):
128        """CPUs are needed to grab the clock domain and system is needed for
129           the cache block size.
130        """
131        super(L1Cache, self).__init__()
132
133        self.version = self.versionCount()
134        # This is the cache memory object that stores the cache data and tags
135        self.cacheMemory = RubyCache(size = '16kB',
136                               assoc = 8,
137                               start_index_bit = self.getBlockSizeBits(system))
138        self.clk_domain = cpu.clk_domain
139        self.send_evictions = self.sendEvicts(cpu)
140        self.ruby_system = ruby_system
141        self.connectQueues(ruby_system)
142
143    def getBlockSizeBits(self, system):
144        bits = int(math.log(system.cache_line_size, 2))
145        if 2**bits != system.cache_line_size.value:
146            panic("Cache line size not a power of 2!")
147        return bits
148
149    def sendEvicts(self, cpu):
150        """True if the CPU model or ISA requires sending evictions from caches
151           to the CPU. Two scenarios warrant forwarding evictions to the CPU:
152           1. The O3 model must keep the LSQ coherent with the caches
153           2. The x86 mwait instruction is built on top of coherence
154           3. The local exclusive monitor in ARM systems
155        """
156        if type(cpu) is DerivO3CPU or \
157           buildEnv['TARGET_ISA'] in ('x86', 'arm'):
158            return True
159        return False
160
161    def connectQueues(self, ruby_system):
162        """Connect all of the queues for this controller.
163        """
164        # mandatoryQueue is a special variable. It is used by the sequencer to
165        # send RubyRequests from the CPU (or other processor). It isn't
166        # explicitly connected to anything.
167        self.mandatoryQueue = MessageBuffer()
168
169        # All message buffers must be created and connected to the general
170        # Ruby network. In this case, "slave/master" don't mean the same thing
171        # as normal gem5 ports. If a MessageBuffer is a "to" buffer (i.e., out)
172        # then you use the "master", otherwise, the slave.
173        self.requestToDir = MessageBuffer(ordered = True)
174        self.requestToDir.master = ruby_system.network.slave
175        self.responseToDirOrSibling = MessageBuffer(ordered = True)
176        self.responseToDirOrSibling.master = ruby_system.network.slave
177        self.forwardFromDir = MessageBuffer(ordered = True)
178        self.forwardFromDir.slave = ruby_system.network.master
179        self.responseFromDirOrSibling = MessageBuffer(ordered = True)
180        self.responseFromDirOrSibling.slave = ruby_system.network.master
181
182class DirController(Directory_Controller):
183
184    _version = 0
185    @classmethod
186    def versionCount(cls):
187        cls._version += 1 # Use count for this particular type
188        return cls._version - 1
189
190    def __init__(self, ruby_system, ranges, mem_ctrls):
191        """ranges are the memory ranges assigned to this controller.
192        """
193        if len(mem_ctrls) > 1:
194            panic("This cache system can only be connected to one mem ctrl")
195        super(DirController, self).__init__()
196        self.version = self.versionCount()
197        self.addr_ranges = ranges
198        self.ruby_system = ruby_system
199        self.directory = RubyDirectoryMemory()
200        # Connect this directory to the memory side.
201        self.memory = mem_ctrls[0].port
202        self.connectQueues(ruby_system)
203
204    def connectQueues(self, ruby_system):
205        self.requestFromCache = MessageBuffer(ordered = True)
206        self.requestFromCache.slave = ruby_system.network.master
207        self.responseFromCache = MessageBuffer(ordered = True)
208        self.responseFromCache.slave = ruby_system.network.master
209
210        self.responseToCache = MessageBuffer(ordered = True)
211        self.responseToCache.master = ruby_system.network.slave
212        self.forwardToCache = MessageBuffer(ordered = True)
213        self.forwardToCache.master = ruby_system.network.slave
214
215        # This is another special message buffer. It is used to send replies
216        # from memory back to the controller. Any messages received on the
217        # memory port (see self.memory above) will be directed to this
218        # message buffer.
219        self.responseFromMemory = MessageBuffer()
220
221class MyNetwork(SimpleNetwork):
222    """A simple point-to-point network. This doesn't not use garnet.
223    """
224
225    def __init__(self, ruby_system):
226        super(MyNetwork, self).__init__()
227        self.netifs = []
228        self.ruby_system = ruby_system
229
230    def connectControllers(self, controllers):
231        """Connect all of the controllers to routers and connec the routers
232           together in a point-to-point network.
233        """
234        # Create one router/switch per controller in the system
235        self.routers = [Switch(router_id = i) for i in range(len(controllers))]
236
237        # Make a link from each controller to the router. The link goes
238        # externally to the network.
239        self.ext_links = [SimpleExtLink(link_id=i, ext_node=c,
240                                        int_node=self.routers[i])
241                          for i, c in enumerate(controllers)]
242
243        # Make an "internal" link (internal to the network) between every pair
244        # of routers.
245        link_count = 0
246        self.int_links = []
247        for ri in self.routers:
248            for rj in self.routers:
249                if ri == rj: continue # Don't connect a router to itself!
250                link_count += 1
251                self.int_links.append(SimpleIntLink(link_id = link_count,
252                                                    src_node = ri,
253                                                    dst_node = rj))
254