Simulation.py revision 6107:52a5e1c63380
1# Copyright (c) 2006-2008 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: Lisa Hsu
28
29from os import getcwd
30from os.path import join as joinpath
31import m5
32from m5.objects import *
33m5.AddToPath('../common')
34
35def setCPUClass(options):
36
37    atomic = False
38    if options.timing:
39        class TmpClass(TimingSimpleCPU): pass
40    elif options.detailed:
41        if not options.caches:
42            print "O3 CPU must be used with caches"
43            sys.exit(1)
44        class TmpClass(DerivO3CPU): pass
45    elif options.inorder:
46        if not options.caches:
47            print "InOrder CPU must be used with caches"
48            sys.exit(1)
49        class TmpClass(InOrderCPU): pass
50    else:
51        class TmpClass(AtomicSimpleCPU): pass
52        atomic = True
53
54    CPUClass = None
55    test_mem_mode = 'atomic'
56
57    if not atomic:
58        if options.checkpoint_restore != None or options.fast_forward:
59            CPUClass = TmpClass
60            class TmpClass(AtomicSimpleCPU): pass
61        else:
62            test_mem_mode = 'timing'
63
64    return (TmpClass, test_mem_mode, CPUClass)
65
66
67def run(options, root, testsys, cpu_class):
68    if options.maxtick:
69        maxtick = options.maxtick
70    elif options.maxtime:
71        simtime = m5.ticks.seconds(simtime)
72        print "simulating for: ", simtime
73        maxtick = simtime
74    else:
75        maxtick = m5.MaxTick
76
77    if options.checkpoint_dir:
78        cptdir = options.checkpoint_dir
79    elif m5.options.outdir:
80        cptdir = m5.options.outdir
81    else:
82        cptdir = getcwd()
83
84    if options.fast_forward and options.checkpoint_restore != None:
85        m5.fatal("Error: Can't specify both --fast-forward and --checkpoint-restore")
86
87    if options.standard_switch and not options.caches:
88        m5.fatal("Error: Must specify --caches when using --standard-switch")
89
90    np = options.num_cpus
91    max_checkpoints = options.max_checkpoints
92    switch_cpus = None
93
94    if cpu_class:
95        switch_cpus = [cpu_class(defer_registration=True, cpu_id=(np+i))
96                       for i in xrange(np)]
97
98        for i in xrange(np):
99            if options.fast_forward:
100                testsys.cpu[i].max_insts_any_thread = int(options.fast_forward)
101            switch_cpus[i].system =  testsys
102            if not m5.build_env['FULL_SYSTEM']:
103                switch_cpus[i].workload = testsys.cpu[i].workload
104            switch_cpus[i].clock = testsys.cpu[0].clock
105            # simulation period
106            if options.max_inst:
107                switch_cpus[i].max_insts_any_thread = options.max_inst
108
109        testsys.switch_cpus = switch_cpus
110        switch_cpu_list = [(testsys.cpu[i], switch_cpus[i]) for i in xrange(np)]
111
112    if options.standard_switch:
113        switch_cpus = [TimingSimpleCPU(defer_registration=True, cpu_id=(np+i))
114                       for i in xrange(np)]
115        switch_cpus_1 = [DerivO3CPU(defer_registration=True, cpu_id=(2*np+i))
116                        for i in xrange(np)]
117
118        for i in xrange(np):
119            switch_cpus[i].system =  testsys
120            switch_cpus_1[i].system =  testsys
121            if not m5.build_env['FULL_SYSTEM']:
122                switch_cpus[i].workload = testsys.cpu[i].workload
123                switch_cpus_1[i].workload = testsys.cpu[i].workload
124            switch_cpus[i].clock = testsys.cpu[0].clock
125            switch_cpus_1[i].clock = testsys.cpu[0].clock
126
127            # if restoring, make atomic cpu simulate only a few instructions
128            if options.checkpoint_restore != None:
129                testsys.cpu[i].max_insts_any_thread = 1
130            # Fast forward to specified location if we are not restoring
131            elif options.fast_forward:
132                testsys.cpu[i].max_insts_any_thread = int(options.fast_forward)
133            # Fast forward to a simpoint (warning: time consuming)
134            elif options.simpoint:
135                if testsys.cpu[i].workload[0].simpoint == 0:
136                    m5.fatal('simpoint not found')
137                testsys.cpu[i].max_insts_any_thread = \
138                    testsys.cpu[i].workload[0].simpoint
139            # No distance specified, just switch
140            else:
141                testsys.cpu[i].max_insts_any_thread = 1
142
143            # warmup period
144            if options.warmup_insts:
145                switch_cpus[i].max_insts_any_thread =  options.warmup_insts
146
147            # simulation period
148            if options.max_inst:
149                switch_cpus_1[i].max_insts_any_thread = options.max_inst
150
151            if not options.caches:
152                # O3 CPU must have a cache to work.
153                print "O3 CPU must be used with caches"
154                sys.exit(1)
155
156            testsys.switch_cpus = switch_cpus
157            testsys.switch_cpus_1 = switch_cpus_1
158            switch_cpu_list = [(testsys.cpu[i], switch_cpus[i]) for i in xrange(np)]
159            switch_cpu_list1 = [(switch_cpus[i], switch_cpus_1[i]) for i in xrange(np)]
160
161    # set the checkpoint in the cpu before m5.instantiate is called
162    if options.take_checkpoints != None and \
163           (options.simpoint or options.at_instruction):
164        offset = int(options.take_checkpoints)
165        # Set an instruction break point
166        if options.simpoint:
167            for i in xrange(np):
168                if testsys.cpu[i].workload[0].simpoint == 0:
169                    m5.fatal('no simpoint for testsys.cpu[%d].workload[0]', i)
170                checkpoint_inst = int(testsys.cpu[i].workload[0].simpoint) + offset
171                testsys.cpu[i].max_insts_any_thread = checkpoint_inst
172                # used for output below
173                options.take_checkpoints = checkpoint_inst
174        else:
175            options.take_checkpoints = offset
176            # Set all test cpus with the right number of instructions
177            # for the upcoming simulation
178            for i in xrange(np):
179                testsys.cpu[i].max_insts_any_thread = offset
180
181    m5.instantiate(root)
182
183    if options.checkpoint_restore != None:
184        from os.path import isdir, exists
185        from os import listdir
186        import re
187
188        if not isdir(cptdir):
189            m5.fatal("checkpoint dir %s does not exist!", cptdir)
190
191        if options.at_instruction:
192            checkpoint_dir = joinpath(cptdir, "cpt.%s.%s" % \
193                    (options.bench, options.checkpoint_restore))
194            if not exists(checkpoint_dir):
195                m5.fatal("Unable to find checkpoint directory %s",
196                         checkpoint_dir)
197
198            print "Restoring checkpoint ..."
199            m5.restoreCheckpoint(root, checkpoint_dir)
200            print "Done."
201        elif options.simpoint:
202            # assume workload 0 has the simpoint
203            if testsys.cpu[0].workload[0].simpoint == 0:
204                m5.fatal('Unable to find simpoint')
205
206            options.checkpoint_restore += \
207                int(testsys.cpu[0].workload[0].simpoint)
208
209            checkpoint_dir = joinpath(cptdir, "cpt.%s.%d" % \
210                    (options.bench, options.checkpoint_restore))
211            if not exists(checkpoint_dir):
212                m5.fatal("Unable to find checkpoint directory %s.%s",
213                        options.bench, options.checkpoint_restore)
214
215            print "Restoring checkpoint ..."
216            m5.restoreCheckpoint(root,checkpoint_dir)
217            print "Done."
218        else:
219            dirs = listdir(cptdir)
220            expr = re.compile('cpt\.([0-9]*)')
221            cpts = []
222            for dir in dirs:
223                match = expr.match(dir)
224                if match:
225                    cpts.append(match.group(1))
226
227            cpts.sort(lambda a,b: cmp(long(a), long(b)))
228
229            cpt_num = options.checkpoint_restore
230
231            if cpt_num > len(cpts):
232                m5.fatal('Checkpoint %d not found', cpt_num)
233
234            ## Adjust max tick based on our starting tick
235            maxtick = maxtick - int(cpts[cpt_num - 1])
236
237            ## Restore the checkpoint
238            m5.restoreCheckpoint(root,
239                    joinpath(cptdir, "cpt.%s" % cpts[cpt_num - 1]))
240
241    if options.standard_switch or cpu_class:
242        if options.standard_switch:
243            print "Switch at instruction count:%s" % \
244                    str(testsys.cpu[0].max_insts_any_thread)
245            exit_event = m5.simulate()
246        elif cpu_class and options.fast_forward:
247            print "Switch at instruction count:%s" % \
248                    str(testsys.cpu[0].max_insts_any_thread)
249            exit_event = m5.simulate()
250        else:
251            print "Switch at curTick count:%s" % str(10000)
252            exit_event = m5.simulate(10000)
253        print "Switched CPUS @ cycle = %s" % (m5.curTick())
254
255        # when you change to Timing (or Atomic), you halt the system
256        # given as argument.  When you are finished with the system
257        # changes (including switchCpus), you must resume the system
258        # manually.  You DON'T need to resume after just switching
259        # CPUs if you haven't changed anything on the system level.
260
261        m5.changeToTiming(testsys)
262        m5.switchCpus(switch_cpu_list)
263        m5.resume(testsys)
264
265        if options.standard_switch:
266            print "Switch at instruction count:%d" % \
267                    (testsys.switch_cpus[0].max_insts_any_thread)
268
269            #warmup instruction count may have already been set
270            if options.warmup_insts:
271                exit_event = m5.simulate()
272            else:
273                exit_event = m5.simulate(options.warmup)
274            print "Switching CPUS @ cycle = %s" % (m5.curTick())
275            print "Simulation ends instruction count:%d" % \
276                    (testsys.switch_cpus_1[0].max_insts_any_thread)
277            m5.drain(testsys)
278            m5.switchCpus(switch_cpu_list1)
279            m5.resume(testsys)
280
281    num_checkpoints = 0
282    exit_cause = ''
283
284    # Checkpoints being taken via the command line at <when> and at
285    # subsequent periods of <period>.  Checkpoint instructions
286    # received from the benchmark running are ignored and skipped in
287    # favor of command line checkpoint instructions.
288    if options.take_checkpoints != None :
289        if options.at_instruction or options.simpoint:
290            checkpoint_inst = int(options.take_checkpoints)
291
292            # maintain correct offset if we restored from some instruction
293            if options.checkpoint_restore != None:
294                checkpoint_inst += options.checkpoint_restore
295
296            print "Creating checkpoint at inst:%d" % (checkpoint_inst)
297            exit_event = m5.simulate()
298            print "exit cause = %s" % (exit_event.getCause())
299
300            # skip checkpoint instructions should they exist
301            while exit_event.getCause() == "checkpoint":
302                exit_event = m5.simulate()
303
304            if exit_event.getCause() == \
305                   "a thread reached the max instruction count":
306                m5.checkpoint(root, joinpath(cptdir, "cpt.%s.%d" % \
307                        (options.bench, checkpoint_inst)))
308                print "Checkpoint written."
309                num_checkpoints += 1
310
311            if exit_event.getCause() == "user interrupt received":
312                exit_cause = exit_event.getCause();
313        else:
314            when, period = options.take_checkpoints.split(",", 1)
315            when = int(when)
316            period = int(period)
317
318            exit_event = m5.simulate(when)
319            while exit_event.getCause() == "checkpoint":
320                exit_event = m5.simulate(when - m5.curTick())
321
322            if exit_event.getCause() == "simulate() limit reached":
323                m5.checkpoint(root, joinpath(cptdir, "cpt.%d"))
324                num_checkpoints += 1
325
326            sim_ticks = when
327            exit_cause = "maximum %d checkpoints dropped" % max_checkpoints
328            while num_checkpoints < max_checkpoints and \
329                    exit_event.getCause() == "simulate() limit reached":
330                if (sim_ticks + period) > maxtick:
331                    exit_event = m5.simulate(maxtick - sim_ticks)
332                    exit_cause = exit_event.getCause()
333                    break
334                else:
335                    exit_event = m5.simulate(period)
336                    sim_ticks += period
337                    while exit_event.getCause() == "checkpoint":
338                        exit_event = m5.simulate(sim_ticks - m5.curTick())
339                    if exit_event.getCause() == "simulate() limit reached":
340                        m5.checkpoint(root, joinpath(cptdir, "cpt.%d"))
341                        num_checkpoints += 1
342
343            if exit_event.getCause() != "simulate() limit reached":
344                exit_cause = exit_event.getCause();
345
346    else: # no checkpoints being taken via this script
347        if options.fast_forward:
348            m5.stats.reset()
349        print "**** REAL SIMULATION ****"
350        exit_event = m5.simulate(maxtick)
351
352        while exit_event.getCause() == "checkpoint":
353            m5.checkpoint(root, joinpath(cptdir, "cpt.%d"))
354            num_checkpoints += 1
355            if num_checkpoints == max_checkpoints:
356                exit_cause = "maximum %d checkpoints dropped" % max_checkpoints
357                break
358
359            exit_event = m5.simulate(maxtick - m5.curTick())
360            exit_cause = exit_event.getCause()
361
362    if exit_cause == '':
363        exit_cause = exit_event.getCause()
364    print 'Exiting @ cycle %i because %s' % (m5.curTick(), exit_cause)
365
366