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