simulate.py revision 8675:fd3f7091a5cf
1# Copyright (c) 2005 The Regents of The University of Michigan
2# Copyright (c) 2010 Advanced Micro Devices, Inc.
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: Nathan Binkert
29#          Steve Reinhardt
30
31import atexit
32import os
33import sys
34
35# import the SWIG-wrapped main C++ functions
36import internal
37import core
38import stats
39import SimObject
40import ticks
41import objects
42from util import fatal
43from util import attrdict
44
45# define a MaxTick parameter
46MaxTick = 2**63 - 1
47
48# The final hook to generate .ini files.  Called from the user script
49# once the config is built.
50def instantiate(ckpt_dir=None):
51    from m5 import options
52
53    root = objects.Root.getInstance()
54
55    if not root:
56        fatal("Need to instantiate Root() before calling instantiate()")
57
58    # we need to fix the global frequency
59    ticks.fixGlobalFrequency()
60
61    # Make sure SimObject-valued params are in the configuration
62    # hierarchy so we catch them with future descendants() walks
63    for obj in root.descendants(): obj.adoptOrphanParams()
64
65    # Unproxy in sorted order for determinism
66    for obj in root.descendants(): obj.unproxyParams()
67
68    if options.dump_config:
69        ini_file = file(os.path.join(options.outdir, options.dump_config), 'w')
70        # Print ini sections in sorted order for easier diffing
71        for obj in sorted(root.descendants(), key=lambda o: o.path()):
72            obj.print_ini(ini_file)
73        ini_file.close()
74
75    if options.json_config:
76        try:
77            import json
78            json_file = file(os.path.join(options.outdir, options.json_config), 'w')
79            d = root.get_config_as_dict()
80            json.dump(d, json_file, indent=4)
81            json_file.close()
82        except ImportError:
83            pass
84
85
86    # Initialize the global statistics
87    stats.initSimStats()
88
89    # Create the C++ sim objects and connect ports
90    for obj in root.descendants(): obj.createCCObject()
91    for obj in root.descendants(): obj.connectPorts()
92
93    # Do a second pass to finish initializing the sim objects
94    for obj in root.descendants(): obj.init()
95
96    # Do a third pass to initialize statistics
97    for obj in root.descendants(): obj.regStats()
98    for obj in root.descendants(): obj.regFormulas()
99
100    # We're done registering statistics.  Enable the stats package now.
101    stats.enable()
102
103    # Restore checkpoint (if any)
104    if ckpt_dir:
105        ckpt = internal.core.getCheckpoint(ckpt_dir)
106        internal.core.unserializeGlobals(ckpt);
107        for obj in root.descendants(): obj.loadState(ckpt)
108        need_resume.append(root)
109    else:
110        for obj in root.descendants(): obj.initState()
111
112    # Reset to put the stats in a consistent state.
113    stats.reset()
114
115def doDot(root):
116    dot = pydot.Dot()
117    instance.outputDot(dot)
118    dot.orientation = "portrait"
119    dot.size = "8.5,11"
120    dot.ranksep="equally"
121    dot.rank="samerank"
122    dot.write("config.dot")
123    dot.write_ps("config.ps")
124
125need_resume = []
126need_startup = True
127def simulate(*args, **kwargs):
128    global need_resume, need_startup
129
130    if need_startup:
131        root = objects.Root.getInstance()
132        for obj in root.descendants(): obj.startup()
133        need_startup = False
134
135    for root in need_resume:
136        resume(root)
137    need_resume = []
138
139    return internal.event.simulate(*args, **kwargs)
140
141# Export curTick to user script.
142def curTick():
143    return internal.core.curTick()
144
145# Python exit handlers happen in reverse order.  We want to dump stats last.
146atexit.register(stats.dump)
147
148# register our C++ exit callback function with Python
149atexit.register(internal.core.doExitCleanup)
150
151# This loops until all objects have been fully drained.
152def doDrain(root):
153    all_drained = drain(root)
154    while (not all_drained):
155        all_drained = drain(root)
156
157# Tries to drain all objects.  Draining might not be completed unless
158# all objects return that they are drained on the first call.  This is
159# because as objects drain they may cause other objects to no longer
160# be drained.
161def drain(root):
162    all_drained = False
163    drain_event = internal.event.createCountedDrain()
164    unready_objs = sum(obj.drain(drain_event) for obj in root.descendants())
165    # If we've got some objects that can't drain immediately, then simulate
166    if unready_objs > 0:
167        drain_event.setCount(unready_objs)
168        simulate()
169    else:
170        all_drained = True
171    internal.event.cleanupCountedDrain(drain_event)
172    return all_drained
173
174def resume(root):
175    for obj in root.descendants(): obj.resume()
176
177def checkpoint(dir):
178    root = objects.Root.getInstance()
179    if not isinstance(root, objects.Root):
180        raise TypeError, "Checkpoint must be called on a root object."
181    doDrain(root)
182    print "Writing checkpoint"
183    internal.core.serializeAll(dir)
184    resume(root)
185
186def changeToAtomic(system):
187    if not isinstance(system, (objects.Root, objects.System)):
188        raise TypeError, "Parameter of type '%s'.  Must be type %s or %s." % \
189              (type(system), objects.Root, objects.System)
190    if system.getMemoryMode() != objects.params.atomic:
191        doDrain(system)
192        print "Changing memory mode to atomic"
193        for obj in system.descendants():
194            obj.changeTiming(objects.params.atomic)
195
196def changeToTiming(system):
197    if not isinstance(system, (objects.Root, objects.System)):
198        raise TypeError, "Parameter of type '%s'.  Must be type %s or %s." % \
199              (type(system), objects.Root, objects.System)
200
201    if system.getMemoryMode() != objects.params.timing:
202        doDrain(system)
203        print "Changing memory mode to timing"
204        for obj in system.descendants():
205            obj.changeTiming(objects.params.timing)
206
207def switchCpus(cpuList):
208    print "switching cpus"
209    if not isinstance(cpuList, list):
210        raise RuntimeError, "Must pass a list to this function"
211    for item in cpuList:
212        if not isinstance(item, tuple) or len(item) != 2:
213            raise RuntimeError, "List must have tuples of (oldCPU,newCPU)"
214
215    for old_cpu, new_cpu in cpuList:
216        if not isinstance(old_cpu, objects.BaseCPU):
217            raise TypeError, "%s is not of type BaseCPU" % old_cpu
218        if not isinstance(new_cpu, objects.BaseCPU):
219            raise TypeError, "%s is not of type BaseCPU" % new_cpu
220
221    # Now all of the CPUs are ready to be switched out
222    for old_cpu, new_cpu in cpuList:
223        old_cpu._ccObject.switchOut()
224
225    for old_cpu, new_cpu in cpuList:
226        new_cpu.takeOverFrom(old_cpu)
227
228from internal.core import disableAllListeners
229