simulate.py revision 8664:42052d5bb793
12086SN/A# Copyright (c) 2005 The Regents of The University of Michigan
22086SN/A# Copyright (c) 2010 Advanced Micro Devices, Inc.
35268Sksewell@umich.edu# All rights reserved.
42086SN/A#
52086SN/A# Redistribution and use in source and binary forms, with or without
62086SN/A# modification, are permitted provided that the following conditions are
72086SN/A# met: redistributions of source code must retain the above copyright
82086SN/A# notice, this list of conditions and the following disclaimer;
92086SN/A# redistributions in binary form must reproduce the above copyright
102086SN/A# notice, this list of conditions and the following disclaimer in the
112086SN/A# documentation and/or other materials provided with the distribution;
122086SN/A# neither the name of the copyright holders nor the names of its
132086SN/A# contributors may be used to endorse or promote products derived from
142086SN/A# this software without specific prior written permission.
152086SN/A#
162086SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
172086SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
182086SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
192086SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
202086SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
212086SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
222086SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
232086SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
242086SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
252086SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
262086SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
272086SN/A#
282665Ssaidi@eecs.umich.edu# Authors: Nathan Binkert
292665Ssaidi@eecs.umich.edu#          Steve Reinhardt
302665Ssaidi@eecs.umich.edu
312686Sksewell@umich.eduimport atexit
322086SN/Aimport os
334202Sbinkertn@umich.eduimport sys
342086SN/Aimport json
354202Sbinkertn@umich.edu
364202Sbinkertn@umich.edu# import the SWIG-wrapped main C++ functions
376313Sgblack@eecs.umich.eduimport internal
384997Sgblack@eecs.umich.eduimport core
395222Sksewell@umich.eduimport stats
404202Sbinkertn@umich.eduimport SimObject
415222Sksewell@umich.eduimport ticks
424997Sgblack@eecs.umich.eduimport objects
434997Sgblack@eecs.umich.edufrom util import fatal
445192Ssaidi@eecs.umich.edufrom util import attrdict
455192Ssaidi@eecs.umich.edu
464202Sbinkertn@umich.edu# define a MaxTick parameter
477799Sgblack@eecs.umich.eduMaxTick = 2**63 - 1
487799Sgblack@eecs.umich.edu
495222Sksewell@umich.edu# The final hook to generate .ini files.  Called from the user script
505222Sksewell@umich.edu# once the config is built.
515222Sksewell@umich.edudef instantiate(ckpt_dir=None):
525222Sksewell@umich.edu    from m5 import options
535222Sksewell@umich.edu
545222Sksewell@umich.edu    root = objects.Root.getInstance()
557799Sgblack@eecs.umich.edu
565222Sksewell@umich.edu    if not root:
574202Sbinkertn@umich.edu        fatal("Need to instantiate Root() before calling instantiate()")
584202Sbinkertn@umich.edu
594202Sbinkertn@umich.edu    # we need to fix the global frequency
604202Sbinkertn@umich.edu    ticks.fixGlobalFrequency()
612086SN/A
624202Sbinkertn@umich.edu    # Make sure SimObject-valued params are in the configuration
634202Sbinkertn@umich.edu    # hierarchy so we catch them with future descendants() walks
644202Sbinkertn@umich.edu    for obj in root.descendants(): obj.adoptOrphanParams()
654202Sbinkertn@umich.edu
664202Sbinkertn@umich.edu    # Unproxy in sorted order for determinism
674202Sbinkertn@umich.edu    for obj in root.descendants(): obj.unproxyParams()
68
69    if options.dump_config:
70        ini_file = file(os.path.join(options.outdir, options.dump_config), 'w')
71        # Print ini sections in sorted order for easier diffing
72        for obj in sorted(root.descendants(), key=lambda o: o.path()):
73            obj.print_ini(ini_file)
74        ini_file.close()
75
76    if options.json_config:
77        json_file = file(os.path.join(options.outdir, options.json_config), 'w')
78        d = root.get_config_as_dict()
79        json.dump(d, json_file, indent=4)
80        json_file.close()
81
82
83    # Initialize the global statistics
84    stats.initSimStats()
85
86    # Create the C++ sim objects and connect ports
87    for obj in root.descendants(): obj.createCCObject()
88    for obj in root.descendants(): obj.connectPorts()
89
90    # Do a second pass to finish initializing the sim objects
91    for obj in root.descendants(): obj.init()
92
93    # Do a third pass to initialize statistics
94    for obj in root.descendants(): obj.regStats()
95    for obj in root.descendants(): obj.regFormulas()
96
97    # We're done registering statistics.  Enable the stats package now.
98    stats.enable()
99
100    # Restore checkpoint (if any)
101    if ckpt_dir:
102        ckpt = internal.core.getCheckpoint(ckpt_dir)
103        internal.core.unserializeGlobals(ckpt);
104        for obj in root.descendants(): obj.loadState(ckpt)
105        need_resume.append(root)
106    else:
107        for obj in root.descendants(): obj.initState()
108
109    # Reset to put the stats in a consistent state.
110    stats.reset()
111
112def doDot(root):
113    dot = pydot.Dot()
114    instance.outputDot(dot)
115    dot.orientation = "portrait"
116    dot.size = "8.5,11"
117    dot.ranksep="equally"
118    dot.rank="samerank"
119    dot.write("config.dot")
120    dot.write_ps("config.ps")
121
122need_resume = []
123need_startup = True
124def simulate(*args, **kwargs):
125    global need_resume, need_startup
126
127    if need_startup:
128        root = objects.Root.getInstance()
129        for obj in root.descendants(): obj.startup()
130        need_startup = False
131
132    for root in need_resume:
133        resume(root)
134    need_resume = []
135
136    return internal.event.simulate(*args, **kwargs)
137
138# Export curTick to user script.
139def curTick():
140    return internal.core.curTick()
141
142# Python exit handlers happen in reverse order.  We want to dump stats last.
143atexit.register(stats.dump)
144
145# register our C++ exit callback function with Python
146atexit.register(internal.core.doExitCleanup)
147
148# This loops until all objects have been fully drained.
149def doDrain(root):
150    all_drained = drain(root)
151    while (not all_drained):
152        all_drained = drain(root)
153
154# Tries to drain all objects.  Draining might not be completed unless
155# all objects return that they are drained on the first call.  This is
156# because as objects drain they may cause other objects to no longer
157# be drained.
158def drain(root):
159    all_drained = False
160    drain_event = internal.event.createCountedDrain()
161    unready_objs = sum(obj.drain(drain_event) for obj in root.descendants())
162    # If we've got some objects that can't drain immediately, then simulate
163    if unready_objs > 0:
164        drain_event.setCount(unready_objs)
165        simulate()
166    else:
167        all_drained = True
168    internal.event.cleanupCountedDrain(drain_event)
169    return all_drained
170
171def resume(root):
172    for obj in root.descendants(): obj.resume()
173
174def checkpoint(dir):
175    root = objects.Root.getInstance()
176    if not isinstance(root, objects.Root):
177        raise TypeError, "Checkpoint must be called on a root object."
178    doDrain(root)
179    print "Writing checkpoint"
180    internal.core.serializeAll(dir)
181    resume(root)
182
183def changeToAtomic(system):
184    if not isinstance(system, (objects.Root, objects.System)):
185        raise TypeError, "Parameter of type '%s'.  Must be type %s or %s." % \
186              (type(system), objects.Root, objects.System)
187    if system.getMemoryMode() != objects.params.atomic:
188        doDrain(system)
189        print "Changing memory mode to atomic"
190        for obj in system.descendants():
191            obj.changeTiming(objects.params.atomic)
192
193def changeToTiming(system):
194    if not isinstance(system, (objects.Root, objects.System)):
195        raise TypeError, "Parameter of type '%s'.  Must be type %s or %s." % \
196              (type(system), objects.Root, objects.System)
197
198    if system.getMemoryMode() != objects.params.timing:
199        doDrain(system)
200        print "Changing memory mode to timing"
201        for obj in system.descendants():
202            obj.changeTiming(objects.params.timing)
203
204def switchCpus(cpuList):
205    print "switching cpus"
206    if not isinstance(cpuList, list):
207        raise RuntimeError, "Must pass a list to this function"
208    for item in cpuList:
209        if not isinstance(item, tuple) or len(item) != 2:
210            raise RuntimeError, "List must have tuples of (oldCPU,newCPU)"
211
212    for old_cpu, new_cpu in cpuList:
213        if not isinstance(old_cpu, objects.BaseCPU):
214            raise TypeError, "%s is not of type BaseCPU" % old_cpu
215        if not isinstance(new_cpu, objects.BaseCPU):
216            raise TypeError, "%s is not of type BaseCPU" % new_cpu
217
218    # Now all of the CPUs are ready to be switched out
219    for old_cpu, new_cpu in cpuList:
220        old_cpu._ccObject.switchOut()
221
222    for old_cpu, new_cpu in cpuList:
223        new_cpu.takeOverFrom(old_cpu)
224
225from internal.core import disableAllListeners
226