1# Copyright (c) 2015-2016 ARM Limited
2# All rights reserved.
3#
4# The license below extends only to copyright in the software and shall
5# not be construed as granting a license to any other intellectual
6# property including but not limited to intellectual property relating
7# to a hardware implementation of the functionality of the software
8# licensed hereunder.  You may use the software subject to the license
9# terms below provided that you ensure that this notice is replicated
10# unmodified and in its entirety in all distributions of the software,
11# modified or unmodified, in source code or in binary form.
12#
13# Copyright (c) 2006-2007 The Regents of The University of Michigan
14# All rights reserved.
15#
16# Redistribution and use in source and binary forms, with or without
17# modification, are permitted provided that the following conditions are
18# met: redistributions of source code must retain the above copyright
19# notice, this list of conditions and the following disclaimer;
20# redistributions in binary form must reproduce the above copyright
21# notice, this list of conditions and the following disclaimer in the
22# documentation and/or other materials provided with the distribution;
23# neither the name of the copyright holders nor the names of its
24# contributors may be used to endorse or promote products derived from
25# this software without specific prior written permission.
26#
27# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38#
39# Authors: Ron Dreslinski
40#          Andreas Hansson
41
42from __future__ import print_function
43from __future__ import absolute_import
44
45import optparse
46import random
47import sys
48
49import m5
50from m5.objects import *
51
52parser = optparse.OptionParser()
53
54parser.add_option("-a", "--atomic", action="store_true",
55                  help="Use atomic (non-timing) mode")
56parser.add_option("-b", "--blocking", action="store_true",
57                  help="Use blocking caches")
58parser.add_option("-m", "--maxtick", type="int", default=m5.MaxTick,
59                  metavar="T",
60                  help="Stop after T ticks")
61parser.add_option("-p", "--prefetchers", action="store_true",
62                  help="Use prefetchers")
63parser.add_option("-s", "--stridepref", action="store_true",
64                  help="Use strided prefetchers")
65
66# This example script has a lot in common with the memtest.py in that
67# it is designed to stress tests the memory system. However, this
68# script uses oblivious traffic generators to create the stimuli, and
69# couples them with memcheckers to verify that the data read matches
70# the allowed outcomes. Just like memtest.py, the traffic generators
71# and checkers are placed in a tree topology. At the bottom of the
72# tree is a shared memory, and then at each level a number of
73# generators and checkers are attached, along with a number of caches
74# that them selves fan out to subtrees of generators and caches. Thus,
75# it is possible to create a system with arbitrarily deep cache
76# hierarchies, sharing or no sharing of caches, and generators not
77# only at the L1s, but also at the L2s, L3s etc.
78#
79# The tree specification consists of two colon-separated lists of one
80# or more integers, one for the caches, and one for the
81# testers/generators. The first integer is the number of
82# caches/testers closest to main memory. Each cache then fans out to a
83# subtree. The last integer in the list is the number of
84# caches/testers associated with the uppermost level of memory. The
85# other integers (if any) specify the number of caches/testers
86# connected at each level of the crossbar hierarchy. The tester string
87# should have one element more than the cache string as there should
88# always be testers attached to the uppermost caches.
89#
90# Since this script tests actual sharing, there is also a possibility
91# to stress prefetching and the interaction between prefetchers and
92# caches. The traffic generators switch between random address streams
93# and linear address streams to ensure that the prefetchers will
94# trigger. By default prefetchers are off.
95
96parser.add_option("-c", "--caches", type="string", default="3:2",
97                  help="Colon-separated cache hierarchy specification, "
98                  "see script comments for details "
99                  "[default: %default]")
100parser.add_option("-t", "--testers", type="string", default="1:0:2",
101                  help="Colon-separated tester hierarchy specification, "
102                  "see script comments for details "
103                  "[default: %default]")
104parser.add_option("-r", "--random", action="store_true",
105                  help="Generate a random tree topology")
106parser.add_option("--sys-clock", action="store", type="string",
107                  default='1GHz',
108                  help = """Top-level clock for blocks running at system
109                  speed""")
110
111(options, args) = parser.parse_args()
112
113if args:
114     print("Error: script doesn't take any positional arguments")
115     sys.exit(1)
116
117# Start by parsing the command line options and do some basic sanity
118# checking
119if options.random:
120     # Generate a tree with a valid number of testers
121     tree_depth = random.randint(1, 4)
122     cachespec = [random.randint(1, 3) for i in range(tree_depth)]
123     testerspec = [random.randint(1, 3) for i in range(tree_depth + 1)]
124     print("Generated random tree -c", ':'.join(map(str, cachespec)),
125         "-t", ':'.join(map(str, testerspec)))
126else:
127     try:
128          cachespec = [int(x) for x in options.caches.split(':')]
129          testerspec = [int(x) for x in options.testers.split(':')]
130     except:
131          print("Error: Unable to parse caches or testers option")
132          sys.exit(1)
133
134     if len(cachespec) < 1:
135          print("Error: Must have at least one level of caches")
136          sys.exit(1)
137
138     if len(cachespec) != len(testerspec) - 1:
139          print("Error: Testers must have one element more than caches")
140          sys.exit(1)
141
142     if testerspec[-1] == 0:
143          print("Error: Must have testers at the uppermost level")
144          sys.exit(1)
145
146     for t in testerspec:
147          if t < 0:
148               print("Error: Cannot have a negative number of testers")
149               sys.exit(1)
150
151     for c in cachespec:
152          if c < 1:
153               print("Error: Must have 1 or more caches at each level")
154               sys.exit(1)
155
156# Determine the tester multiplier for each level as the string
157# elements are per subsystem and it fans out
158multiplier = [1]
159for c in cachespec:
160     if c < 1:
161          print("Error: Must have at least one cache per level")
162     multiplier.append(multiplier[-1] * c)
163
164numtesters = 0
165for t, m in zip(testerspec, multiplier):
166     numtesters += t * m
167
168# Define a prototype L1 cache that we scale for all successive levels
169proto_l1 = Cache(size = '32kB', assoc = 4,
170                 tag_latency = 1, data_latency = 1, response_latency = 1,
171                 tgts_per_mshr = 8)
172
173if options.blocking:
174     proto_l1.mshrs = 1
175else:
176     proto_l1.mshrs = 4
177
178if options.prefetchers:
179     proto_l1.prefetcher = TaggedPrefetcher()
180elif options.stridepref:
181     proto_l1.prefetcher = StridePrefetcher()
182
183cache_proto = [proto_l1]
184
185# Now add additional cache levels (if any) by scaling L1 params, the
186# first element is Ln, and the last element L1
187for scale in cachespec[:-1]:
188     # Clone previous level and update params
189     prev = cache_proto[0]
190     next = prev()
191     next.size = prev.size * scale
192     next.tag_latency = prev.tag_latency * 10
193     next.data_latency = prev.data_latency * 10
194     next.response_latency = prev.response_latency * 10
195     next.assoc = prev.assoc * scale
196     next.mshrs = prev.mshrs * scale
197     cache_proto.insert(0, next)
198
199# Create a config to be used by all the traffic generators
200cfg_file_name = "configs/example/memcheck.cfg"
201cfg_file = open(cfg_file_name, 'w')
202
203# Three states, with random, linear and idle behaviours. The random
204# and linear states access memory in the range [0 : 16 Mbyte] with 8
205# byte and 64 byte accesses respectively.
206cfg_file.write("STATE 0 10000000 RANDOM 65 0 16777216 8 50000 150000 0\n")
207cfg_file.write("STATE 1 10000000 LINEAR 65 0 16777216 64 50000 150000 0\n")
208cfg_file.write("STATE 2 10000000 IDLE\n")
209cfg_file.write("INIT 0\n")
210cfg_file.write("TRANSITION 0 1 0.5\n")
211cfg_file.write("TRANSITION 0 2 0.5\n")
212cfg_file.write("TRANSITION 1 0 0.5\n")
213cfg_file.write("TRANSITION 1 2 0.5\n")
214cfg_file.write("TRANSITION 2 0 0.5\n")
215cfg_file.write("TRANSITION 2 1 0.5\n")
216cfg_file.close()
217
218# Make a prototype for the tester to be used throughout
219proto_tester = TrafficGen(config_file = cfg_file_name)
220
221# Set up the system along with a DRAM controller
222system = System(physmem = DDR3_1600_8x8())
223
224system.voltage_domain = VoltageDomain(voltage = '1V')
225
226system.clk_domain = SrcClockDomain(clock =  options.sys_clock,
227                        voltage_domain = system.voltage_domain)
228
229system.memchecker = MemChecker()
230
231# For each level, track the next subsys index to use
232next_subsys_index = [0] * (len(cachespec) + 1)
233
234# Recursive function to create a sub-tree of the cache and tester
235# hierarchy
236def make_cache_level(ncaches, prototypes, level, next_cache):
237     global next_subsys_index, proto_l1, testerspec, proto_tester
238
239     index = next_subsys_index[level]
240     next_subsys_index[level] += 1
241
242     # Create a subsystem to contain the crossbar and caches, and
243     # any testers
244     subsys = SubSystem()
245     setattr(system, 'l%dsubsys%d' % (level, index), subsys)
246
247     # The levels are indexing backwards through the list
248     ntesters = testerspec[len(cachespec) - level]
249
250     testers = [proto_tester() for i in range(ntesters)]
251     checkers = [MemCheckerMonitor(memchecker = system.memchecker) \
252                      for i in range(ntesters)]
253     if ntesters:
254          subsys.tester = testers
255          subsys.checkers = checkers
256
257     if level != 0:
258          # Create a crossbar and add it to the subsystem, note that
259          # we do this even with a single element on this level
260          xbar = L2XBar(width = 32)
261          subsys.xbar = xbar
262          if next_cache:
263               xbar.master = next_cache.cpu_side
264
265          # Create and connect the caches, both the ones fanning out
266          # to create the tree, and the ones used to connect testers
267          # on this level
268          tree_caches = [prototypes[0]() for i in range(ncaches[0])]
269          tester_caches = [proto_l1() for i in range(ntesters)]
270
271          subsys.cache = tester_caches + tree_caches
272          for cache in tree_caches:
273               cache.mem_side = xbar.slave
274               make_cache_level(ncaches[1:], prototypes[1:], level - 1, cache)
275          for tester, checker, cache in zip(testers, checkers, tester_caches):
276               tester.port = checker.slave
277               checker.master = cache.cpu_side
278               cache.mem_side = xbar.slave
279     else:
280          if not next_cache:
281               print("Error: No next-level cache at top level")
282               sys.exit(1)
283
284          if ntesters > 1:
285               # Create a crossbar and add it to the subsystem
286               xbar = L2XBar(width = 32)
287               subsys.xbar = xbar
288               xbar.master = next_cache.cpu_side
289               for tester, checker in zip(testers, checkers):
290                    tester.port = checker.slave
291                    checker.master = xbar.slave
292          else:
293               # Single tester
294               testers[0].port = checkers[0].slave
295               checkers[0].master = next_cache.cpu_side
296
297# Top level call to create the cache hierarchy, bottom up
298make_cache_level(cachespec, cache_proto, len(cachespec), None)
299
300# Connect the lowest level crossbar to the memory
301last_subsys = getattr(system, 'l%dsubsys0' % len(cachespec))
302last_subsys.xbar.master = system.physmem.port
303last_subsys.xbar.point_of_coherency = True
304
305root = Root(full_system = False, system = system)
306if options.atomic:
307    root.system.mem_mode = 'atomic'
308else:
309    root.system.mem_mode = 'timing'
310
311# The system port is never used in the tester so merely connect it
312# to avoid problems
313root.system.system_port = last_subsys.xbar.slave
314
315# Instantiate configuration
316m5.instantiate()
317
318# Simulate until program terminates
319exit_event = m5.simulate(options.maxtick)
320
321print('Exiting @ tick', m5.curTick(), 'because', exit_event.getCause())
322