1# Copyright (c) 2016-2017 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# Redistribution and use in source and binary forms, with or without
14# modification, are permitted provided that the following conditions are
15# met: redistributions of source code must retain the above copyright
16# notice, this list of conditions and the following disclaimer;
17# redistributions in binary form must reproduce the above copyright
18# notice, this list of conditions and the following disclaimer in the
19# documentation and/or other materials provided with the distribution;
20# neither the name of the copyright holders nor the names of its
21# contributors may be used to endorse or promote products derived from
22# this software without specific prior written permission.
23#
24# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35#
36#  Authors:  Andreas Sandberg
37#            Chuan Zhu
38#            Gabor Dozsa
39#
40
41"""This script is the syscall emulation example script from the ARM
42Research Starter Kit on System Modeling. More information can be found
43at: http://www.arm.com/ResearchEnablement/SystemModeling
44"""
45
46from __future__ import print_function
47from __future__ import absolute_import
48
49import os
50import m5
51from m5.util import addToPath
52from m5.objects import *
53import argparse
54import shlex
55
56m5.util.addToPath('../..')
57
58from common import MemConfig
59from common.cores.arm import HPI
60
61import devices
62
63
64
65# Pre-defined CPU configurations. Each tuple must be ordered as : (cpu_class,
66# l1_icache_class, l1_dcache_class, walk_cache_class, l2_Cache_class). Any of
67# the cache class may be 'None' if the particular cache is not present.
68cpu_types = {
69    "atomic" : ( AtomicSimpleCPU, None, None, None, None),
70    "minor" : (MinorCPU,
71               devices.L1I, devices.L1D,
72               devices.WalkCache,
73               devices.L2),
74    "hpi" : ( HPI.HPI,
75              HPI.HPI_ICache, HPI.HPI_DCache,
76              HPI.HPI_WalkCache,
77              HPI.HPI_L2)
78}
79
80
81class SimpleSeSystem(System):
82    '''
83    Example system class for syscall emulation mode
84    '''
85
86    # Use a fixed cache line size of 64 bytes
87    cache_line_size = 64
88
89    def __init__(self, args, **kwargs):
90        super(SimpleSeSystem, self).__init__(**kwargs)
91
92        # Setup book keeping to be able to use CpuClusters from the
93        # devices module.
94        self._clusters = []
95        self._num_cpus = 0
96
97        # Create a voltage and clock domain for system components
98        self.voltage_domain = VoltageDomain(voltage="3.3V")
99        self.clk_domain = SrcClockDomain(clock="1GHz",
100                                         voltage_domain=self.voltage_domain)
101
102        # Create the off-chip memory bus.
103        self.membus = SystemXBar()
104
105        # Wire up the system port that gem5 uses to load the kernel
106        # and to perform debug accesses.
107        self.system_port = self.membus.slave
108
109
110        # Add CPUs to the system. A cluster of CPUs typically have
111        # private L1 caches and a shared L2 cache.
112        self.cpu_cluster = devices.CpuCluster(self,
113                                              args.num_cores,
114                                              args.cpu_freq, "1.2V",
115                                              *cpu_types[args.cpu])
116
117        # Create a cache hierarchy (unless we are simulating a
118        # functional CPU in atomic memory mode) for the CPU cluster
119        # and connect it to the shared memory bus.
120        if self.cpu_cluster.memoryMode() == "timing":
121            self.cpu_cluster.addL1()
122            self.cpu_cluster.addL2(self.cpu_cluster.clk_domain)
123        self.cpu_cluster.connectMemSide(self.membus)
124
125        # Tell gem5 about the memory mode used by the CPUs we are
126        # simulating.
127        self.mem_mode = self.cpu_cluster.memoryMode()
128
129    def numCpuClusters(self):
130        return len(self._clusters)
131
132    def addCpuCluster(self, cpu_cluster, num_cpus):
133        assert cpu_cluster not in self._clusters
134        assert num_cpus > 0
135        self._clusters.append(cpu_cluster)
136        self._num_cpus += num_cpus
137
138    def numCpus(self):
139        return self._num_cpus
140
141def get_processes(cmd):
142    """Interprets commands to run and returns a list of processes"""
143
144    cwd = os.getcwd()
145    multiprocesses = []
146    for idx, c in enumerate(cmd):
147        argv = shlex.split(c)
148
149        process = Process(pid=100 + idx, cwd=cwd, cmd=argv, executable=argv[0])
150
151        print("info: %d. command and arguments: %s" % (idx + 1, process.cmd))
152        multiprocesses.append(process)
153
154    return multiprocesses
155
156
157def create(args):
158    ''' Create and configure the system object. '''
159
160    system = SimpleSeSystem(args)
161
162    # Tell components about the expected physical memory ranges. This
163    # is, for example, used by the MemConfig helper to determine where
164    # to map DRAMs in the physical address space.
165    system.mem_ranges = [ AddrRange(start=0, size=args.mem_size) ]
166
167    # Configure the off-chip memory system.
168    MemConfig.config_mem(args, system)
169
170    # Parse the command line and get a list of Processes instances
171    # that we can pass to gem5.
172    processes = get_processes(args.commands_to_run)
173    if len(processes) != args.num_cores:
174        print("Error: Cannot map %d command(s) onto %d CPU(s)" %
175              (len(processes), args.num_cores))
176        sys.exit(1)
177
178    # Assign one workload to each CPU
179    for cpu, workload in zip(system.cpu_cluster.cpus, processes):
180        cpu.workload = workload
181
182    return system
183
184
185def main():
186    parser = argparse.ArgumentParser(epilog=__doc__)
187
188    parser.add_argument("commands_to_run", metavar="command(s)", nargs='*',
189                        help="Command(s) to run")
190    parser.add_argument("--cpu", type=str, choices=cpu_types.keys(),
191                        default="atomic",
192                        help="CPU model to use")
193    parser.add_argument("--cpu-freq", type=str, default="4GHz")
194    parser.add_argument("--num-cores", type=int, default=1,
195                        help="Number of CPU cores")
196    parser.add_argument("--mem-type", default="DDR3_1600_8x8",
197                        choices=MemConfig.mem_names(),
198                        help = "type of memory to use")
199    parser.add_argument("--mem-channels", type=int, default=2,
200                        help = "number of memory channels")
201    parser.add_argument("--mem-ranks", type=int, default=None,
202                        help = "number of memory ranks per channel")
203    parser.add_argument("--mem-size", action="store", type=str,
204                        default="2GB",
205                        help="Specify the physical memory size")
206
207    args = parser.parse_args()
208
209    # Create a single root node for gem5's object hierarchy. There can
210    # only exist one root node in the simulator at any given
211    # time. Tell gem5 that we want to use syscall emulation mode
212    # instead of full system mode.
213    root = Root(full_system=False)
214
215    # Populate the root node with a system. A system corresponds to a
216    # single node with shared memory.
217    root.system = create(args)
218
219    # Instantiate the C++ object hierarchy. After this point,
220    # SimObjects can't be instantiated anymore.
221    m5.instantiate()
222
223    # Start the simulator. This gives control to the C++ world and
224    # starts the simulator. The returned event tells the simulation
225    # script why the simulator exited.
226    event = m5.simulate()
227
228    # Print the reason for the simulation exit. Some exit codes are
229    # requests for service (e.g., checkpoints) from the simulation
230    # script. We'll just ignore them here and exit.
231    print(event.getCause(), " @ ", m5.curTick())
232    sys.exit(event.getCode())
233
234
235if __name__ == "__m5_main__":
236    main()
237