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 full system 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 *
53from m5.options import *
54import argparse
55
56m5.util.addToPath('../..')
57
58from common import SysPaths
59from common import MemConfig
60from common.cores.arm import HPI
61
62import devices
63
64
65default_dist_version = '20170616'
66default_kernel = 'vmlinux.vexpress_gem5_v1_64.' + default_dist_version
67default_disk = 'linaro-minimal-aarch64.img'
68
69
70# Pre-defined CPU configurations. Each tuple must be ordered as : (cpu_class,
71# l1_icache_class, l1_dcache_class, walk_cache_class, l2_Cache_class). Any of
72# the cache class may be 'None' if the particular cache is not present.
73cpu_types = {
74
75    "atomic" : ( AtomicSimpleCPU, None, None, None, None),
76    "minor" : (MinorCPU,
77               devices.L1I, devices.L1D,
78               devices.WalkCache,
79               devices.L2),
80    "hpi" : ( HPI.HPI,
81              HPI.HPI_ICache, HPI.HPI_DCache,
82              HPI.HPI_WalkCache,
83              HPI.HPI_L2)
84}
85
86def create_cow_image(name):
87    """Helper function to create a Copy-on-Write disk image"""
88    image = CowDiskImage()
89    image.child.image_file = SysPaths.disk(name)
90
91    return image;
92
93
94def create(args):
95    ''' Create and configure the system object. '''
96
97    if args.script and not os.path.isfile(args.script):
98        print("Error: Bootscript %s does not exist" % args.script)
99        sys.exit(1)
100
101    cpu_class = cpu_types[args.cpu][0]
102    mem_mode = cpu_class.memory_mode()
103    # Only simulate caches when using a timing CPU (e.g., the HPI model)
104    want_caches = True if mem_mode == "timing" else False
105
106    system = devices.SimpleSystem(want_caches,
107                                  args.mem_size,
108                                  mem_mode=mem_mode,
109                                  kernel=SysPaths.binary(args.kernel),
110                                  readfile=args.script)
111
112    MemConfig.config_mem(args, system)
113
114    # Add the PCI devices we need for this system. The base system
115    # doesn't have any PCI devices by default since they are assumed
116    # to be added by the configurastion scripts needin them.
117    system.pci_devices = [
118        # Create a VirtIO block device for the system's boot
119        # disk. Attach the disk image using gem5's Copy-on-Write
120        # functionality to avoid writing changes to the stored copy of
121        # the disk image.
122        PciVirtIO(vio=VirtIOBlock(image=create_cow_image(args.disk_image))),
123    ]
124
125    # Attach the PCI devices to the system. The helper method in the
126    # system assigns a unique PCI bus ID to each of the devices and
127    # connects them to the IO bus.
128    for dev in system.pci_devices:
129        system.attach_pci(dev)
130
131    # Wire up the system's memory system
132    system.connect()
133
134    # Add CPU clusters to the system
135    system.cpu_cluster = [
136        devices.CpuCluster(system,
137                           args.num_cores,
138                           args.cpu_freq, "1.0V",
139                           *cpu_types[args.cpu]),
140    ]
141
142    # Create a cache hierarchy for the cluster. We are assuming that
143    # clusters have core-private L1 caches and an L2 that's shared
144    # within the cluster.
145    for cluster in system.cpu_cluster:
146        system.addCaches(want_caches, last_cache_level=2)
147
148    # Setup gem5's minimal Linux boot loader.
149    system.realview.setupBootLoader(system.membus, system, SysPaths.binary)
150
151    if args.dtb:
152        system.dtb_filename = args.dtb
153    else:
154        # No DTB specified: autogenerate DTB
155        system.generateDtb(m5.options.outdir, 'system.dtb')
156
157    # Linux boot command flags
158    kernel_cmd = [
159        # Tell Linux to use the simulated serial port as a console
160        "console=ttyAMA0",
161        # Hard-code timi
162        "lpj=19988480",
163        # Disable address space randomisation to get a consistent
164        # memory layout.
165        "norandmaps",
166        # Tell Linux where to find the root disk image.
167        "root=/dev/vda1",
168        # Mount the root disk read-write by default.
169        "rw",
170        # Tell Linux about the amount of physical memory present.
171        "mem=%s" % args.mem_size,
172    ]
173    system.boot_osflags = " ".join(kernel_cmd)
174
175    return system
176
177
178def run(args):
179    cptdir = m5.options.outdir
180    if args.checkpoint:
181        print("Checkpoint directory: %s" % cptdir)
182
183    while True:
184        event = m5.simulate()
185        exit_msg = event.getCause()
186        if exit_msg == "checkpoint":
187            print("Dropping checkpoint at tick %d" % m5.curTick())
188            cpt_dir = os.path.join(m5.options.outdir, "cpt.%d" % m5.curTick())
189            m5.checkpoint(os.path.join(cpt_dir))
190            print("Checkpoint done.")
191        else:
192            print(exit_msg, " @ ", m5.curTick())
193            break
194
195    sys.exit(event.getCode())
196
197
198def main():
199    parser = argparse.ArgumentParser(epilog=__doc__)
200
201    parser.add_argument("--dtb", type=str, default=None,
202                        help="DTB file to load")
203    parser.add_argument("--kernel", type=str, default=default_kernel,
204                        help="Linux kernel")
205    parser.add_argument("--disk-image", type=str,
206                        default=default_disk,
207                        help="Disk to instantiate")
208    parser.add_argument("--script", type=str, default="",
209                        help = "Linux bootscript")
210    parser.add_argument("--cpu", type=str, choices=cpu_types.keys(),
211                        default="atomic",
212                        help="CPU model to use")
213    parser.add_argument("--cpu-freq", type=str, default="4GHz")
214    parser.add_argument("--num-cores", type=int, default=1,
215                        help="Number of CPU cores")
216    parser.add_argument("--mem-type", default="DDR3_1600_8x8",
217                        choices=MemConfig.mem_names(),
218                        help = "type of memory to use")
219    parser.add_argument("--mem-channels", type=int, default=1,
220                        help = "number of memory channels")
221    parser.add_argument("--mem-ranks", type=int, default=None,
222                        help = "number of memory ranks per channel")
223    parser.add_argument("--mem-size", action="store", type=str,
224                        default="2GB",
225                        help="Specify the physical memory size")
226    parser.add_argument("--checkpoint", action="store_true")
227    parser.add_argument("--restore", type=str, default=None)
228
229
230    args = parser.parse_args()
231
232    root = Root(full_system=True)
233    root.system = create(args)
234
235    if args.restore is not None:
236        m5.instantiate(args.restore)
237    else:
238        m5.instantiate()
239
240    run(args)
241
242
243if __name__ == "__m5_main__":
244    main()
245