Merge zizzer:/bk/newmem
[gem5.git] / src / python / m5 / __init__.py
1 # Copyright (c) 2005 The Regents of The University of Michigan
2 # All rights reserved.
3 #
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are
6 # met: redistributions of source code must retain the above copyright
7 # notice, this list of conditions and the following disclaimer;
8 # redistributions in binary form must reproduce the above copyright
9 # notice, this list of conditions and the following disclaimer in the
10 # documentation and/or other materials provided with the distribution;
11 # neither the name of the copyright holders nor the names of its
12 # contributors may be used to endorse or promote products derived from
13 # this software without specific prior written permission.
14 #
15 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 #
27 # Authors: Nathan Binkert
28 # Steve Reinhardt
29
30 import atexit
31 import os
32 import sys
33
34 # import the SWIG-wrapped main C++ functions
35 import internal
36 # import a few SWIG-wrapped items (those that are likely to be used
37 # directly by user scripts) completely into this module for
38 # convenience
39 import event
40
41 # import the m5 compile options
42 import defines
43
44 # define a MaxTick parameter
45 MaxTick = 2**63 - 1
46
47 # define this here so we can use it right away if necessary
48 def panic(string):
49 print >>sys.stderr, 'panic:', string
50 sys.exit(1)
51
52 # force scalars to one-element lists for uniformity
53 def makeList(objOrList):
54 if isinstance(objOrList, list):
55 return objOrList
56 return [objOrList]
57
58 # Prepend given directory to system module search path. We may not
59 # need this anymore if we can structure our config library more like a
60 # Python package.
61 def AddToPath(path):
62 # if it's a relative path and we know what directory the current
63 # python script is in, make the path relative to that directory.
64 if not os.path.isabs(path) and sys.path[0]:
65 path = os.path.join(sys.path[0], path)
66 path = os.path.realpath(path)
67 # sys.path[0] should always refer to the current script's directory,
68 # so place the new dir right after that.
69 sys.path.insert(1, path)
70
71 # make a SmartDict out of the build options for our local use
72 import smartdict
73 build_env = smartdict.SmartDict()
74 build_env.update(defines.m5_build_env)
75
76 # make a SmartDict out of the OS environment too
77 env = smartdict.SmartDict()
78 env.update(os.environ)
79
80 # The final hook to generate .ini files. Called from the user script
81 # once the config is built.
82 def instantiate(root):
83 # we need to fix the global frequency
84 ticks.fixGlobalFrequency()
85
86 root.unproxy_all()
87 # ugly temporary hack to get output to config.ini
88 sys.stdout = file(os.path.join(options.outdir, 'config.ini'), 'w')
89 root.print_ini()
90 sys.stdout.close() # close config.ini
91 sys.stdout = sys.__stdout__ # restore to original
92
93 # load config.ini into C++
94 internal.core.loadIniFile(resolveSimObject)
95
96 # Initialize the global statistics
97 internal.stats.initSimStats()
98
99 # Create the C++ sim objects and connect ports
100 root.createCCObject()
101 root.connectPorts()
102
103 # Do a second pass to finish initializing the sim objects
104 internal.sim_object.initAll()
105
106 # Do a third pass to initialize statistics
107 internal.sim_object.regAllStats()
108
109 # Check to make sure that the stats package is properly initialized
110 internal.stats.check()
111
112 # Reset to put the stats in a consistent state.
113 internal.stats.reset()
114
115 def 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
125 need_resume = []
126 need_startup = True
127 def simulate(*args, **kwargs):
128 global need_resume, need_startup
129
130 if need_startup:
131 internal.core.SimStartup()
132 need_startup = False
133
134 for root in need_resume:
135 resume(root)
136 need_resume = []
137
138 return internal.event.simulate(*args, **kwargs)
139
140 # Export curTick to user script.
141 def curTick():
142 return internal.core.cvar.curTick
143
144 # Python exit handlers happen in reverse order. We want to dump stats last.
145 atexit.register(internal.stats.dump)
146
147 # register our C++ exit callback function with Python
148 atexit.register(internal.core.doExitCleanup)
149
150 # This loops until all objects have been fully drained.
151 def doDrain(root):
152 all_drained = drain(root)
153 while (not all_drained):
154 all_drained = drain(root)
155
156 # Tries to drain all objects. Draining might not be completed unless
157 # all objects return that they are drained on the first call. This is
158 # because as objects drain they may cause other objects to no longer
159 # be drained.
160 def drain(root):
161 all_drained = False
162 drain_event = internal.event.createCountedDrain()
163 unready_objects = root.startDrain(drain_event, True)
164 # If we've got some objects that can't drain immediately, then simulate
165 if unready_objects > 0:
166 drain_event.setCount(unready_objects)
167 simulate()
168 else:
169 all_drained = True
170 internal.event.cleanupCountedDrain(drain_event)
171 return all_drained
172
173 def resume(root):
174 root.resume()
175
176 def checkpoint(root, dir):
177 if not isinstance(root, objects.Root):
178 raise TypeError, "Checkpoint must be called on a root object."
179 doDrain(root)
180 print "Writing checkpoint"
181 internal.sim_object.serializeAll(dir)
182 resume(root)
183
184 def restoreCheckpoint(root, dir):
185 print "Restoring from checkpoint"
186 internal.sim_object.unserializeAll(dir)
187 need_resume.append(root)
188
189 def changeToAtomic(system):
190 if not isinstance(system, (objects.Root, objects.System)):
191 raise TypeError, "Parameter of type '%s'. Must be type %s or %s." % \
192 (type(system), objects.Root, objects.System)
193 doDrain(system)
194 print "Changing memory mode to atomic"
195 system.changeTiming(internal.sim_object.SimObject.Atomic)
196
197 def changeToTiming(system):
198 if not isinstance(system, (objects.Root, objects.System)):
199 raise TypeError, "Parameter of type '%s'. Must be type %s or %s." % \
200 (type(system), objects.Root, objects.System)
201 doDrain(system)
202 print "Changing memory mode to timing"
203 system.changeTiming(internal.sim_object.SimObject.Timing)
204
205 def switchCpus(cpuList):
206 print "switching cpus"
207 if not isinstance(cpuList, list):
208 raise RuntimeError, "Must pass a list to this function"
209 for i in cpuList:
210 if not isinstance(i, tuple):
211 raise RuntimeError, "List must have tuples of (oldCPU,newCPU)"
212
213 [old_cpus, new_cpus] = zip(*cpuList)
214
215 for cpu in old_cpus:
216 if not isinstance(cpu, objects.BaseCPU):
217 raise TypeError, "%s is not of type BaseCPU" % cpu
218 for cpu in new_cpus:
219 if not isinstance(cpu, objects.BaseCPU):
220 raise TypeError, "%s is not of type BaseCPU" % cpu
221
222 # Drain all of the individual CPUs
223 drain_event = internal.event.createCountedDrain()
224 unready_cpus = 0
225 for old_cpu in old_cpus:
226 unready_cpus += old_cpu.startDrain(drain_event, False)
227 # If we've got some objects that can't drain immediately, then simulate
228 if unready_cpus > 0:
229 drain_event.setCount(unready_cpus)
230 simulate()
231 internal.event.cleanupCountedDrain(drain_event)
232 # Now all of the CPUs are ready to be switched out
233 for old_cpu in old_cpus:
234 old_cpu._ccObject.switchOut()
235 index = 0
236 for new_cpu in new_cpus:
237 new_cpu.takeOverFrom(old_cpus[index])
238 new_cpu._ccObject.resume()
239 index += 1
240
241 # Since we have so many mutual imports in this package, we should:
242 # 1. Put all intra-package imports at the *bottom* of the file, unless
243 # they're absolutely needed before that (for top-level statements
244 # or class attributes). Imports of "trivial" packages that don't
245 # import other packages (e.g., 'smartdict') can be at the top.
246 # 2. Never use 'from foo import *' on an intra-package import since
247 # you can get the wrong result if foo is only partially imported
248 # at the point you do that (i.e., because foo is in the middle of
249 # importing *you*).
250 from main import options
251 import objects
252 import params
253 from SimObject import resolveSimObject