simulate.py (8998:c8bf5a20bc07) simulate.py (8999:6f306dd5cee0)
1# Copyright (c) 2012 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#
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
13# Copyright (c) 2005 The Regents of The University of Michigan
14# Copyright (c) 2010 Advanced Micro Devices, Inc.
15# All rights reserved.
16#
17# Redistribution and use in source and binary forms, with or without
18# modification, are permitted provided that the following conditions are
19# met: redistributions of source code must retain the above copyright
20# notice, this list of conditions and the following disclaimer;
21# redistributions in binary form must reproduce the above copyright
22# notice, this list of conditions and the following disclaimer in the
23# documentation and/or other materials provided with the distribution;
24# neither the name of the copyright holders nor the names of its
25# contributors may be used to endorse or promote products derived from
26# this software without specific prior written permission.
27#
28# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39#
40# Authors: Nathan Binkert
41# Steve Reinhardt
42
43import atexit
44import os
45import sys
46
35try:
36 import pydot
37except:
38 pydot = False
39
40
41# import the SWIG-wrapped main C++ functions
42import internal
43import core
44import stats
45import SimObject
46import ticks
47import objects
47# import the SWIG-wrapped main C++ functions
48import internal
49import core
50import stats
51import SimObject
52import ticks
53import objects
54from m5.util.dot_writer import do_dot
55
48from util import fatal
49from util import attrdict
50
51# define a MaxTick parameter
52MaxTick = 2**63 - 1
53
54# The final hook to generate .ini files. Called from the user script
55# once the config is built.
56def instantiate(ckpt_dir=None):
57 from m5 import options
58
59 root = objects.Root.getInstance()
60
61 if not root:
62 fatal("Need to instantiate Root() before calling instantiate()")
63
64 # we need to fix the global frequency
65 ticks.fixGlobalFrequency()
66
67 # Make sure SimObject-valued params are in the configuration
68 # hierarchy so we catch them with future descendants() walks
69 for obj in root.descendants(): obj.adoptOrphanParams()
70
71 # Unproxy in sorted order for determinism
72 for obj in root.descendants(): obj.unproxyParams()
73
74 if options.dump_config:
75 ini_file = file(os.path.join(options.outdir, options.dump_config), 'w')
76 # Print ini sections in sorted order for easier diffing
77 for obj in sorted(root.descendants(), key=lambda o: o.path()):
78 obj.print_ini(ini_file)
79 ini_file.close()
80
81 if options.json_config:
82 try:
83 import json
84 json_file = file(os.path.join(options.outdir, options.json_config), 'w')
85 d = root.get_config_as_dict()
86 json.dump(d, json_file, indent=4)
87 json_file.close()
88 except ImportError:
89 pass
90
56from util import fatal
57from util import attrdict
58
59# define a MaxTick parameter
60MaxTick = 2**63 - 1
61
62# The final hook to generate .ini files. Called from the user script
63# once the config is built.
64def instantiate(ckpt_dir=None):
65 from m5 import options
66
67 root = objects.Root.getInstance()
68
69 if not root:
70 fatal("Need to instantiate Root() before calling instantiate()")
71
72 # we need to fix the global frequency
73 ticks.fixGlobalFrequency()
74
75 # Make sure SimObject-valued params are in the configuration
76 # hierarchy so we catch them with future descendants() walks
77 for obj in root.descendants(): obj.adoptOrphanParams()
78
79 # Unproxy in sorted order for determinism
80 for obj in root.descendants(): obj.unproxyParams()
81
82 if options.dump_config:
83 ini_file = file(os.path.join(options.outdir, options.dump_config), 'w')
84 # Print ini sections in sorted order for easier diffing
85 for obj in sorted(root.descendants(), key=lambda o: o.path()):
86 obj.print_ini(ini_file)
87 ini_file.close()
88
89 if options.json_config:
90 try:
91 import json
92 json_file = file(os.path.join(options.outdir, options.json_config), 'w')
93 d = root.get_config_as_dict()
94 json.dump(d, json_file, indent=4)
95 json_file.close()
96 except ImportError:
97 pass
98
91 if pydot:
92 doDot(root)
99 do_dot(root, options.outdir, options.dot_config)
93
94 # Initialize the global statistics
95 stats.initSimStats()
96
97 # Create the C++ sim objects and connect ports
98 for obj in root.descendants(): obj.createCCObject()
99 for obj in root.descendants(): obj.connectPorts()
100
101 # Do a second pass to finish initializing the sim objects
102 for obj in root.descendants(): obj.init()
103
104 # Do a third pass to initialize statistics
105 for obj in root.descendants(): obj.regStats()
106 for obj in root.descendants(): obj.regFormulas()
107
108 # We're done registering statistics. Enable the stats package now.
109 stats.enable()
110
111 # Restore checkpoint (if any)
112 if ckpt_dir:
113 ckpt = internal.core.getCheckpoint(ckpt_dir)
114 internal.core.unserializeGlobals(ckpt);
115 for obj in root.descendants(): obj.loadState(ckpt)
116 need_resume.append(root)
117 else:
118 for obj in root.descendants(): obj.initState()
119
120 # Reset to put the stats in a consistent state.
121 stats.reset()
122
100
101 # Initialize the global statistics
102 stats.initSimStats()
103
104 # Create the C++ sim objects and connect ports
105 for obj in root.descendants(): obj.createCCObject()
106 for obj in root.descendants(): obj.connectPorts()
107
108 # Do a second pass to finish initializing the sim objects
109 for obj in root.descendants(): obj.init()
110
111 # Do a third pass to initialize statistics
112 for obj in root.descendants(): obj.regStats()
113 for obj in root.descendants(): obj.regFormulas()
114
115 # We're done registering statistics. Enable the stats package now.
116 stats.enable()
117
118 # Restore checkpoint (if any)
119 if ckpt_dir:
120 ckpt = internal.core.getCheckpoint(ckpt_dir)
121 internal.core.unserializeGlobals(ckpt);
122 for obj in root.descendants(): obj.loadState(ckpt)
123 need_resume.append(root)
124 else:
125 for obj in root.descendants(): obj.initState()
126
127 # Reset to put the stats in a consistent state.
128 stats.reset()
129
123def doDot(root):
124 from m5 import options
125 dot = pydot.Dot()
126 root.outputDot(dot)
127 dot.orientation = "portrait"
128 dot.size = "8.5,11"
129 dot.ranksep="equally"
130 dot.rank="samerank"
131 dot_filename = os.path.join(options.outdir, options.dot_config)
132 dot.write(dot_filename)
133 dot.write_pdf(dot_filename + ".pdf")
134
135need_resume = []
136need_startup = True
137def simulate(*args, **kwargs):
138 global need_resume, need_startup
139
140 if need_startup:
141 root = objects.Root.getInstance()
142 for obj in root.descendants(): obj.startup()
143 need_startup = False
144
145 for root in need_resume:
146 resume(root)
147 need_resume = []
148
149 return internal.event.simulate(*args, **kwargs)
150
151# Export curTick to user script.
152def curTick():
153 return internal.core.curTick()
154
155# Python exit handlers happen in reverse order. We want to dump stats last.
156atexit.register(stats.dump)
157
158# register our C++ exit callback function with Python
159atexit.register(internal.core.doExitCleanup)
160
161# This loops until all objects have been fully drained.
162def doDrain(root):
163 all_drained = drain(root)
164 while (not all_drained):
165 all_drained = drain(root)
166
167# Tries to drain all objects. Draining might not be completed unless
168# all objects return that they are drained on the first call. This is
169# because as objects drain they may cause other objects to no longer
170# be drained.
171def drain(root):
172 all_drained = False
173 drain_event = internal.event.createCountedDrain()
174 unready_objs = sum(obj.drain(drain_event) for obj in root.descendants())
175 # If we've got some objects that can't drain immediately, then simulate
176 if unready_objs > 0:
177 drain_event.setCount(unready_objs)
178 simulate()
179 else:
180 all_drained = True
181 internal.event.cleanupCountedDrain(drain_event)
182 return all_drained
183
184def resume(root):
185 for obj in root.descendants(): obj.resume()
186
187def checkpoint(dir):
188 root = objects.Root.getInstance()
189 if not isinstance(root, objects.Root):
190 raise TypeError, "Checkpoint must be called on a root object."
191 doDrain(root)
192 print "Writing checkpoint"
193 internal.core.serializeAll(dir)
194 resume(root)
195
196def changeToAtomic(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 if system.getMemoryMode() != objects.params.atomic:
201 doDrain(system)
202 print "Changing memory mode to atomic"
203 for obj in system.descendants():
204 obj.changeTiming(objects.params.atomic)
205
206def changeToTiming(system):
207 if not isinstance(system, (objects.Root, objects.System)):
208 raise TypeError, "Parameter of type '%s'. Must be type %s or %s." % \
209 (type(system), objects.Root, objects.System)
210
211 if system.getMemoryMode() != objects.params.timing:
212 doDrain(system)
213 print "Changing memory mode to timing"
214 for obj in system.descendants():
215 obj.changeTiming(objects.params.timing)
216
217def switchCpus(cpuList):
218 print "switching cpus"
219 if not isinstance(cpuList, list):
220 raise RuntimeError, "Must pass a list to this function"
221 for item in cpuList:
222 if not isinstance(item, tuple) or len(item) != 2:
223 raise RuntimeError, "List must have tuples of (oldCPU,newCPU)"
224
225 for old_cpu, new_cpu in cpuList:
226 if not isinstance(old_cpu, objects.BaseCPU):
227 raise TypeError, "%s is not of type BaseCPU" % old_cpu
228 if not isinstance(new_cpu, objects.BaseCPU):
229 raise TypeError, "%s is not of type BaseCPU" % new_cpu
230
231 # Now all of the CPUs are ready to be switched out
232 for old_cpu, new_cpu in cpuList:
233 old_cpu._ccObject.switchOut()
234
235 for old_cpu, new_cpu in cpuList:
236 new_cpu.takeOverFrom(old_cpu)
237
238from internal.core import disableAllListeners
130need_resume = []
131need_startup = True
132def simulate(*args, **kwargs):
133 global need_resume, need_startup
134
135 if need_startup:
136 root = objects.Root.getInstance()
137 for obj in root.descendants(): obj.startup()
138 need_startup = False
139
140 for root in need_resume:
141 resume(root)
142 need_resume = []
143
144 return internal.event.simulate(*args, **kwargs)
145
146# Export curTick to user script.
147def curTick():
148 return internal.core.curTick()
149
150# Python exit handlers happen in reverse order. We want to dump stats last.
151atexit.register(stats.dump)
152
153# register our C++ exit callback function with Python
154atexit.register(internal.core.doExitCleanup)
155
156# This loops until all objects have been fully drained.
157def doDrain(root):
158 all_drained = drain(root)
159 while (not all_drained):
160 all_drained = drain(root)
161
162# Tries to drain all objects. Draining might not be completed unless
163# all objects return that they are drained on the first call. This is
164# because as objects drain they may cause other objects to no longer
165# be drained.
166def drain(root):
167 all_drained = False
168 drain_event = internal.event.createCountedDrain()
169 unready_objs = sum(obj.drain(drain_event) for obj in root.descendants())
170 # If we've got some objects that can't drain immediately, then simulate
171 if unready_objs > 0:
172 drain_event.setCount(unready_objs)
173 simulate()
174 else:
175 all_drained = True
176 internal.event.cleanupCountedDrain(drain_event)
177 return all_drained
178
179def resume(root):
180 for obj in root.descendants(): obj.resume()
181
182def checkpoint(dir):
183 root = objects.Root.getInstance()
184 if not isinstance(root, objects.Root):
185 raise TypeError, "Checkpoint must be called on a root object."
186 doDrain(root)
187 print "Writing checkpoint"
188 internal.core.serializeAll(dir)
189 resume(root)
190
191def changeToAtomic(system):
192 if not isinstance(system, (objects.Root, objects.System)):
193 raise TypeError, "Parameter of type '%s'. Must be type %s or %s." % \
194 (type(system), objects.Root, objects.System)
195 if system.getMemoryMode() != objects.params.atomic:
196 doDrain(system)
197 print "Changing memory mode to atomic"
198 for obj in system.descendants():
199 obj.changeTiming(objects.params.atomic)
200
201def changeToTiming(system):
202 if not isinstance(system, (objects.Root, objects.System)):
203 raise TypeError, "Parameter of type '%s'. Must be type %s or %s." % \
204 (type(system), objects.Root, objects.System)
205
206 if system.getMemoryMode() != objects.params.timing:
207 doDrain(system)
208 print "Changing memory mode to timing"
209 for obj in system.descendants():
210 obj.changeTiming(objects.params.timing)
211
212def switchCpus(cpuList):
213 print "switching cpus"
214 if not isinstance(cpuList, list):
215 raise RuntimeError, "Must pass a list to this function"
216 for item in cpuList:
217 if not isinstance(item, tuple) or len(item) != 2:
218 raise RuntimeError, "List must have tuples of (oldCPU,newCPU)"
219
220 for old_cpu, new_cpu in cpuList:
221 if not isinstance(old_cpu, objects.BaseCPU):
222 raise TypeError, "%s is not of type BaseCPU" % old_cpu
223 if not isinstance(new_cpu, objects.BaseCPU):
224 raise TypeError, "%s is not of type BaseCPU" % new_cpu
225
226 # Now all of the CPUs are ready to be switched out
227 for old_cpu, new_cpu in cpuList:
228 old_cpu._ccObject.switchOut()
229
230 for old_cpu, new_cpu in cpuList:
231 new_cpu.takeOverFrom(old_cpu)
232
233from internal.core import disableAllListeners