__init__.py revision 4553:fac59b75a87d
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
30import atexit
31import os
32import sys
33
34# import the SWIG-wrapped main C++ functions
35import 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
39import event
40
41# import the m5 compile options
42import defines
43
44# define a MaxTick parameter
45MaxTick = 2**63 - 1
46
47# define this here so we can use it right away if necessary
48def panic(string):
49    print >>sys.stderr, 'panic:', string
50    sys.exit(1)
51
52# force scalars to one-element lists for uniformity
53def 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.
61def 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
72import smartdict
73build_env = smartdict.SmartDict()
74build_env.update(defines.m5_build_env)
75
76# make a SmartDict out of the OS environment too
77env = smartdict.SmartDict()
78env.update(os.environ)
79
80# The final hook to generate .ini files.  Called from the user script
81# once the config is built.
82def 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
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        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.
141def curTick():
142    return internal.core.cvar.curTick
143
144# Python exit handlers happen in reverse order.  We want to dump stats last.
145atexit.register(internal.stats.dump)
146
147# register our C++ exit callback function with Python
148atexit.register(internal.core.doExitCleanup)
149
150# This loops until all objects have been fully drained.
151def 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.
160def 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
173def resume(root):
174    root.resume()
175
176def 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
184def restoreCheckpoint(root, dir):
185    print "Restoring from checkpoint"
186    internal.sim_object.unserializeAll(dir)
187    need_resume.append(root)
188
189def 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    if system.getMemoryMode() != internal.sim_object.SimObject.Atomic:
194        doDrain(system)
195        print "Changing memory mode to atomic"
196        system.changeTiming(internal.sim_object.SimObject.Atomic)
197
198def changeToTiming(system):
199    if not isinstance(system, (objects.Root, objects.System)):
200        raise TypeError, "Parameter of type '%s'.  Must be type %s or %s." % \
201              (type(system), objects.Root, objects.System)
202
203    if system.getMemoryMode() != internal.sim_object.SimObject.Timing:
204        doDrain(system)
205        print "Changing memory mode to timing"
206        system.changeTiming(internal.sim_object.SimObject.Timing)
207
208def switchCpus(cpuList):
209    print "switching cpus"
210    if not isinstance(cpuList, list):
211        raise RuntimeError, "Must pass a list to this function"
212    for i in cpuList:
213        if not isinstance(i, tuple):
214            raise RuntimeError, "List must have tuples of (oldCPU,newCPU)"
215
216    [old_cpus, new_cpus] = zip(*cpuList)
217
218    for cpu in old_cpus:
219        if not isinstance(cpu, objects.BaseCPU):
220            raise TypeError, "%s is not of type BaseCPU" % cpu
221    for cpu in new_cpus:
222        if not isinstance(cpu, objects.BaseCPU):
223            raise TypeError, "%s is not of type BaseCPU" % cpu
224
225    # Drain all of the individual CPUs
226    drain_event = internal.event.createCountedDrain()
227    unready_cpus = 0
228    for old_cpu in old_cpus:
229        unready_cpus += old_cpu.startDrain(drain_event, False)
230    # If we've got some objects that can't drain immediately, then simulate
231    if unready_cpus > 0:
232        drain_event.setCount(unready_cpus)
233        simulate()
234    internal.event.cleanupCountedDrain(drain_event)
235    # Now all of the CPUs are ready to be switched out
236    for old_cpu in old_cpus:
237        old_cpu._ccObject.switchOut()
238    index = 0
239    for new_cpu in new_cpus:
240        new_cpu.takeOverFrom(old_cpus[index])
241        new_cpu._ccObject.resume()
242        index += 1
243
244# Since we have so many mutual imports in this package, we should:
245# 1. Put all intra-package imports at the *bottom* of the file, unless
246#    they're absolutely needed before that (for top-level statements
247#    or class attributes).  Imports of "trivial" packages that don't
248#    import other packages (e.g., 'smartdict') can be at the top.
249# 2. Never use 'from foo import *' on an intra-package import since
250#    you can get the wrong result if foo is only partially imported
251#    at the point you do that (i.e., because foo is in the middle of
252#    importing *you*).
253from main import options
254import objects
255import params
256from SimObject import resolveSimObject
257